repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/api_keys.rs | crates/router/src/core/api_keys.rs | use common_utils::date_time;
#[cfg(feature = "email")]
use diesel_models::{api_keys::ApiKey, enums as storage_enums};
use error_stack::{report, ResultExt};
use masking::{PeekInterface, StrongSecret};
use router_env::{instrument, tracing};
use crate::{
configs::settings,
consts,
core::errors::{self, RouterResponse, StorageErrorExt},
db::domain,
routes::{metrics, SessionState},
services::{authentication, ApplicationResponse},
types::{api, storage, transformers::ForeignInto},
};
#[cfg(feature = "email")]
const API_KEY_EXPIRY_TAG: &str = "API_KEY";
#[cfg(feature = "email")]
const API_KEY_EXPIRY_NAME: &str = "API_KEY_EXPIRY";
#[cfg(feature = "email")]
const API_KEY_EXPIRY_RUNNER: diesel_models::ProcessTrackerRunner =
diesel_models::ProcessTrackerRunner::ApiKeyExpiryWorkflow;
static HASH_KEY: once_cell::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> =
once_cell::sync::OnceCell::new();
impl settings::ApiKeys {
pub fn get_hash_key(
&self,
) -> errors::RouterResult<&'static StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> {
HASH_KEY.get_or_try_init(|| {
<[u8; PlaintextApiKey::HASH_KEY_LEN]>::try_from(
hex::decode(self.hash_key.peek())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("API key hash key has invalid hexadecimal data")?
.as_slice(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The API hashing key has incorrect length")
.map(StrongSecret::new)
})
}
}
// Defining new types `PlaintextApiKey` and `HashedApiKey` in the hopes of reducing the possibility
// of plaintext API key being stored in the data store.
pub struct PlaintextApiKey(StrongSecret<String>);
#[derive(Debug, PartialEq, Eq)]
pub struct HashedApiKey(String);
impl PlaintextApiKey {
const HASH_KEY_LEN: usize = 32;
const PREFIX_LEN: usize = 12;
pub fn new(length: usize) -> Self {
let env = router_env::env::prefix_for_env();
let key = common_utils::crypto::generate_cryptographically_secure_random_string(length);
Self(format!("{env}_{key}").into())
}
pub fn new_key_id() -> common_utils::id_type::ApiKeyId {
let env = router_env::env::prefix_for_env();
common_utils::id_type::ApiKeyId::generate_key_id(env)
}
pub fn prefix(&self) -> String {
self.0.peek().chars().take(Self::PREFIX_LEN).collect()
}
pub fn peek(&self) -> &str {
self.0.peek()
}
pub fn keyed_hash(&self, key: &[u8; Self::HASH_KEY_LEN]) -> HashedApiKey {
/*
Decisions regarding API key hashing algorithm chosen:
- Since API key hash verification would be done for each request, there is a requirement
for the hashing to be quick.
- Password hashing algorithms would not be suitable for this purpose as they're designed to
prevent brute force attacks, considering that the same password could be shared across
multiple sites by the user.
- Moreover, password hash verification happens once per user session, so the delay involved
is negligible, considering the security benefits it provides.
While with API keys (assuming uniqueness of keys across the application), the delay
involved in hashing (with the use of a password hashing algorithm) becomes significant,
considering that it must be done per request.
- Since we are the only ones generating API keys and are able to guarantee their uniqueness,
a simple hash algorithm is sufficient for this purpose.
Hash algorithms considered:
- Password hashing algorithms: Argon2id and PBKDF2
- Simple hashing algorithms: HMAC-SHA256, HMAC-SHA512, BLAKE3
After benchmarking the simple hashing algorithms, we decided to go with the BLAKE3 keyed
hashing algorithm, with a randomly generated key for the hash key.
*/
HashedApiKey(
blake3::keyed_hash(key, self.0.peek().as_bytes())
.to_hex()
.to_string(),
)
}
}
#[instrument(skip_all)]
pub async fn create_api_key(
state: SessionState,
api_key: api::CreateApiKeyRequest,
key_store: domain::MerchantKeyStore,
) -> RouterResponse<api::CreateApiKeyResponse> {
let api_key_config = state.conf.api_keys.get_inner();
let store = state.store.as_ref();
let merchant_id = key_store.merchant_id.clone();
let hash_key = api_key_config.get_hash_key()?;
let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH);
let api_key = storage::ApiKeyNew {
key_id: PlaintextApiKey::new_key_id(),
merchant_id: merchant_id.to_owned(),
name: api_key.name,
description: api_key.description,
hashed_api_key: plaintext_api_key.keyed_hash(hash_key.peek()).into(),
prefix: plaintext_api_key.prefix(),
created_at: date_time::now(),
expires_at: api_key.expiration.into(),
last_used: None,
};
let api_key = store
.insert_api_key(api_key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert new API key")?;
let state_inner = state.clone();
let hashed_api_key = api_key.hashed_api_key.clone();
let merchant_id_inner = merchant_id.clone();
let key_id = api_key.key_id.clone();
let expires_at = api_key.expires_at;
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::add_api_key(
&state_inner,
hashed_api_key.into_inner().into(),
merchant_id_inner,
key_id,
expires_at.map(authentication::decision::convert_expiry),
)
.await
},
authentication::decision::ADD,
);
metrics::API_KEY_CREATED.add(
1,
router_env::metric_attributes!(("merchant", merchant_id.clone())),
);
// Add process to process_tracker for email reminder, only if expiry is set to future date
// If the `api_key` is set to expire in less than 7 days, the merchant is not notified about it's expiry
#[cfg(feature = "email")]
{
if api_key.expires_at.is_some() {
let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone();
add_api_key_expiry_task(
store,
&api_key,
expiry_reminder_days,
state.conf.application_source,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert API key expiry reminder to process tracker")?;
}
}
Ok(ApplicationResponse::Json(
(api_key, plaintext_api_key).foreign_into(),
))
}
// Add api_key_expiry task to the process_tracker table.
// Construct ProcessTrackerNew struct with all required fields, and schedule the first email.
// After first email has been sent, update the schedule_time based on retry_count in execute_workflow().
// A task is not scheduled if the time for the first email is in the past.
#[cfg(feature = "email")]
#[instrument(skip_all)]
pub async fn add_api_key_expiry_task(
store: &dyn crate::db::StorageInterface,
api_key: &ApiKey,
expiry_reminder_days: Vec<u8>,
application_source: common_enums::ApplicationSource,
) -> Result<(), errors::ProcessTrackerError> {
let current_time = date_time::now();
let schedule_time = expiry_reminder_days
.first()
.and_then(|expiry_reminder_day| {
api_key.expires_at.map(|expires_at| {
expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day)))
})
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain initial process tracker schedule time")?;
if schedule_time <= current_time {
return Ok(());
}
let api_key_expiry_tracker = storage::ApiKeyExpiryTrackingData {
key_id: api_key.key_id.clone(),
merchant_id: api_key.merchant_id.clone(),
api_key_name: api_key.name.clone(),
prefix: api_key.prefix.clone(),
// We need API key expiry too, because we need to decide on the schedule_time in
// execute_workflow() where we won't be having access to the Api key object.
api_key_expiry: api_key.expires_at,
expiry_reminder_days: expiry_reminder_days.clone(),
};
let process_tracker_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
API_KEY_EXPIRY_NAME,
API_KEY_EXPIRY_RUNNER,
[API_KEY_EXPIRY_TAG],
api_key_expiry_tracker,
None,
schedule_time,
common_types::consts::API_VERSION,
application_source,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct API key expiry process tracker task")?;
store
.insert_process(process_tracker_entry)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while inserting API key expiry reminder to process_tracker: {:?}",
api_key.key_id
)
})?;
metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "ApiKeyExpiry")));
Ok(())
}
#[instrument(skip_all)]
pub async fn retrieve_api_key(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
) -> RouterResponse<api::RetrieveApiKeyResponse> {
let store = state.store.as_ref();
let api_key = store
.find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::ApiKeyNotFound))?; // If retrieve returned `None`
Ok(ApplicationResponse::Json(api_key.foreign_into()))
}
#[instrument(skip_all)]
pub async fn update_api_key(
state: SessionState,
api_key: api::UpdateApiKeyRequest,
) -> RouterResponse<api::RetrieveApiKeyResponse> {
let merchant_id = api_key.merchant_id.clone();
let key_id = api_key.key_id.clone();
let store = state.store.as_ref();
let api_key = store
.update_api_key(
merchant_id.to_owned(),
key_id.to_owned(),
api_key.foreign_into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?;
let state_inner = state.clone();
let hashed_api_key = api_key.hashed_api_key.clone();
let key_id_inner = api_key.key_id.clone();
let expires_at = api_key.expires_at;
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::add_api_key(
&state_inner,
hashed_api_key.into_inner().into(),
merchant_id.clone(),
key_id_inner,
expires_at.map(authentication::decision::convert_expiry),
)
.await
},
authentication::decision::ADD,
);
#[cfg(feature = "email")]
{
let expiry_reminder_days = state.conf.api_keys.get_inner().expiry_reminder_days.clone();
let task_id = generate_task_id_for_api_key_expiry_workflow(&key_id);
// In order to determine how to update the existing process in the process_tracker table,
// we need access to the current entry in the table.
let existing_process_tracker_task = store
.find_process_by_id(task_id.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable(
"Failed to retrieve API key expiry reminder task from process tracker",
)?;
// If process exist
if existing_process_tracker_task.is_some() {
if api_key.expires_at.is_some() {
// Process exist in process, update the process with new schedule_time
update_api_key_expiry_task(store, &api_key, expiry_reminder_days)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to update API key expiry reminder task in process tracker",
)?;
}
// If an expiry is set to 'never'
else {
// Process exist in process, revoke it
revoke_api_key_expiry_task(store, &key_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to revoke API key expiry reminder task in process tracker",
)?;
}
}
// This case occurs if the expiry for an API key is set to 'never' during its creation. If so,
// process in tracker was not created.
else if api_key.expires_at.is_some() {
// Process doesn't exist in process_tracker table, so create new entry with
// schedule_time based on new expiry set.
add_api_key_expiry_task(
store,
&api_key,
expiry_reminder_days,
state.conf.application_source,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert API key expiry reminder task to process tracker")?;
}
}
Ok(ApplicationResponse::Json(api_key.foreign_into()))
}
// Update api_key_expiry task in the process_tracker table.
// Construct Update variant of ProcessTrackerUpdate with new tracking_data.
// A task is not scheduled if the time for the first email is in the past.
#[cfg(feature = "email")]
#[instrument(skip_all)]
pub async fn update_api_key_expiry_task(
store: &dyn crate::db::StorageInterface,
api_key: &ApiKey,
expiry_reminder_days: Vec<u8>,
) -> Result<(), errors::ProcessTrackerError> {
let current_time = date_time::now();
let schedule_time = expiry_reminder_days
.first()
.and_then(|expiry_reminder_day| {
api_key.expires_at.map(|expires_at| {
expires_at.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day)))
})
});
if let Some(schedule_time) = schedule_time {
if schedule_time <= current_time {
return Ok(());
}
}
let task_id = generate_task_id_for_api_key_expiry_workflow(&api_key.key_id);
let task_ids = vec![task_id.clone()];
let updated_tracking_data = &storage::ApiKeyExpiryTrackingData {
key_id: api_key.key_id.clone(),
merchant_id: api_key.merchant_id.clone(),
api_key_name: api_key.name.clone(),
prefix: api_key.prefix.clone(),
api_key_expiry: api_key.expires_at,
expiry_reminder_days,
};
let updated_api_key_expiry_workflow_model = serde_json::to_value(updated_tracking_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("unable to serialize API key expiry tracker: {updated_tracking_data:?}")
})?;
let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update {
name: None,
retry_count: Some(0),
schedule_time,
tracking_data: Some(updated_api_key_expiry_workflow_model),
business_status: Some(String::from(
diesel_models::process_tracker::business_status::PENDING,
)),
status: Some(storage_enums::ProcessTrackerStatus::New),
updated_at: Some(current_time),
};
store
.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(())
}
#[instrument(skip_all)]
pub async fn revoke_api_key(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> RouterResponse<api::RevokeApiKeyResponse> {
let store = state.store.as_ref();
let api_key = store
.find_api_key_by_merchant_id_key_id_optional(&merchant_id, key_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?;
let revoked = store
.revoke_api_key(&merchant_id, key_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ApiKeyNotFound)?;
if let Some(api_key) = api_key {
let hashed_api_key = api_key.hashed_api_key;
let state = state.clone();
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::revoke_api_key(&state, hashed_api_key.into_inner().into())
.await
},
authentication::decision::REVOKE,
);
}
metrics::API_KEY_REVOKED.add(1, &[]);
#[cfg(feature = "email")]
{
let task_id = generate_task_id_for_api_key_expiry_workflow(key_id);
// In order to determine how to update the existing process in the process_tracker table,
// we need access to the current entry in the table.
let existing_process_tracker_task = store
.find_process_by_id(task_id.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable(
"Failed to retrieve API key expiry reminder task from process tracker",
)?;
// If process exist, then revoke it
if existing_process_tracker_task.is_some() {
revoke_api_key_expiry_task(store, key_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to revoke API key expiry reminder task in process tracker",
)?;
}
}
Ok(ApplicationResponse::Json(api::RevokeApiKeyResponse {
merchant_id: merchant_id.to_owned(),
key_id: key_id.to_owned(),
revoked,
}))
}
// Function to revoke api_key_expiry task in the process_tracker table when API key is revoked.
// Construct StatusUpdate variant of ProcessTrackerUpdate by setting status to 'finish'.
#[cfg(feature = "email")]
#[instrument(skip_all)]
pub async fn revoke_api_key_expiry_task(
store: &dyn crate::db::StorageInterface,
key_id: &common_utils::id_type::ApiKeyId,
) -> Result<(), errors::ProcessTrackerError> {
let task_id = generate_task_id_for_api_key_expiry_workflow(key_id);
let task_ids = vec![task_id];
let updated_process_tracker_data = storage::ProcessTrackerUpdate::StatusUpdate {
status: storage_enums::ProcessTrackerStatus::Finish,
business_status: Some(String::from(diesel_models::business_status::REVOKED)),
};
store
.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(())
}
#[instrument(skip_all)]
pub async fn list_api_keys(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> RouterResponse<Vec<api::RetrieveApiKeyResponse>> {
let store = state.store.as_ref();
let api_keys = store
.list_api_keys_by_merchant_id(&merchant_id, limit, offset)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list merchant API keys")?;
let api_keys = api_keys
.into_iter()
.map(ForeignInto::foreign_into)
.collect();
Ok(ApplicationResponse::Json(api_keys))
}
#[cfg(feature = "email")]
fn generate_task_id_for_api_key_expiry_workflow(
key_id: &common_utils::id_type::ApiKeyId,
) -> String {
format!(
"{API_KEY_EXPIRY_RUNNER}_{API_KEY_EXPIRY_NAME}_{}",
key_id.get_string_repr()
)
}
impl From<&str> for PlaintextApiKey {
fn from(s: &str) -> Self {
Self(s.to_owned().into())
}
}
impl From<String> for PlaintextApiKey {
fn from(s: String) -> Self {
Self(s.into())
}
}
impl From<HashedApiKey> for storage::HashedApiKey {
fn from(hashed_api_key: HashedApiKey) -> Self {
hashed_api_key.0.into()
}
}
impl From<storage::HashedApiKey> for HashedApiKey {
fn from(hashed_api_key: storage::HashedApiKey) -> Self {
Self(hashed_api_key.into_inner())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_hashing_and_verification() {
let settings = settings::Settings::new().expect("invalid settings");
let plaintext_api_key = PlaintextApiKey::new(consts::API_KEY_LENGTH);
let hash_key = settings.api_keys.get_inner().get_hash_key().unwrap();
let hashed_api_key = plaintext_api_key.keyed_hash(hash_key.peek());
assert_ne!(
plaintext_api_key.0.peek().as_bytes(),
hashed_api_key.0.as_bytes()
);
let new_hashed_api_key = plaintext_api_key.keyed_hash(hash_key.peek());
assert_eq!(hashed_api_key, new_hashed_api_key)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/errors.rs | crates/router/src/core/errors.rs | pub mod chat;
pub mod customers_error_response;
pub mod error_handlers;
pub mod transformers;
#[cfg(feature = "olap")]
pub mod user;
pub mod utils;
use std::fmt::Display;
pub use ::payment_methods::core::errors::VaultError;
use actix_web::{body::BoxBody, ResponseError};
pub use common_utils::errors::{CustomResult, ParsingError, ValidationError};
use diesel_models::errors as storage_errors;
pub use hyperswitch_domain_models::errors::api_error_response::{
ApiErrorResponse, ErrorType, NotImplementedMessage,
};
pub use hyperswitch_interfaces::errors::ConnectorError;
pub use redis_interface::errors::RedisError;
use scheduler::errors as sch_errors;
use storage_impl::errors as storage_impl_errors;
#[cfg(feature = "olap")]
pub use user::*;
pub use self::{
customers_error_response::CustomersErrorResponse,
sch_errors::*,
storage_errors::*,
storage_impl_errors::*,
utils::{ConnectorErrorExt, StorageErrorExt},
};
use crate::services;
pub type RouterResult<T> = CustomResult<T, ApiErrorResponse>;
pub type RouterResponse<T> = CustomResult<services::ApplicationResponse<T>, ApiErrorResponse>;
pub type ApplicationResult<T> = error_stack::Result<T, ApplicationError>;
pub type ApplicationResponse<T> = ApplicationResult<services::ApplicationResponse<T>>;
pub type CustomerResponse<T> =
CustomResult<services::ApplicationResponse<T>, CustomersErrorResponse>;
macro_rules! impl_error_display {
($st: ident, $arg: tt) => {
impl Display for $st {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
fmt,
"{{ error_type: {:?}, error_description: {} }}",
self, $arg
)
}
}
};
}
#[macro_export]
macro_rules! capture_method_not_supported {
($connector:expr, $capture_method:expr) => {
Err(errors::ConnectorError::NotSupported {
message: format!("{} for selected payment method", $capture_method),
connector: $connector,
}
.into())
};
($connector:expr, $capture_method:expr, $payment_method_type:expr) => {
Err(errors::ConnectorError::NotSupported {
message: format!("{} for {}", $capture_method, $payment_method_type),
connector: $connector,
}
.into())
};
}
#[macro_export]
macro_rules! unimplemented_payment_method {
($payment_method:expr, $connector:expr) => {
errors::ConnectorError::NotImplemented(format!(
"{} through {}",
$payment_method, $connector
))
};
($payment_method:expr, $flow:expr, $connector:expr) => {
errors::ConnectorError::NotImplemented(format!(
"{} {} through {}",
$payment_method, $flow, $connector
))
};
}
macro_rules! impl_error_type {
($name: ident, $arg: tt) => {
#[derive(Debug)]
pub struct $name;
impl_error_display!($name, $arg);
impl std::error::Error for $name {}
};
}
impl_error_type!(EncryptionError, "Encryption error");
impl From<ring::error::Unspecified> for EncryptionError {
fn from(_: ring::error::Unspecified) -> Self {
Self
}
}
pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> {
ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Default,
}
.error_response()
}
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckOutGoing {
#[error("Outgoing call failed with error: {message}")]
OutGoingFailed { message: String },
}
#[derive(Debug, thiserror::Error)]
pub enum AwsKmsError {
#[error("Failed to base64 decode input data")]
Base64DecodingFailed,
#[error("Failed to AWS KMS decrypt input data")]
DecryptionFailed,
#[error("Missing plaintext AWS KMS decryption output")]
MissingPlaintextDecryptionOutput,
#[error("Failed to UTF-8 decode decryption output")]
Utf8DecodingFailed,
}
#[derive(Debug, thiserror::Error, serde::Serialize)]
pub enum WebhooksFlowError {
#[error("Merchant webhook config not found")]
MerchantConfigNotFound,
#[error("Webhook details for merchant not configured")]
MerchantWebhookDetailsNotFound,
#[error("Merchant does not have a webhook URL configured")]
MerchantWebhookUrlNotConfigured,
#[error("Webhook event updation failed")]
WebhookEventUpdationFailed,
#[error("Outgoing webhook body signing failed")]
OutgoingWebhookSigningFailed,
#[error("Webhook api call to merchant failed")]
CallToMerchantFailed,
#[error("Webhook not received by merchant")]
NotReceivedByMerchant,
#[error("Dispute webhook status validation failed")]
DisputeWebhookValidationFailed,
#[error("Outgoing webhook body encoding failed")]
OutgoingWebhookEncodingFailed,
#[error("Failed to update outgoing webhook process tracker task")]
OutgoingWebhookProcessTrackerTaskUpdateFailed,
#[error("Failed to schedule retry attempt for outgoing webhook")]
OutgoingWebhookRetrySchedulingFailed,
#[error("Outgoing webhook response encoding failed")]
OutgoingWebhookResponseEncodingFailed,
#[error("ID generation failed")]
IdGenerationFailed,
}
impl WebhooksFlowError {
pub(crate) fn is_webhook_delivery_retryable_error(&self) -> bool {
match self {
Self::MerchantConfigNotFound
| Self::MerchantWebhookDetailsNotFound
| Self::MerchantWebhookUrlNotConfigured
| Self::OutgoingWebhookResponseEncodingFailed => false,
Self::WebhookEventUpdationFailed
| Self::OutgoingWebhookSigningFailed
| Self::CallToMerchantFailed
| Self::NotReceivedByMerchant
| Self::DisputeWebhookValidationFailed
| Self::OutgoingWebhookEncodingFailed
| Self::OutgoingWebhookProcessTrackerTaskUpdateFailed
| Self::OutgoingWebhookRetrySchedulingFailed
| Self::IdGenerationFailed => true,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ApplePayDecryptionError {
#[error("Failed to base64 decode input data")]
Base64DecodingFailed,
#[error("Failed to decrypt input data")]
DecryptionFailed,
#[error("Certificate parsing failed")]
CertificateParsingFailed,
#[error("Certificate parsing failed")]
MissingMerchantId,
#[error("Key Deserialization failure")]
KeyDeserializationFailed,
#[error("Failed to Derive a shared secret key")]
DerivingSharedSecretKeyFailed,
}
#[derive(Debug, thiserror::Error)]
pub enum PazeDecryptionError {
#[error("Failed to base64 decode input data")]
Base64DecodingFailed,
#[error("Failed to decrypt input data")]
DecryptionFailed,
#[error("Certificate parsing failed")]
CertificateParsingFailed,
}
#[derive(Debug, thiserror::Error)]
pub enum GooglePayDecryptionError {
#[error("Invalid expiration time")]
InvalidExpirationTime,
#[error("Failed to base64 decode input data")]
Base64DecodingFailed,
#[error("Failed to decrypt input data")]
DecryptionFailed,
#[error("Failed to deserialize input data")]
DeserializationFailed,
#[error("Certificate parsing failed")]
CertificateParsingFailed,
#[error("Key deserialization failure")]
KeyDeserializationFailed,
#[error("Failed to derive a shared ephemeral key")]
DerivingSharedEphemeralKeyFailed,
#[error("Failed to derive a shared secret key")]
DerivingSharedSecretKeyFailed,
#[error("Failed to parse the tag")]
ParsingTagError,
#[error("HMAC verification failed")]
HmacVerificationFailed,
#[error("Failed to derive Elliptic Curve key")]
DerivingEcKeyFailed,
#[error("Failed to Derive Public key")]
DerivingPublicKeyFailed,
#[error("Failed to Derive Elliptic Curve group")]
DerivingEcGroupFailed,
#[error("Failed to allocate memory for big number")]
BigNumAllocationFailed,
#[error("Failed to get the ECDSA signature")]
EcdsaSignatureFailed,
#[error("Failed to verify the signature")]
SignatureVerificationFailed,
#[error("Invalid signature is provided")]
InvalidSignature,
#[error("Failed to parse the Signed Key")]
SignedKeyParsingFailure,
#[error("The Signed Key is expired")]
SignedKeyExpired,
#[error("Failed to parse the ECDSA signature")]
EcdsaSignatureParsingFailed,
#[error("Invalid intermediate signature is provided")]
InvalidIntermediateSignature,
#[error("Invalid protocol version")]
InvalidProtocolVersion,
#[error("Decrypted Token has expired")]
DecryptedTokenExpired,
#[error("Failed to parse the given value")]
ParsingFailed,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum RoutingError {
#[error("Merchant routing algorithm not found in cache")]
CacheMiss,
#[error("Final connector selection failed")]
ConnectorSelectionFailed,
#[error("[DSL] Missing required field in payment data: '{field_name}'")]
DslMissingRequiredField { field_name: String },
#[error("The lock on the DSL cache is most probably poisoned")]
DslCachePoisoned,
#[error("Expected DSL to be saved in DB but did not find")]
DslMissingInDb,
#[error("Unable to parse DSL from JSON")]
DslParsingError,
#[error("Failed to initialize DSL backend")]
DslBackendInitError,
#[error("Error updating merchant with latest dsl cache contents")]
DslMerchantUpdateError,
#[error("Error executing the DSL")]
DslExecutionError,
#[error("Final connector selection failed")]
DslFinalConnectorSelectionFailed,
#[error("[DSL] Received incorrect selection algorithm as DSL output")]
DslIncorrectSelectionAlgorithm,
#[error("there was an error saving/retrieving values from the kgraph cache")]
KgraphCacheFailure,
#[error("failed to refresh the kgraph cache")]
KgraphCacheRefreshFailed,
#[error("there was an error during the kgraph analysis phase")]
KgraphAnalysisError,
#[error("'profile_id' was not provided")]
ProfileIdMissing,
#[error("the profile was not found in the database")]
ProfileNotFound,
#[error("failed to fetch the fallback config for the merchant")]
FallbackConfigFetchFailed,
#[error("Invalid connector name received: '{0}'")]
InvalidConnectorName(String),
#[error("The routing algorithm in merchant account had invalid structure")]
InvalidRoutingAlgorithmStructure,
#[error("Volume split failed")]
VolumeSplitFailed,
#[error("Unable to parse metadata")]
MetadataParsingError,
#[error("Unable to retrieve success based routing config")]
SuccessBasedRoutingConfigError,
#[error("Params not found in success based routing config")]
SuccessBasedRoutingParamsNotFoundError,
#[error("Unable to calculate success based routing config from dynamic routing service")]
SuccessRateCalculationError,
#[error("Success rate client from dynamic routing gRPC service not initialized")]
SuccessRateClientInitializationError,
#[error("Elimination client from dynamic routing gRPC service not initialized")]
EliminationClientInitializationError,
#[error("Unable to analyze elimination routing config from dynamic routing service")]
EliminationRoutingCalculationError,
#[error("Params not found in elimination based routing config")]
EliminationBasedRoutingParamsNotFoundError,
#[error("Unable to retrieve elimination based routing config")]
EliminationRoutingConfigError,
#[error(
"Invalid elimination based connector label received from dynamic routing service: '{0}'"
)]
InvalidEliminationBasedConnectorLabel(String),
#[error("Unable to convert from '{from}' to '{to}'")]
GenericConversionError { from: String, to: String },
#[error("Invalid success based connector label received from dynamic routing service: '{0}'")]
InvalidSuccessBasedConnectorLabel(String),
#[error("unable to find '{field}'")]
GenericNotFoundError { field: String },
#[error("Unable to deserialize from '{from}' to '{to}'")]
DeserializationError { from: String, to: String },
#[error("Unable to retrieve contract based routing config")]
ContractBasedRoutingConfigError,
#[error("Params not found in contract based routing config")]
ContractBasedRoutingParamsNotFoundError,
#[error("Unable to calculate contract score from dynamic routing service: '{err}'")]
ContractScoreCalculationError { err: String },
#[error("Unable to update contract score on dynamic routing service")]
ContractScoreUpdationError,
#[error("contract routing client from dynamic routing gRPC service not initialized")]
ContractRoutingClientInitializationError,
#[error("Invalid contract based connector label received from dynamic routing service: '{0}'")]
InvalidContractBasedConnectorLabel(String),
#[error("Failed to perform routing in open_router")]
OpenRouterCallFailed,
#[error("Error from open_router: {0}")]
OpenRouterError(String),
#[error("Decision engine responded with validation error: {0}")]
DecisionEngineValidationError(String),
#[error("Invalid transaction type")]
InvalidTransactionType,
#[error("Routing events error: {message}, status code: {status_code}")]
RoutingEventsError { message: String, status_code: u16 },
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum ConditionalConfigError {
#[error("failed to fetch the fallback config for the merchant")]
FallbackConfigFetchFailed,
#[error("The lock on the DSL cache is most probably poisoned")]
DslCachePoisoned,
#[error("Merchant routing algorithm not found in cache")]
CacheMiss,
#[error("Expected DSL to be saved in DB but did not find")]
DslMissingInDb,
#[error("Unable to parse DSL from JSON")]
DslParsingError,
#[error("Failed to initialize DSL backend")]
DslBackendInitError,
#[error("Error executing the DSL")]
DslExecutionError,
#[error("Error constructing the Input")]
InputConstructionError,
}
#[derive(Debug, thiserror::Error)]
pub enum NetworkTokenizationError {
#[error("Failed to save network token in vault")]
SaveNetworkTokenFailed,
#[error("Failed to fetch network token details from vault")]
FetchNetworkTokenFailed,
#[error("Failed to encode network token vault request")]
RequestEncodingFailed,
#[error("Failed to deserialize network token service response")]
ResponseDeserializationFailed,
#[error("Failed to delete network token")]
DeleteNetworkTokenFailed,
#[error("Network token service not configured")]
NetworkTokenizationServiceNotConfigured,
#[error("Failed while calling Network Token Service API")]
ApiError,
#[error("Network Tokenization is not enabled for profile")]
NetworkTokenizationNotEnabledForProfile,
#[error("Network Tokenization is not supported for {message}")]
NotSupported { message: String },
#[error("Failed to encrypt the NetworkToken payment method details")]
NetworkTokenDetailsEncryptionFailed,
}
#[derive(Debug, thiserror::Error)]
pub enum BulkNetworkTokenizationError {
#[error("Failed to validate card details")]
CardValidationFailed,
#[error("Failed to validate payment method details")]
PaymentMethodValidationFailed,
#[error("Failed to assign a customer to the card")]
CustomerAssignmentFailed,
#[error("Failed to perform BIN lookup for the card")]
BinLookupFailed,
#[error("Failed to tokenize the card details with the network")]
NetworkTokenizationFailed,
#[error("Failed to store the card details in locker")]
VaultSaveFailed,
#[error("Failed to create a payment method entry")]
PaymentMethodCreationFailed,
#[error("Failed to update the payment method")]
PaymentMethodUpdationFailed,
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
#[derive(Debug, thiserror::Error)]
pub enum RevenueRecoveryError {
#[error("Failed to fetch payment intent")]
PaymentIntentFetchFailed,
#[error("Failed to fetch payment attempt")]
PaymentAttemptFetchFailed,
#[error("Failed to fetch payment attempt")]
PaymentAttemptIdNotFound,
#[error("Failed to get revenue recovery invoice webhook")]
InvoiceWebhookProcessingFailed,
#[error("Failed to get revenue recovery invoice transaction")]
TransactionWebhookProcessingFailed,
#[error("Failed to create payment intent")]
PaymentIntentCreateFailed,
#[error("Source verification failed for billing connector")]
WebhookAuthenticationFailed,
#[error("Payment merchant connector account not found using account reference id")]
PaymentMerchantConnectorAccountNotFound,
#[error("Failed to fetch primitive date_time")]
ScheduleTimeFetchFailed,
#[error("Failed to create process tracker")]
ProcessTrackerCreationError,
#[error("Failed to get the response from process tracker")]
ProcessTrackerResponseError,
#[error("Billing connector psync call failed")]
BillingConnectorPaymentsSyncFailed,
#[error("Billing connector invoice sync call failed")]
BillingConnectorInvoiceSyncFailed,
#[error("Failed to fetch connector customer ID")]
CustomerIdNotFound,
#[error("Failed to get the retry count for payment intent")]
RetryCountFetchFailed,
#[error("Failed to get the billing threshold retry count")]
BillingThresholdRetryCountFetchFailed,
#[error("Failed to get the retry algorithm type")]
RetryAlgorithmTypeNotFound,
#[error("Failed to update the retry algorithm type")]
RetryAlgorithmUpdationFailed,
#[error("Failed to create the revenue recovery attempt data")]
RevenueRecoveryAttemptDataCreateFailed,
#[error("Failed to insert the revenue recovery payment method data in redis")]
RevenueRecoveryRedisInsertFailed,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/user.rs | crates/router/src/core/user.rs | use std::{
collections::{HashMap, HashSet},
ops::Not,
};
use api_models::{
payments::RedirectionResponse,
user::{self as user_api, InviteMultipleUserResponse, NameIdUnit},
};
use common_enums::{connector_enums, EntityType, UserAuthType};
use common_utils::{
fp_utils, type_name,
types::{keymanager::Identifier, user::LineageContext},
};
#[cfg(feature = "email")]
use diesel_models::user_role::UserRoleUpdate;
use diesel_models::{
enums::{TotpStatus, UserRoleVersion, UserStatus},
organization::OrganizationBridge,
user as storage_user,
user_authentication_method::{UserAuthenticationMethodNew, UserAuthenticationMethodUpdate},
};
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "email")]
use router_env::env;
use router_env::logger;
use storage_impl::errors::StorageError;
#[cfg(not(feature = "email"))]
use user_api::dashboard_metadata::SetMetaDataRequest;
#[cfg(feature = "v1")]
use super::admin;
use super::errors::{StorageErrorExt, UserErrors, UserResponse, UserResult};
#[cfg(feature = "v1")]
use crate::types::transformers::ForeignFrom;
use crate::{
consts,
core::encryption::send_request_to_key_service_for_user,
db::{
domain::user_authentication_method::DEFAULT_USER_AUTH_METHOD,
user_role::ListUserRolesByUserIdPayload,
},
routes::{app::ReqState, SessionState},
services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse},
types::{domain, transformers::ForeignInto},
utils::{
self,
user::{theme as theme_utils, two_factor_auth as tfa_utils},
},
};
#[cfg(feature = "email")]
use crate::{services::email::types as email_types, utils::user as user_utils};
pub mod dashboard_metadata;
#[cfg(feature = "dummy_connector")]
pub mod sample_data;
pub mod theme;
#[cfg(feature = "email")]
pub async fn signup_with_merchant_id(
state: SessionState,
request: user_api::SignUpWithMerchantIdRequest,
auth_id: Option<String>,
theme_id: Option<String>,
) -> UserResponse<user_api::SignUpWithMerchantIdResponse> {
let new_user = domain::NewUser::try_from(request.clone())?;
new_user
.get_new_merchant()
.get_new_organization()
.insert_org_in_db(state.clone())
.await?;
let user_from_db = new_user
.insert_user_and_merchant_in_db(state.clone())
.await?;
let _user_role = new_user
.insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await?;
let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
let email_contents = email_types::ResetPassword {
recipient_email: user_from_db.get_email().try_into()?,
user_name: domain::UserName::new(user_from_db.get_name())?,
settings: state.conf.clone(),
auth_id,
theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
theme_config: theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
};
let send_email_result = state
.email_client
.compose_and_send_email(
user_utils::get_base_url(&state),
Box::new(email_contents),
state.conf.proxy.https_url.as_ref(),
)
.await;
logger::info!(?send_email_result);
Ok(ApplicationResponse::Json(user_api::AuthorizeResponse {
is_email_sent: send_email_result.is_ok(),
user_id: user_from_db.get_user_id().to_string(),
}))
}
pub async fn get_user_details(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::GetUserDetailsResponse> {
let user = user_from_token.get_user_from_db(&state).await?;
let verification_days_left = utils::user::get_verification_days_left(&state, &user)?;
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&user_from_token.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await;
let version = if let Ok(merchant_key_store) = merchant_key_store {
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(&user_from_token.merchant_id, &merchant_key_store)
.await;
if let Ok(merchant_account) = merchant_account {
merchant_account.version
} else if merchant_account
.as_ref()
.map_err(|e| e.current_context().is_db_not_found())
.err()
.unwrap_or(false)
{
common_enums::ApiVersion::V2
} else {
Err(merchant_account
.err()
.map(|e| e.change_context(UserErrors::InternalServerError))
.unwrap_or(UserErrors::InternalServerError.into()))?
}
} else if merchant_key_store
.as_ref()
.map_err(|e| e.current_context().is_db_not_found())
.err()
.unwrap_or(false)
{
common_enums::ApiVersion::V2
} else {
Err(merchant_key_store
.err()
.map(|e| e.change_context(UserErrors::InternalServerError))
.unwrap_or(UserErrors::InternalServerError.into()))?
};
let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
&state,
&user_from_token,
EntityType::Profile,
)
.await?;
Ok(ApplicationResponse::Json(
user_api::GetUserDetailsResponse {
merchant_id: user_from_token.merchant_id,
name: user.get_name(),
email: user.get_email(),
user_id: user.get_user_id().to_string(),
verification_days_left,
role_id: user_from_token.role_id,
org_id: user_from_token.org_id,
is_two_factor_auth_setup: user.get_totp_status() == TotpStatus::Set,
recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()),
profile_id: user_from_token.profile_id,
entity_type: role_info.get_entity_type(),
theme_id: theme.map(|theme| theme.theme_id),
version,
},
))
}
pub async fn signup_token_only_flow(
state: SessionState,
request: user_api::SignUpRequest,
) -> UserResponse<user_api::TokenResponse> {
let user_email = domain::UserEmail::from_pii_email(request.email.clone())?;
utils::user::validate_email_domain_auth_type_using_db(
&state,
&user_email,
UserAuthType::Password,
)
.await?;
let new_user = domain::NewUser::try_from(request)?;
new_user
.get_new_merchant()
.get_new_organization()
.insert_org_in_db(state.clone())
.await?;
let user_from_db = new_user
.insert_user_and_merchant_in_db(state.clone())
.await?;
let user_role = new_user
.insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await?;
let next_flow =
domain::NextFlow::from_origin(domain::Origin::SignUp, user_from_db.clone(), &state).await?;
let token = next_flow
.get_token_with_user_role(&state, &user_role)
.await?;
let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
};
auth::cookies::set_cookie_response(response, token)
}
pub async fn signin_token_only_flow(
state: SessionState,
request: user_api::SignInRequest,
) -> UserResponse<user_api::TokenResponse> {
let user_email = domain::UserEmail::from_pii_email(request.email)?;
utils::user::validate_email_domain_auth_type_using_db(
&state,
&user_email,
UserAuthType::Password,
)
.await?;
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_email(&user_email)
.await
.to_not_found_response(UserErrors::InvalidCredentials)?
.into();
user_from_db.compare_password(&request.password)?;
let next_flow =
domain::NextFlow::from_origin(domain::Origin::SignIn, user_from_db.clone(), &state).await?;
let token = next_flow.get_token(&state).await?;
let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
};
auth::cookies::set_cookie_response(response, token)
}
#[cfg(feature = "email")]
pub async fn connect_account(
state: SessionState,
request: user_api::ConnectAccountRequest,
auth_id: Option<String>,
theme_id: Option<String>,
) -> UserResponse<user_api::ConnectAccountResponse> {
let user_email = domain::UserEmail::from_pii_email(request.email.clone())?;
utils::user::validate_email_domain_auth_type_using_db(
&state,
&user_email,
UserAuthType::MagicLink,
)
.await?;
let find_user = state.global_store.find_user_by_email(&user_email).await;
if let Ok(found_user) = find_user {
let user_from_db: domain::UserFromStorage = found_user.into();
let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
let email_contents = email_types::MagicLink {
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
settings: state.conf.clone(),
user_name: domain::UserName::new(user_from_db.get_name())?,
auth_id,
theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
theme_config: theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
};
let send_email_result = state
.email_client
.compose_and_send_email(
user_utils::get_base_url(&state),
Box::new(email_contents),
state.conf.proxy.https_url.as_ref(),
)
.await;
logger::info!(?send_email_result);
Ok(ApplicationResponse::Json(
user_api::ConnectAccountResponse {
is_email_sent: send_email_result.is_ok(),
user_id: user_from_db.get_user_id().to_string(),
},
))
} else if find_user
.as_ref()
.map_err(|e| e.current_context().is_db_not_found())
.err()
.unwrap_or(false)
{
if matches!(env::which(), env::Env::Production) {
return Err(report!(UserErrors::InvalidCredentials));
}
let new_user = domain::NewUser::try_from(request)?;
let _ = new_user
.get_new_merchant()
.get_new_organization()
.insert_org_in_db(state.clone())
.await?;
let user_from_db = new_user
.insert_user_and_merchant_in_db(state.clone())
.await?;
let _user_role = new_user
.insert_org_level_user_role_in_db(
state.clone(),
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
UserStatus::Active,
)
.await?;
let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
let magic_link_email = email_types::VerifyEmail {
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
settings: state.conf.clone(),
auth_id,
theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
theme_config: theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
};
let magic_link_result = state
.email_client
.compose_and_send_email(
user_utils::get_base_url(&state),
Box::new(magic_link_email),
state.conf.proxy.https_url.as_ref(),
)
.await;
logger::info!(?magic_link_result);
if state.tenant.tenant_id.get_string_repr() == common_utils::consts::DEFAULT_TENANT {
let welcome_to_community_email = email_types::WelcomeToCommunity {
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
};
let welcome_email_result = state
.email_client
.compose_and_send_email(
user_utils::get_base_url(&state),
Box::new(welcome_to_community_email),
state.conf.proxy.https_url.as_ref(),
)
.await;
logger::info!(?welcome_email_result);
}
Ok(ApplicationResponse::Json(
user_api::ConnectAccountResponse {
is_email_sent: magic_link_result.is_ok(),
user_id: user_from_db.get_user_id().to_string(),
},
))
} else {
Err(find_user
.err()
.map(|e| e.change_context(UserErrors::InternalServerError))
.unwrap_or(UserErrors::InternalServerError.into()))
}
}
pub async fn signout(
state: SessionState,
user_from_token: auth::UserIdFromAuth,
) -> UserResponse<()> {
tfa_utils::delete_totp_from_redis(&state, &user_from_token.user_id).await?;
tfa_utils::delete_recovery_code_from_redis(&state, &user_from_token.user_id).await?;
tfa_utils::delete_totp_secret_from_redis(&state, &user_from_token.user_id).await?;
auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?;
auth::cookies::remove_cookie_response()
}
pub async fn change_password(
state: SessionState,
request: user_api::ChangePasswordRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<()> {
let user: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_from_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
user.compare_password(&request.old_password)
.change_context(UserErrors::InvalidOldPassword)?;
if request.old_password == request.new_password {
return Err(UserErrors::ChangePasswordError.into());
}
let new_password = domain::UserPassword::new(request.new_password)?;
let new_password_hash =
utils::user::password::generate_password_hash(new_password.get_secret())?;
let _ = state
.global_store
.update_user_by_user_id(
user.get_user_id(),
diesel_models::user::UserUpdate::PasswordUpdate {
password: new_password_hash,
},
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to update user password in the database")?;
let _ = auth::blacklist::insert_user_in_blacklist(&state, user.get_user_id())
.await
.map_err(|error| logger::error!(?error));
#[cfg(not(feature = "email"))]
{
state
.store
.delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&user_from_token.user_id,
&user_from_token.merchant_id,
diesel_models::enums::DashboardMetadata::IsChangePasswordRequired,
)
.await
.map_err(|e| logger::error!("Error while deleting dashboard metadata {e:?}"))
.ok();
}
Ok(ApplicationResponse::StatusOk)
}
#[cfg(feature = "email")]
pub async fn forgot_password(
state: SessionState,
request: user_api::ForgotPasswordRequest,
auth_id: Option<String>,
theme_id: Option<String>,
) -> UserResponse<()> {
let user_email = domain::UserEmail::from_pii_email(request.email)?;
utils::user::validate_email_domain_auth_type_using_db(
&state,
&user_email,
UserAuthType::Password,
)
.await?;
let user_from_db = state
.global_store
.find_user_by_email(&user_email)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::UserNotFound)
} else {
e.change_context(UserErrors::InternalServerError)
}
})
.map(domain::UserFromStorage::from)?;
let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
let email_contents = email_types::ResetPassword {
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
settings: state.conf.clone(),
user_name: domain::UserName::new(user_from_db.get_name())?,
auth_id,
theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
theme_config: theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
};
state
.email_client
.compose_and_send_email(
user_utils::get_base_url(&state),
Box::new(email_contents),
state.conf.proxy.https_url.as_ref(),
)
.await
.map_err(|e| e.change_context(UserErrors::InternalServerError))?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn rotate_password(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
request: user_api::RotatePasswordRequest,
_req_state: ReqState,
) -> UserResponse<()> {
let user: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
let password = domain::UserPassword::new(request.password.to_owned())?;
let hash_password = utils::user::password::generate_password_hash(password.get_secret())?;
if user.compare_password(&request.password).is_ok() {
return Err(UserErrors::ChangePasswordError.into());
}
let user = state
.global_store
.update_user_by_user_id(
&user_token.user_id,
storage_user::UserUpdate::PasswordUpdate {
password: hash_password,
},
)
.await
.change_context(UserErrors::InternalServerError)?;
let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id)
.await
.map_err(|error| logger::error!(?error));
auth::cookies::remove_cookie_response()
}
#[cfg(feature = "email")]
pub async fn reset_password_token_only_flow(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
request: user_api::ResetPasswordRequest,
) -> UserResponse<()> {
let token = request.token.expose();
let email_token = auth::decode_jwt::<email_types::EmailToken>(&token, &state)
.await
.change_context(UserErrors::LinkInvalid)?;
auth::blacklist::check_email_token_in_blacklist(&state, &token).await?;
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_email(&email_token.get_email()?)
.await
.change_context(UserErrors::InternalServerError)?
.into();
if user_from_db.get_user_id() != user_token.user_id {
return Err(UserErrors::LinkInvalid.into());
}
let password = domain::UserPassword::new(request.password)?;
let hash_password = utils::user::password::generate_password_hash(password.get_secret())?;
let user = state
.global_store
.update_user_by_user_id(
user_from_db.get_user_id(),
storage_user::UserUpdate::PasswordUpdate {
password: hash_password,
},
)
.await
.change_context(UserErrors::InternalServerError)?;
if !user_from_db.is_verified() {
let _ = state
.global_store
.update_user_by_user_id(
user_from_db.get_user_id(),
storage_user::UserUpdate::VerifyUser,
)
.await
.map_err(|error| logger::error!(?error));
}
let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
.await
.map_err(|error| logger::error!(?error));
let _ = auth::blacklist::insert_user_in_blacklist(&state, &user.user_id)
.await
.map_err(|error| logger::error!(?error));
auth::cookies::remove_cookie_response()
}
pub async fn invite_multiple_user(
state: SessionState,
user_from_token: auth::UserFromToken,
requests: Vec<user_api::InviteUserRequest>,
req_state: ReqState,
auth_id: Option<String>,
) -> UserResponse<Vec<InviteMultipleUserResponse>> {
if requests.len() > 10 {
return Err(report!(UserErrors::MaxInvitationsError))
.attach_printable("Number of invite requests must not exceed 10");
}
let responses = futures::future::join_all(requests.into_iter().map(|request| async {
match handle_invitation(&state, &user_from_token, &request, &req_state, &auth_id).await {
Ok(response) => response,
Err(error) => {
logger::error!(invite_error=?error);
InviteMultipleUserResponse {
email: request.email,
is_email_sent: false,
password: None,
error: Some(error.current_context().get_error_message().to_string()),
}
}
}
}))
.await;
Ok(ApplicationResponse::Json(responses))
}
async fn handle_invitation(
state: &SessionState,
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
req_state: &ReqState,
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
let inviter_user = user_from_token.get_user_from_db(state).await?;
if inviter_user.get_email() == request.email {
Err(report!(UserErrors::InvalidRoleOperationWithMessage(
"User Inviting themselves".to_string(),
)))?;
}
let inviter_role_info = roles::RoleInfo::from_role_id_in_lineage(
state,
&user_from_token.role_id,
&user_from_token.merchant_id,
&user_from_token.org_id,
&user_from_token.profile_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.to_not_found_response(UserErrors::InternalServerError)?;
let req_role_info = roles::RoleInfo::from_role_id_in_lineage(
state,
&request.role_id,
&user_from_token.merchant_id,
&user_from_token.org_id,
&user_from_token.profile_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.to_not_found_response(UserErrors::InvalidRoleId)?;
if inviter_role_info.get_entity_type() < req_role_info.get_entity_type() {
Err(report!(UserErrors::InvalidRoleOperationWithMessage(
"Inviter role entity type is lower than requested role entity type".to_string(),
)))
.attach_printable(format!(
"{} is trying to invite {}",
inviter_role_info.get_entity_type(),
req_role_info.get_entity_type()
))?;
};
if !req_role_info.is_invitable() {
Err(report!(UserErrors::InvalidRoleId))
.attach_printable(format!("role_id = {} is not invitable", request.role_id))?;
}
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
let invitee_user = state.global_store.find_user_by_email(&invitee_email).await;
if let Ok(invitee_user) = invitee_user {
handle_existing_user_invitation(
state,
user_from_token,
request,
invitee_user.into(),
req_role_info,
auth_id,
)
.await
} else if invitee_user
.as_ref()
.map_err(|e| e.current_context().is_db_not_found())
.err()
.unwrap_or(false)
{
handle_new_user_invitation(
state,
user_from_token,
request,
req_role_info,
req_state.clone(),
auth_id,
)
.await
} else {
Err(UserErrors::InternalServerError.into())
}
}
#[allow(unused_variables)]
async fn handle_existing_user_invitation(
state: &SessionState,
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
invitee_user_from_db: domain::UserFromStorage,
role_info: roles::RoleInfo,
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
let now = common_utils::date_time::now();
if state
.global_store
.find_user_role_by_user_id_and_lineage_with_entity_type(
invitee_user_from_db.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
&user_from_token.merchant_id,
&user_from_token.profile_id,
UserRoleVersion::V1,
)
.await
.is_err_and(|err| err.current_context().is_db_not_found())
.not()
{
return Err(UserErrors::UserExists.into());
}
if state
.global_store
.find_user_role_by_user_id_and_lineage_with_entity_type(
invitee_user_from_db.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
&user_from_token.merchant_id,
&user_from_token.profile_id,
UserRoleVersion::V2,
)
.await
.is_err_and(|err| err.current_context().is_db_not_found())
.not()
{
return Err(UserErrors::UserExists.into());
}
let (org_id, merchant_id, profile_id) = match role_info.get_entity_type() {
EntityType::Tenant => {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Tenant roles are not allowed for this operation".to_string(),
)
.into());
}
EntityType::Organization => (Some(&user_from_token.org_id), None, None),
EntityType::Merchant => (
Some(&user_from_token.org_id),
Some(&user_from_token.merchant_id),
None,
),
EntityType::Profile => (
Some(&user_from_token.org_id),
Some(&user_from_token.merchant_id),
Some(&user_from_token.profile_id),
),
};
if state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: invitee_user_from_db.get_user_id(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id,
merchant_id,
profile_id,
entity_id: None,
version: None,
status: None,
limit: Some(1),
})
.await
.is_ok_and(|data| data.is_empty().not())
{
return Err(UserErrors::UserExists.into());
}
let user_role = domain::NewUserRole {
user_id: invitee_user_from_db.get_user_id().to_owned(),
role_id: request.role_id.clone(),
status: {
if cfg!(feature = "email") {
UserStatus::InvitationSent
} else {
UserStatus::Active
}
},
created_by: user_from_token.user_id.clone(),
last_modified_by: user_from_token.user_id.clone(),
created_at: now,
last_modified: now,
entity: domain::NoLevel,
};
let _user_role = match role_info.get_entity_type() {
EntityType::Tenant => {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Tenant roles are not allowed for this operation".to_string(),
)
.into());
}
EntityType::Organization => {
user_role
.add_entity(domain::OrganizationLevel {
tenant_id: user_from_token
.tenant_id
.clone()
.unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
})
.insert_in_v2(state)
.await?
}
EntityType::Merchant => {
user_role
.add_entity(domain::MerchantLevel {
tenant_id: user_from_token
.tenant_id
.clone()
.unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
})
.insert_in_v2(state)
.await?
}
EntityType::Profile => {
user_role
.add_entity(domain::ProfileLevel {
tenant_id: user_from_token
.tenant_id
.clone()
.unwrap_or(state.tenant.tenant_id.clone()),
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
profile_id: user_from_token.profile_id.clone(),
})
.insert_in_v2(state)
.await?
}
};
let is_email_sent;
#[cfg(feature = "email")]
{
let invitee_email = domain::UserEmail::from_pii_email(request.email.clone())?;
let entity = match role_info.get_entity_type() {
EntityType::Tenant => {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Tenant roles are not allowed for this operation".to_string(),
)
.into());
}
EntityType::Organization => email_types::Entity {
entity_id: user_from_token.org_id.get_string_repr().to_owned(),
entity_type: EntityType::Organization,
},
EntityType::Merchant => email_types::Entity {
entity_id: user_from_token.merchant_id.get_string_repr().to_owned(),
entity_type: EntityType::Merchant,
},
EntityType::Profile => email_types::Entity {
entity_id: user_from_token.profile_id.get_string_repr().to_owned(),
entity_type: EntityType::Profile,
},
};
let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
state,
user_from_token,
role_info.get_entity_type(),
)
.await?;
let email_contents = email_types::InviteUser {
recipient_email: invitee_email,
user_name: domain::UserName::new(invitee_user_from_db.get_name())?,
settings: state.conf.clone(),
entity,
auth_id: auth_id.clone(),
theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
theme_config: theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
};
is_email_sent = state
.email_client
.compose_and_send_email(
user_utils::get_base_url(state),
Box::new(email_contents),
state.conf.proxy.https_url.as_ref(),
)
.await
.map(|email_result| logger::info!(?email_result))
.map_err(|email_result| logger::error!(?email_result))
.is_ok();
}
#[cfg(not(feature = "email"))]
{
is_email_sent = false;
}
Ok(InviteMultipleUserResponse {
email: request.email.clone(),
is_email_sent,
password: None,
error: None,
})
}
#[allow(unused_variables)]
async fn handle_new_user_invitation(
state: &SessionState,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/refunds_v2.rs | crates/router/src/core/refunds_v2.rs | use std::{fmt::Debug, str::FromStr};
use api_models::{enums::Connector, refunds::RefundErrorDetails};
use common_utils::{id_type, types as common_utils_types};
use diesel_models::refund as diesel_refund;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
refunds::RefundListConstraints,
router_data::{ErrorResponse, RouterData},
router_data_v2::RefundFlowData,
};
use hyperswitch_interfaces::{
api::{Connector as ConnectorTrait, ConnectorIntegration},
connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},
integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject},
};
use router_env::{instrument, tracing};
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, StorageErrorExt},
payments::{self, access_token, gateway::context as gateway_context, helpers},
utils::{self as core_utils, refunds_validator},
},
db, logger,
routes::{metrics, SessionState},
services,
types::{
self,
api::{self, refunds},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils,
};
#[instrument(skip_all)]
pub async fn refund_create_core(
state: SessionState,
platform: domain::Platform,
req: refunds::RefundsCreateRequest,
global_refund_id: id_type::GlobalRefundId,
) -> errors::RouterResponse<refunds::RefundResponse> {
let db = &*state.store;
let (payment_intent, payment_attempt, amount);
payment_intent = db
.find_payment_intent_by_id(
&req.payment_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
utils::when(
!(payment_intent.status == enums::IntentStatus::Succeeded
|| payment_intent.status == enums::IntentStatus::PartiallyCaptured),
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: "refund".into(),
field_name: "status".into(),
current_value: payment_intent.status.to_string(),
states: "succeeded, partially_captured".to_string()
})
.attach_printable("unable to refund for a unsuccessful payment intent"))
},
)?;
let captured_amount = payment_intent
.amount_captured
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("amount captured is none in a successful payment")?;
// Amount is not passed in request refer from payment intent.
amount = req.amount.unwrap_or(captured_amount);
utils::when(amount <= common_utils_types::MinorUnit::new(0), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount".to_string(),
expected_format: "positive integer".to_string()
})
.attach_printable("amount less than or equal to zero"))
})?;
payment_attempt = db
.find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id(
platform.get_processor().get_key_store(),
&req.payment_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?;
tracing::Span::current().record("global_refund_id", global_refund_id.get_string_repr());
let merchant_connector_details = req.merchant_connector_details.clone();
Box::pin(validate_and_create_refund(
&state,
&platform,
&payment_attempt,
&payment_intent,
amount,
req,
global_refund_id,
merchant_connector_details,
))
.await
.map(services::ApplicationResponse::Json)
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
platform: &domain::Platform,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
return_raw_connector_response: Option<bool>,
) -> errors::RouterResult<(diesel_refund::Refund, Option<masking::Secret<String>>)> {
let db = &*state.store;
let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?;
let storage_scheme = platform.get_processor().get_account().storage_scheme;
let mca = db
.find_merchant_connector_account_by_id(&mca_id, platform.get_processor().get_key_store())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch merchant connector account")?;
metrics::REFUND_COUNT.add(
1,
router_env::metric_attributes!(("connector", mca_id.get_string_repr().to_string())),
);
let connector_enum = mca.connector_name;
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_enum.to_string(),
api::GetToken::Connector,
Some(mca_id.clone()),
)?;
refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca));
let mut router_data = core_utils::construct_refund_router_data(
state,
connector_enum,
platform,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let profile_id = payment_intent.profile_id.clone();
let default_gateway_context = gateway_context::RouterGatewayContext::direct(
platform.clone(),
merchant_connector_account,
payment_intent.merchant_id.clone(),
profile_id,
None,
);
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
&router_data,
None,
&default_gateway_context,
))
.await?;
logger::debug!(refund_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let connector_response = Box::pin(call_connector_service(
state,
&connector,
add_access_token_result,
router_data,
return_raw_connector_response,
))
.await;
let refund_update = get_refund_update_object(
state,
&connector,
&storage_scheme,
platform,
&connector_response,
)
.await;
let response = match refund_update {
Some(refund_update) => state
.store
.update_refund(
refund.to_owned(),
refund_update,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.id.get_string_repr()
)
})?,
None => refund.to_owned(),
};
let raw_connector_response = connector_response
.as_ref()
.ok()
.and_then(|data| data.raw_connector_response.clone());
// Implement outgoing webhooks here
connector_response.to_refund_failed_response()?;
Ok((response, raw_connector_response))
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn internal_trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
platform: &domain::Platform,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails,
return_raw_connector_response: Option<bool>,
) -> errors::RouterResult<(diesel_refund::Refund, Option<masking::Secret<String>>)> {
let storage_scheme = platform.get_processor().get_account().storage_scheme;
let routed_through = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve connector from payment attempt")?;
metrics::REFUND_COUNT.add(
1,
router_env::metric_attributes!(("connector", routed_through.clone())),
);
let connector_enum = merchant_connector_details.connector_name;
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_enum.to_string(),
api::GetToken::Connector,
None,
)?;
refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(
merchant_connector_details,
);
let mut router_data = core_utils::construct_refund_router_data(
state,
connector_enum,
platform,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let profile_id = payment_intent.profile_id.clone();
let default_gateway_context = gateway_context::RouterGatewayContext::direct(
platform.clone(),
merchant_connector_account,
payment_intent.merchant_id.clone(),
profile_id,
None,
);
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
&router_data,
None,
&default_gateway_context,
))
.await?;
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let connector_response = Box::pin(call_connector_service(
state,
&connector,
add_access_token_result,
router_data,
return_raw_connector_response,
))
.await;
let refund_update = get_refund_update_object(
state,
&connector,
&storage_scheme,
platform,
&connector_response,
)
.await;
let response = match refund_update {
Some(refund_update) => state
.store
.update_refund(
refund.to_owned(),
refund_update,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.id.get_string_repr()
)
})?,
None => refund.to_owned(),
};
let raw_connector_response = connector_response
.as_ref()
.ok()
.and_then(|data| data.raw_connector_response.clone());
// Implement outgoing webhooks here
connector_response.to_refund_failed_response()?;
Ok((response, raw_connector_response))
}
async fn call_connector_service<F>(
state: &SessionState,
connector: &api::ConnectorData,
add_access_token_result: types::AddAccessTokenResult,
router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>,
return_raw_connector_response: Option<bool>,
) -> Result<
RouterData<F, types::RefundsData, types::RefundsResponseData>,
error_stack::Report<errors::ConnectorError>,
>
where
F: Debug + Clone + 'static,
dyn ConnectorTrait + Sync:
ConnectorIntegration<F, types::RefundsData, types::RefundsResponseData>,
dyn ConnectorV2 + Sync:
ConnectorIntegrationV2<F, RefundFlowData, types::RefundsData, types::RefundsResponseData>,
{
if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
F,
types::RefundsData,
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
return_raw_connector_response,
)
.await
} else {
Ok(router_data)
}
}
async fn get_refund_update_object(
state: &SessionState,
connector: &api::ConnectorData,
storage_scheme: &enums::MerchantStorageScheme,
platform: &domain::Platform,
router_data_response: &Result<
RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>,
error_stack::Report<errors::ConnectorError>,
>,
) -> Option<diesel_refund::RefundUpdate> {
match router_data_response {
// This error is related to connector implementation i.e if no implementation for refunds for that specific connector in HS or the connector does not support refund itself.
Err(err) => get_connector_implementation_error_refund_update(err, *storage_scheme),
Ok(response) => {
let response = perform_integrity_check(response.clone());
match response.response.clone() {
Err(err) => Some(
get_connector_error_refund_update(state, err, connector, storage_scheme).await,
),
Ok(refund_response_data) => Some(get_refund_update_for_refund_response_data(
response,
connector,
refund_response_data,
storage_scheme,
platform,
)),
}
}
}
}
fn get_connector_implementation_error_refund_update(
error: &error_stack::Report<errors::ConnectorError>,
storage_scheme: enums::MerchantStorageScheme,
) -> Option<diesel_refund::RefundUpdate> {
Option::<diesel_refund::RefundUpdate>::foreign_from((error.current_context(), storage_scheme))
}
async fn get_connector_error_refund_update(
state: &SessionState,
err: ErrorResponse,
connector: &api::ConnectorData,
storage_scheme: &enums::MerchantStorageScheme,
) -> diesel_refund::RefundUpdate {
let unified_error_object = get_unified_error_and_message(state, &err, connector).await;
diesel_refund::RefundUpdate::build_error_update_for_unified_error_and_message(
unified_error_object,
err.reason.or(Some(err.message)),
Some(err.code),
storage_scheme,
)
}
async fn get_unified_error_and_message(
state: &SessionState,
err: &ErrorResponse,
connector: &api::ConnectorData,
) -> (String, String) {
let option_gsm = helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::REFUND_FLOW_STR,
consts::DEFAULT_SUBFLOW_STR,
)
.await;
// Note: Some connectors do not have a separate list of refund errors
// In such cases, the error codes and messages are stored under "Authorize" flow in GSM table
// So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow"
let option_gsm = if option_gsm.is_none() {
helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::PAYMENT_FLOW_STR,
consts::AUTHORIZE_FLOW_STR,
)
.await
} else {
option_gsm
};
let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());
let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message);
match gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref()) {
Some((code, message)) => (code.to_owned(), message.to_owned()),
None => (
consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(),
consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(),
),
}
}
pub fn get_refund_update_for_refund_response_data(
router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>,
connector: &api::ConnectorData,
refund_response_data: types::RefundsResponseData,
storage_scheme: &enums::MerchantStorageScheme,
platform: &domain::Platform,
) -> diesel_refund::RefundUpdate {
// match on connector integrity checks
match router_data.integrity_check.clone() {
Err(err) => {
let connector_refund_id = err
.connector_transaction_id
.map(common_utils_types::ConnectorTransactionId::from);
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
(
"merchant_id",
platform.get_processor().get_account().get_id().clone()
),
),
);
diesel_refund::RefundUpdate::build_error_update_for_integrity_check_failure(
err.field_names,
connector_refund_id,
storage_scheme,
)
}
Ok(()) => {
if refund_response_data.refund_status == diesel_models::enums::RefundStatus::Success {
metrics::SUCCESSFUL_REFUND.add(
1,
router_env::metric_attributes!((
"connector",
connector.connector_name.to_string(),
)),
)
}
let connector_refund_id = common_utils_types::ConnectorTransactionId::from(
refund_response_data.connector_refund_id,
);
diesel_refund::RefundUpdate::build_refund_update(
connector_refund_id,
refund_response_data.refund_status,
storage_scheme,
)
}
}
}
pub fn perform_integrity_check<F>(
mut router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>,
) -> RouterData<F, types::RefundsData, types::RefundsResponseData>
where
F: Debug + Clone + 'static,
{
// Initiating Integrity check
let integrity_result = check_refund_integrity(&router_data.request, &router_data.response);
router_data.integrity_check = integrity_result;
router_data
}
impl ForeignFrom<(&errors::ConnectorError, enums::MerchantStorageScheme)>
for Option<diesel_refund::RefundUpdate>
{
fn foreign_from(
(from, storage_scheme): (&errors::ConnectorError, enums::MerchantStorageScheme),
) -> Self {
match from {
errors::ConnectorError::NotImplemented(message) => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(
errors::ConnectorError::NotImplemented(message.to_owned()).to_string(),
),
refund_error_code: Some("NOT_IMPLEMENTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
})
}
errors::ConnectorError::FlowNotSupported { flow, connector } => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(format!("{flow} is not supported by {connector}")),
refund_error_code: Some("NOT_SUPPORTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
})
}
errors::ConnectorError::NotSupported { message, connector } => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(format!(
"{message} is not supported by {connector}"
)),
refund_error_code: Some("NOT_SUPPORTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
})
}
_ => None,
}
}
}
pub fn check_refund_integrity<T, Request>(
request: &Request,
refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>,
) -> Result<(), common_utils::errors::IntegrityCheckError>
where
T: FlowIntegrity,
Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>,
{
let connector_refund_id = refund_response_data
.as_ref()
.map(|resp_data| resp_data.connector_refund_id.clone())
.ok();
request.check_integrity(request, connector_refund_id.to_owned())
}
// ********************************************** REFUND UPDATE **********************************************
pub async fn refund_metadata_update_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
req: refunds::RefundMetadataUpdateRequest,
global_refund_id: id_type::GlobalRefundId,
) -> errors::RouterResponse<refunds::RefundResponse> {
let db = state.store.as_ref();
let refund = db
.find_refund_by_id(&global_refund_id, merchant_account.storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let response = db
.update_refund(
refund,
diesel_refund::RefundUpdate::MetadataAndReasonUpdate {
metadata: req.metadata,
reason: req.reason,
updated_by: merchant_account.storage_scheme.to_string(),
},
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Unable to update refund with refund_id: {}",
global_refund_id.get_string_repr()
)
})?;
refunds::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json)
}
// ********************************************** REFUND SYNC **********************************************
#[instrument(skip_all)]
pub async fn refund_retrieve_core_with_refund_id(
state: SessionState,
platform: domain::Platform,
profile: domain::Profile,
request: refunds::RefundsRetrieveRequest,
) -> errors::RouterResponse<refunds::RefundResponse> {
let refund_id = request.refund_id.clone();
let db = &*state.store;
let profile_id = profile.get_id().to_owned();
let refund = db
.find_refund_by_id(
&refund_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let (response, raw_connector_response) = Box::pin(refund_retrieve_core(
state.clone(),
platform,
Some(profile_id),
request,
refund,
))
.await?;
api::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json)
}
#[instrument(skip_all)]
pub async fn refund_retrieve_core(
state: SessionState,
platform: domain::Platform,
profile_id: Option<id_type::ProfileId>,
request: refunds::RefundsRetrieveRequest,
refund: diesel_refund::Refund,
) -> errors::RouterResult<(diesel_refund::Refund, Option<masking::Secret<String>>)> {
let db = &*state.store;
core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?;
let payment_id = &refund.payment_id;
let payment_intent = db
.find_payment_intent_by_id(
payment_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let active_attempt_id = payment_intent
.active_attempt_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Active attempt id not found")?;
let payment_attempt = db
.find_payment_attempt_by_id(
platform.get_processor().get_key_store(),
&active_attempt_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let unified_translated_message = if let (Some(unified_code), Some(unified_message)) =
(refund.unified_code.clone(), refund.unified_message.clone())
{
helpers::get_unified_translation(
&state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message))
} else {
refund.unified_message
};
let refund = diesel_refund::Refund {
unified_message: unified_translated_message,
..refund
};
let (response, raw_connector_response) = if should_call_refund(
&refund,
request.force_sync.unwrap_or(false),
request.return_raw_connector_response.unwrap_or(false),
) {
if state.conf.merchant_id_auth.merchant_id_auth_enabled {
let merchant_connector_details = match request.merchant_connector_details {
Some(details) => details,
None => {
return Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_connector_details"
}));
}
};
Box::pin(internal_sync_refund_with_gateway(
&state,
&platform,
&payment_attempt,
&payment_intent,
&refund,
merchant_connector_details,
request.return_raw_connector_response,
))
.await
} else {
Box::pin(sync_refund_with_gateway(
&state,
&platform,
&payment_attempt,
&payment_intent,
&refund,
request.return_raw_connector_response,
))
.await
}
} else {
Ok((refund, None))
}?;
Ok((response, raw_connector_response))
}
fn should_call_refund(
refund: &diesel_models::refund::Refund,
force_sync: bool,
return_raw_connector_response: bool,
) -> bool {
// This implies, we cannot perform a refund sync & `the connector_refund_id`
// doesn't exist
let predicate1 = refund.connector_refund_id.is_some();
// This allows refund sync at connector level if force_sync is enabled, or
// checks if the refund has failed
let predicate2 = return_raw_connector_response
|| force_sync
|| !matches!(
refund.refund_status,
diesel_models::enums::RefundStatus::Failure
| diesel_models::enums::RefundStatus::Success
);
predicate1 && predicate2
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn sync_refund_with_gateway(
state: &SessionState,
platform: &domain::Platform,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &diesel_refund::Refund,
return_raw_connector_response: Option<bool>,
) -> errors::RouterResult<(diesel_refund::Refund, Option<masking::Secret<String>>)> {
let db = &*state.store;
let connector_id = refund.connector.to_string();
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_id,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector")?;
let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?;
let mca = db
.find_merchant_connector_account_by_id(&mca_id, platform.get_processor().get_key_store())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch merchant connector account")?;
let connector_enum = mca.connector_name;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca));
let mut router_data = core_utils::construct_refund_router_data::<api::RSync>(
state,
connector_enum,
platform,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let profile_id = payment_intent.profile_id.clone();
let default_gateway_context = gateway_context::RouterGatewayContext::direct(
platform.clone(),
merchant_connector_account,
payment_intent.merchant_id.clone(),
profile_id,
None,
);
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
&router_data,
None,
&default_gateway_context,
))
.await?;
logger::debug!(refund_retrieve_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let connector_response = Box::pin(call_connector_service(
state,
&connector,
add_access_token_result,
router_data,
return_raw_connector_response,
))
.await
.to_refund_failed_response()?;
let connector_response = perform_integrity_check(connector_response);
let refund_update =
build_refund_update_for_rsync(&connector, platform, connector_response.clone());
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)
.attach_printable_lazy(|| {
format!(
"Unable to update refund with refund_id: {}",
refund.id.get_string_repr()
)
})?;
// Implement outgoing webhook here
Ok((response, connector_response.raw_connector_response))
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn internal_sync_refund_with_gateway(
state: &SessionState,
platform: &domain::Platform,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &diesel_refund::Refund,
merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails,
return_raw_connector_response: Option<bool>,
) -> errors::RouterResult<(diesel_refund::Refund, Option<masking::Secret<String>>)> {
let connector_enum = merchant_connector_details.connector_name;
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_enum.to_string(),
api::GetToken::Connector,
None,
)?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(
merchant_connector_details,
);
let mut router_data = core_utils::construct_refund_router_data::<api::RSync>(
state,
connector_enum,
platform,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/blocklist.rs | crates/router/src/core/blocklist.rs | pub mod transformers;
pub mod utils;
use api_models::blocklist as api_blocklist;
use crate::{
core::errors::{self, RouterResponse},
routes::SessionState,
services,
types::domain,
};
pub async fn add_entry_to_blocklist(
state: SessionState,
platform: domain::Platform,
body: api_blocklist::AddToBlocklistRequest,
) -> RouterResponse<api_blocklist::AddToBlocklistResponse> {
utils::insert_entry_into_blocklist(
&state,
platform.get_processor().get_account().get_id(),
body,
)
.await
.map(services::ApplicationResponse::Json)
}
pub async fn remove_entry_from_blocklist(
state: SessionState,
platform: domain::Platform,
body: api_blocklist::DeleteFromBlocklistRequest,
) -> RouterResponse<api_blocklist::DeleteFromBlocklistResponse> {
utils::delete_entry_from_blocklist(
&state,
platform.get_processor().get_account().get_id(),
body,
)
.await
.map(services::ApplicationResponse::Json)
}
pub async fn list_blocklist_entries(
state: SessionState,
platform: domain::Platform,
query: api_blocklist::ListBlocklistQuery,
) -> RouterResponse<Vec<api_blocklist::BlocklistResponse>> {
utils::list_blocklist_entries_for_merchant(
&state,
platform.get_processor().get_account().get_id(),
query,
)
.await
.map(services::ApplicationResponse::Json)
}
pub async fn toggle_blocklist_guard(
state: SessionState,
platform: domain::Platform,
query: api_blocklist::ToggleBlocklistQuery,
) -> RouterResponse<api_blocklist::ToggleBlocklistResponse> {
utils::toggle_blocklist_guard_for_merchant(
&state,
platform.get_processor().get_account().get_id(),
query,
)
.await
.map(services::ApplicationResponse::Json)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/connector_onboarding.rs | crates/router/src/core/connector_onboarding.rs | use api_models::{connector_onboarding as api, enums};
use masking::Secret;
use crate::{
core::errors::{ApiErrorResponse, RouterResponse, RouterResult},
routes::app::ReqState,
services::{authentication as auth, ApplicationResponse},
types as oss_types,
utils::connector_onboarding as utils,
SessionState,
};
pub mod paypal;
#[async_trait::async_trait]
pub trait AccessToken {
async fn access_token(state: &SessionState) -> RouterResult<oss_types::AccessToken>;
}
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()),
}
}
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()),
}
}
pub async fn reset_tracking_id(
state: SessionState,
user_from_token: auth::UserFromToken,
request: api::ResetTrackingIdRequest,
_req_state: ReqState,
) -> RouterResponse<()> {
utils::check_if_connector_exists(&state, &request.connector_id, &user_from_token.merchant_id)
.await?;
utils::set_tracking_id_in_configs(&state, &request.connector_id, request.connector).await?;
Ok(ApplicationResponse::StatusOk)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payment_method_balance.rs | crates/router/src/core/payment_method_balance.rs | use std::{collections::HashMap, marker::PhantomData};
use api_models::payments::{
ApplyPaymentMethodDataRequest, CheckAndApplyPaymentMethodDataResponse, GetPaymentMethodType,
PMBalanceCheckFailureResponse, PMBalanceCheckSuccessResponse,
};
use common_enums::CallConnectorAction;
use common_utils::{
ext_traits::{Encode, StringExt},
id_type,
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payments::HeaderPayload,
router_data_v2::{flow_common_types::GiftCardBalanceCheckFlowData, RouterDataV2},
router_flow_types::GiftCardBalanceCheck,
router_request_types::GiftCardBalanceCheckRequestData,
router_response_types::GiftCardBalanceCheckResponseData,
};
use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion;
use masking::ExposeInterface;
use router_env::{instrument, tracing};
use crate::{
consts,
core::{
errors::{self, RouterResponse},
payments::helpers,
},
db::errors::StorageErrorExt,
routes::{app::ReqState, SessionState},
services::{self, logger},
types::{api, domain},
};
#[allow(clippy::too_many_arguments)]
pub async fn payments_check_gift_card_balance_core(
state: &SessionState,
platform: &domain::Platform,
profile: &domain::Profile,
_req_state: &ReqState,
payment_method_data: api_models::payments::BalanceCheckPaymentMethodData,
payment_id: &id_type::GlobalPaymentId,
) -> errors::RouterResult<(MinorUnit, common_enums::Currency)> {
let db = state.store.as_ref();
let storage_scheme = platform.get_processor().get_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
payment_id,
platform.get_processor().get_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let redis_conn = db
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not get redis connection")?;
let gift_card_connector_id: String = redis_conn
.get_key(&payment_id.get_gift_card_connector_key().as_str().into())
.await
.attach_printable("Failed to fetch gift card connector from redis")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "No connector found with Gift Card Support".to_string(),
})?;
let gift_card_connector_id = id_type::MerchantConnectorAccountId::wrap(gift_card_connector_id)
.attach_printable("Failed to deserialize MCA")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "No connector found with Gift Card Support".to_string(),
})?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
platform.get_processor().get_key_store(),
Some(&gift_card_connector_id),
)
.await
.attach_printable(
"failed to fetch merchant connector account for gift card balance check",
)?,
));
let connector_name = merchant_connector_account
.get_connector_name()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector name not present for gift card balance check")?; // always get the connector name from this call
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name.to_string(),
api::GetToken::Connector,
merchant_connector_account.get_mca_id(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_auth_type = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let resource_common_data = GiftCardBalanceCheckFlowData;
let api_models::payments::BalanceCheckPaymentMethodData::GiftCard(gift_card_data) =
payment_method_data;
let router_data: RouterDataV2<
GiftCardBalanceCheck,
GiftCardBalanceCheckFlowData,
GiftCardBalanceCheckRequestData,
GiftCardBalanceCheckResponseData,
> = RouterDataV2 {
flow: PhantomData,
resource_common_data,
tenant_id: state.tenant.tenant_id.clone(),
connector_auth_type,
request: GiftCardBalanceCheckRequestData {
payment_method_data: domain::PaymentMethodData::GiftCard(Box::new(
gift_card_data.clone().into(),
)),
currency: Some(payment_intent.amount_details.currency),
minor_amount: Some(payment_intent.amount_details.order_amount),
},
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
};
let old_router_data = GiftCardBalanceCheckFlowData::to_old_router_data(router_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Cannot construct router data for making the gift card balance check api call",
)?;
let connector_integration: services::BoxedGiftCardBalanceCheckIntegrationInterface<
GiftCardBalanceCheck,
GiftCardBalanceCheckRequestData,
GiftCardBalanceCheckResponseData,
> = connector_data.connector.get_connector_integration();
let connector_response = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while calling gift card balance check connector api")?;
let gift_card_balance = connector_response
.response
.map_err(|_| errors::ApiErrorResponse::UnprocessableEntity {
message: "Error while fetching gift card balance".to_string(),
})
.attach_printable("Connector returned invalid response")?;
let balance = gift_card_balance.balance;
let currency = gift_card_balance.currency;
let payment_method_key = domain::GiftCardData::from(gift_card_data.clone())
.get_payment_method_key()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Unable to get unique key for payment method".to_string(),
})?
.expose();
let balance_data = domain::PaymentMethodBalanceData {
payment_intent_id: &payment_intent.id,
pm_balance_data: vec![(
domain::PaymentMethodBalanceKey {
payment_method_type: common_enums::PaymentMethod::GiftCard,
payment_method_subtype: gift_card_data.get_payment_method_type(),
payment_method_key,
},
domain::PaymentMethodBalance { balance, currency },
)]
.into_iter()
.collect(),
};
persist_individual_pm_balance_details_in_redis(state, profile, &balance_data)
.await
.attach_printable("Failed to persist gift card balance details in redis")?;
let resp = (balance, currency);
Ok(resp)
}
#[allow(clippy::too_many_arguments)]
pub async fn payments_check_and_apply_pm_data_core(
state: SessionState,
platform: domain::Platform,
profile: domain::Profile,
_req_state: ReqState,
req: ApplyPaymentMethodDataRequest,
payment_id: id_type::GlobalPaymentId,
) -> RouterResponse<CheckAndApplyPaymentMethodDataResponse> {
let db = state.store.as_ref();
let storage_scheme = platform.get_processor().get_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
&payment_id,
platform.get_processor().get_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_method_balances = fetch_payment_methods_balances_from_redis_fallible(
&state,
&payment_intent.id,
&req.payment_methods,
)
.await
.attach_printable("Failed to retrieve payment method balances from redis")?;
let mut balance_values: Vec<api_models::payments::EligibilityBalanceCheckResponseItem> =
futures::future::join_all(req.payment_methods.into_iter().map(|pm| async {
let api_models::payments::BalanceCheckPaymentMethodData::GiftCard(gift_card_data) =
pm.clone();
let pm_balance_key = domain::PaymentMethodBalanceKey {
payment_method_type: common_enums::PaymentMethod::GiftCard,
payment_method_subtype: gift_card_data.get_payment_method_type(),
payment_method_key: domain::GiftCardData::from(gift_card_data.clone())
.get_payment_method_key()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Unable to get unique key for payment method".to_string(),
})?
.expose(),
};
let eligibility = match payment_method_balances
.get(&pm_balance_key)
.and_then(|inner| inner.as_ref())
{
Some(balance) => {
api_models::payments::PMBalanceCheckEligibilityResponse::Success(
PMBalanceCheckSuccessResponse {
balance: balance.balance,
applicable_amount: MinorUnit::zero(), // Will be calculated after sorting
currency: balance.currency,
},
)
}
None => {
match payments_check_gift_card_balance_core(
&state,
&platform,
&profile,
&_req_state,
pm.clone(),
&payment_id,
)
.await
{
Ok((balance, currency)) => {
api_models::payments::PMBalanceCheckEligibilityResponse::Success(
PMBalanceCheckSuccessResponse {
balance,
applicable_amount: MinorUnit::zero(), // Will be calculated after sorting
currency,
},
)
}
Err(err) => {
api_models::payments::PMBalanceCheckEligibilityResponse::Failure(
PMBalanceCheckFailureResponse {
error: err.to_string(),
},
)
}
}
}
};
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(
api_models::payments::EligibilityBalanceCheckResponseItem {
payment_method_data: pm,
eligibility,
},
)
}))
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()?;
// Sort balance_values by balance in ascending order (smallest first)
// This ensures smaller gift cards are fully utilized before larger ones
balance_values.sort_by(|a, b| {
a.eligibility
.get_balance()
.cmp(&b.eligibility.get_balance())
});
// Calculate applicable amounts with running total
let mut running_total = MinorUnit::zero();
let order_amount = payment_intent.amount_details.order_amount;
for balance_item in balance_values.iter_mut() {
if let api_models::payments::PMBalanceCheckEligibilityResponse::Success(balance_api) =
&mut balance_item.eligibility
{
let remaining_amount = (order_amount - running_total).max(MinorUnit::zero());
balance_api.applicable_amount = std::cmp::min(balance_api.balance, remaining_amount);
running_total = running_total + balance_api.applicable_amount;
}
}
let total_applicable_balance = running_total;
// remaining_amount cannot be negative, hence using max with 0. This situation can arise when
// the gift card balance exceeds the order amount
let remaining_amount = (payment_intent.amount_details.order_amount - total_applicable_balance)
.max(MinorUnit::zero());
let resp = CheckAndApplyPaymentMethodDataResponse {
balances: balance_values,
remaining_amount,
currency: payment_intent.amount_details.currency,
requires_additional_pm_data: remaining_amount.is_greater_than(0),
surcharge_details: None, // TODO: Implement surcharge recalculation logic
};
Ok(services::ApplicationResponse::Json(resp))
}
#[instrument(skip_all)]
pub async fn persist_individual_pm_balance_details_in_redis<'a>(
state: &SessionState,
business_profile: &domain::Profile,
pm_balance_data: &domain::PaymentMethodBalanceData<'_>,
) -> errors::RouterResult<()> {
if !pm_balance_data.is_empty() {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let redis_key = pm_balance_data.get_pm_balance_redis_key();
let value_list = pm_balance_data
.get_individual_pm_balance_key_value_pairs()
.into_iter()
.map(|(key, value)| {
value
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode to string of json")
.map(|encoded_value| (key, encoded_value))
})
.collect::<Result<Vec<_>, _>>()?;
let intent_fulfillment_time = business_profile
.get_order_fulfillment_time()
.unwrap_or(consts::DEFAULT_FULFILLMENT_TIME);
redis_conn
.set_hash_fields(
&redis_key.as_str().into(),
value_list,
Some(intent_fulfillment_time),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to write to redis")?;
logger::debug!("Surcharge results stored in redis with key = {}", redis_key);
}
Ok(())
}
pub async fn fetch_payment_methods_balances_from_redis(
state: &SessionState,
payment_intent_id: &id_type::GlobalPaymentId,
payment_methods: &[api_models::payments::BalanceCheckPaymentMethodData],
) -> errors::RouterResult<HashMap<domain::PaymentMethodBalanceKey, domain::PaymentMethodBalance>> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let balance_data = domain::PaymentMethodBalanceData::new(payment_intent_id);
let balance_values: HashMap<String, domain::PaymentMethodBalance> = redis_conn
.get_hash_fields::<Vec<(String, String)>>(&balance_data.get_pm_balance_redis_key().into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to read payment method balance data from redis")?
.into_iter()
.map(|(key, value)| {
value
.parse_struct("PaymentMethodBalance")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse PaymentMethodBalance")
.map(|parsed| (key, parsed))
})
.collect::<errors::RouterResult<HashMap<_, _>>>()?;
payment_methods
.iter()
.map(|pm| {
let api_models::payments::BalanceCheckPaymentMethodData::GiftCard(gift_card_data) = pm;
let pm_balance_key = domain::PaymentMethodBalanceKey {
payment_method_type: common_enums::PaymentMethod::GiftCard,
payment_method_subtype: gift_card_data.get_payment_method_type(),
payment_method_key: domain::GiftCardData::from(gift_card_data.clone())
.get_payment_method_key()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Unable to get unique key for payment method".to_string(),
})?
.expose(),
};
let redis_key = pm_balance_key.get_redis_key();
let balance_value = balance_values.get(&redis_key).cloned().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "Balance not found for one or more payment methods".to_string(),
},
)?;
Ok((pm_balance_key, balance_value))
})
.collect::<errors::RouterResult<HashMap<_, _>>>()
}
/// This function does not return an error if balance for a payment method is not found, it just sets
/// the corresponding value in the HashMap to None
pub async fn fetch_payment_methods_balances_from_redis_fallible(
state: &SessionState,
payment_intent_id: &id_type::GlobalPaymentId,
payment_methods: &[api_models::payments::BalanceCheckPaymentMethodData],
) -> errors::RouterResult<
HashMap<domain::PaymentMethodBalanceKey, Option<domain::PaymentMethodBalance>>,
> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let balance_data = domain::PaymentMethodBalanceData::new(payment_intent_id);
let balance_values: HashMap<String, domain::PaymentMethodBalance> = redis_conn
.get_hash_fields::<Vec<(String, String)>>(&balance_data.get_pm_balance_redis_key().into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to read payment method balance data from redis")?
.into_iter()
.map(|(key, value)| {
value
.parse_struct("PaymentMethodBalance")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse PaymentMethodBalance")
.map(|parsed| (key, parsed))
})
.collect::<errors::RouterResult<HashMap<_, _>>>()?;
payment_methods
.iter()
.map(|pm| {
let api_models::payments::BalanceCheckPaymentMethodData::GiftCard(gift_card_data) = pm;
let pm_balance_key = domain::PaymentMethodBalanceKey {
payment_method_type: common_enums::PaymentMethod::GiftCard,
payment_method_subtype: gift_card_data.get_payment_method_type(),
payment_method_key: domain::GiftCardData::from(gift_card_data.clone())
.get_payment_method_key()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Unable to get unique key for payment method".to_string(),
})?
.expose(),
};
let redis_key = pm_balance_key.get_redis_key();
let balance_value = balance_values.get(&redis_key).cloned();
Ok((pm_balance_key, balance_value))
})
.collect::<errors::RouterResult<HashMap<_, _>>>()
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check.rs | crates/router/src/core/fraud_check.rs | use std::fmt::Debug;
use api_models::{self, enums as api_enums};
use common_enums::CaptureMethod;
use error_stack::ResultExt;
use masking::PeekInterface;
use router_env::{
logger,
tracing::{self, instrument},
};
use self::{
flows::{self as frm_flows, FeatureFrm},
types::{
self as frm_core_types, ConnectorDetailsCore, FrmConfigsObject, FrmData, FrmInfo,
PaymentDetails, PaymentToFrmData,
},
};
use super::errors::{ConnectorErrorExt, RouterResponse};
use crate::{
core::{
errors::{self, RouterResult},
payments::{self, flows::ConstructFlowSpecificData, operations::BoxedOperation},
},
db::StorageInterface,
routes::{app::ReqState, SessionState},
services,
types::{
self as oss_types,
api::{
fraud_check as frm_api, routing::FrmRoutingAlgorithm, Connector,
FraudCheckConnectorData, Fulfillment,
},
domain, fraud_check as frm_types,
storage::{
enums::{
AttemptStatus, FraudCheckLastStep, FraudCheckStatus, FraudCheckType, FrmSuggestion,
IntentStatus,
},
fraud_check::{FraudCheck, FraudCheckUpdate},
PaymentIntent,
},
},
utils::ValueExt,
};
pub mod flows;
pub mod operation;
pub mod types;
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn call_frm_service<D: Clone, F, Req, OperationData>(
state: &SessionState,
payment_data: &OperationData,
frm_data: &mut FrmData,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
) -> RouterResult<oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>>
where
F: Send + Clone,
OperationData: payments::OperationSessionGetters<D> + Send + Sync + Clone,
// To create connector flow specific interface data
FrmData: ConstructFlowSpecificData<F, Req, frm_types::FraudCheckResponseData>,
oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>: FeatureFrm<F, Req> + Send,
// To construct connector flow specific api
dyn Connector: services::api::ConnectorIntegration<F, Req, frm_types::FraudCheckResponseData>,
{
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn call_frm_service<D: Clone, F, Req, OperationData>(
state: &SessionState,
payment_data: &OperationData,
frm_data: &mut FrmData,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
) -> RouterResult<oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>>
where
F: Send + Clone,
OperationData: payments::OperationSessionGetters<D> + Send + Sync + Clone,
// To create connector flow specific interface data
FrmData: ConstructFlowSpecificData<F, Req, frm_types::FraudCheckResponseData>,
oss_types::RouterData<F, Req, frm_types::FraudCheckResponseData>: FeatureFrm<F, Req> + Send,
// To construct connector flow specific api
dyn Connector: services::api::ConnectorIntegration<F, Req, frm_types::FraudCheckResponseData>,
{
let merchant_connector_account = payments::construct_profile_id_and_get_mca(
state,
platform,
payment_data,
&frm_data.connector_details.connector_name,
None,
false,
)
.await?;
frm_data
.payment_attempt
.connector_transaction_id
.clone_from(&payment_data.get_payment_attempt().connector_transaction_id);
let mut router_data = frm_data
.construct_router_data(
state,
&frm_data.connector_details.connector_name,
platform,
customer,
&merchant_connector_account,
None,
None,
None,
None,
)
.await?;
router_data.status = payment_data.get_payment_attempt().status;
if matches!(
frm_data.fraud_check.frm_transaction_type,
FraudCheckType::PreFrm
) && matches!(
frm_data.fraud_check.last_step,
FraudCheckLastStep::CheckoutOrSale
) {
frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund
}
let connector =
FraudCheckConnectorData::get_connector_by_name(&frm_data.connector_details.connector_name)?;
let router_data_res = router_data
.decide_frm_flows(
state,
&connector,
payments::CallConnectorAction::Trigger,
platform,
)
.await?;
Ok(router_data_res)
}
#[cfg(feature = "v2")]
pub async fn should_call_frm<F, D>(
_platform: &domain::Platform,
_payment_data: &D,
_state: &SessionState,
) -> RouterResult<(
bool,
Option<FrmRoutingAlgorithm>,
Option<common_utils::id_type::ProfileId>,
Option<FrmConfigsObject>,
)>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
// Frm routing algorithm is not present in the merchant account
// it has to be fetched from the business profile
todo!()
}
#[cfg(feature = "v1")]
pub async fn should_call_frm<F, D>(
platform: &domain::Platform,
payment_data: &D,
state: &SessionState,
) -> RouterResult<(
bool,
Option<FrmRoutingAlgorithm>,
Option<common_utils::id_type::ProfileId>,
Option<FrmConfigsObject>,
)>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
use common_utils::ext_traits::OptionExt;
use masking::ExposeInterface;
let db = &*state.store;
match platform
.get_processor()
.get_account()
.frm_routing_algorithm
.clone()
{
Some(frm_routing_algorithm_value) => {
let frm_routing_algorithm_struct: FrmRoutingAlgorithm = frm_routing_algorithm_value
.clone()
.parse_value("FrmRoutingAlgorithm")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "frm_routing_algorithm",
})
.attach_printable("Data field not found in frm_routing_algorithm")?;
let profile_id = payment_data
.get_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();
#[cfg(feature = "v1")]
let merchant_connector_account_from_db_option = db
.find_merchant_connector_account_by_profile_id_connector_name(
&profile_id,
&frm_routing_algorithm_struct.data,
platform.get_processor().get_key_store(),
)
.await
.map_err(|error| {
logger::error!(
"{:?}",
error.change_context(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: platform
.get_processor()
.get_account()
.get_id()
.get_string_repr()
.to_owned(),
}
)
)
})
.ok();
let enabled_merchant_connector_account_from_db_option =
merchant_connector_account_from_db_option.and_then(|mca| {
if mca.disabled.unwrap_or(false) {
logger::info!("No eligible connector found for FRM");
None
} else {
Some(mca)
}
});
#[cfg(feature = "v2")]
let merchant_connector_account_from_db_option: Option<
domain::MerchantConnectorAccount,
> = {
let _ = key_store;
let _ = frm_routing_algorithm_struct;
let _ = profile_id;
todo!()
};
match enabled_merchant_connector_account_from_db_option {
Some(merchant_connector_account_from_db) => {
let frm_configs_option = merchant_connector_account_from_db
.frm_configs
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "frm_configs",
})
.ok();
match frm_configs_option {
Some(frm_configs_value) => {
let frm_configs_struct: Vec<api_models::admin::FrmConfigs> = frm_configs_value
.into_iter()
.map(|config| { config
.expose()
.parse_value("FrmConfigs")
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "frm_configs".to_string(),
expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","flow": "post"}]}]"#.to_string(),
})
})
.collect::<Result<Vec<_>, _>>()?;
let mut is_frm_connector_enabled = false;
let mut is_frm_pm_enabled = false;
let connector = payment_data.get_payment_attempt().connector.clone();
let filtered_frm_config = frm_configs_struct
.iter()
.filter(|frm_config| match (&connector, &frm_config.gateway) {
(Some(current_connector), Some(configured_connector)) => {
let is_enabled =
*current_connector == configured_connector.to_string();
if is_enabled {
is_frm_connector_enabled = true;
}
is_enabled
}
(None, _) | (_, None) => true,
})
.collect::<Vec<_>>();
let filtered_payment_methods = filtered_frm_config
.iter()
.map(|frm_config| {
let filtered_frm_config_by_pm = frm_config
.payment_methods
.iter()
.filter(|frm_config_pm| {
match (
payment_data.get_payment_attempt().payment_method,
frm_config_pm.payment_method,
) {
(
Some(current_pm),
Some(configured_connector_pm),
) => {
let is_enabled = current_pm.to_string()
== configured_connector_pm.to_string();
if is_enabled {
is_frm_pm_enabled = true;
}
is_enabled
}
(None, _) | (_, None) => true,
}
})
.collect::<Vec<_>>();
filtered_frm_config_by_pm
})
.collect::<Vec<_>>()
.concat();
let is_frm_enabled = is_frm_connector_enabled && is_frm_pm_enabled;
logger::debug!(
"is_frm_connector_enabled {:?}, is_frm_pm_enabled: {:?}, is_frm_enabled :{:?}",
is_frm_connector_enabled,
is_frm_pm_enabled,
is_frm_enabled
);
// filtered_frm_config...
// Panic Safety: we are first checking if the object is present... only if present, we try to fetch index 0
let frm_configs_object = FrmConfigsObject {
frm_enabled_gateway: filtered_frm_config
.first()
.and_then(|c| c.gateway),
frm_enabled_pm: filtered_payment_methods
.first()
.and_then(|pm| pm.payment_method),
// flow type should be consumed from payment_method.flow. To provide backward compatibility, if we don't find it there, we consume it from payment_method.payment_method_types[0].flow_type.
frm_preferred_flow_type: filtered_payment_methods
.first()
.and_then(|pm| pm.flow.clone())
.or(filtered_payment_methods.first().and_then(|pm| {
pm.payment_method_types.as_ref().and_then(|pmt| {
pmt.first().map(|pmts| pmts.flow.clone())
})
}))
.ok_or(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "frm_configs".to_string(),
expected_format: r#"[{ "gateway": "stripe", "payment_methods": [{ "payment_method": "card","flow": "post"}]}]"#.to_string(),
})?,
};
logger::debug!(
"frm_routing_configs: {:?} {:?} {:?} {:?}",
frm_routing_algorithm_struct,
profile_id,
frm_configs_object,
is_frm_enabled
);
Ok((
is_frm_enabled,
Some(frm_routing_algorithm_struct),
Some(profile_id),
Some(frm_configs_object),
))
}
None => {
logger::error!("Cannot find frm_configs for FRM provider");
Ok((false, None, None, None))
}
}
}
None => {
logger::error!("Cannot find merchant connector account for FRM provider");
Ok((false, None, None, None))
}
}
}
_ => Ok((false, None, None, None)),
}
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn make_frm_data_and_fraud_check_operation<F, D>(
_db: &dyn StorageInterface,
state: &SessionState,
platform: &domain::Platform,
payment_data: D,
frm_routing_algorithm: FrmRoutingAlgorithm,
profile_id: common_utils::id_type::ProfileId,
frm_configs: FrmConfigsObject,
_customer: &Option<domain::Customer>,
) -> RouterResult<FrmInfo<F, D>>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
todo!()
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn make_frm_data_and_fraud_check_operation<F, D>(
_db: &dyn StorageInterface,
state: &SessionState,
platform: &domain::Platform,
payment_data: D,
frm_routing_algorithm: FrmRoutingAlgorithm,
profile_id: common_utils::id_type::ProfileId,
frm_configs: FrmConfigsObject,
_customer: &Option<domain::Customer>,
) -> RouterResult<FrmInfo<F, D>>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
let order_details = payment_data
.get_payment_intent()
.order_details
.clone()
.or_else(||
// when the order_details are present within the meta_data, we need to take those to support backward compatibility
payment_data.get_payment_intent().metadata.clone().and_then(|meta| {
let order_details = meta.get("order_details").to_owned();
order_details.map(|order| vec![masking::Secret::new(order.to_owned())])
}))
.map(|order_details_value| {
order_details_value
.into_iter()
.map(|data| {
data.peek()
.to_owned()
.parse_value("OrderDetailsWithAmount")
.attach_printable("unable to parse OrderDetailsWithAmount")
})
.collect::<Result<Vec<_>, _>>()
.unwrap_or_default()
});
let frm_connector_details = ConnectorDetailsCore {
connector_name: frm_routing_algorithm.data,
profile_id,
};
let payment_to_frm_data = PaymentToFrmData {
amount: payment_data.get_amount(),
payment_intent: payment_data.get_payment_intent().to_owned(),
payment_attempt: payment_data.get_payment_attempt().to_owned(),
merchant_account: platform.get_processor().get_account().to_owned(),
address: payment_data.get_address().clone(),
connector_details: frm_connector_details.clone(),
order_details,
frm_metadata: payment_data.get_payment_intent().frm_metadata.clone(),
};
let fraud_check_operation: operation::BoxedFraudCheckOperation<F, D> =
fraud_check_operation_by_frm_preferred_flow_type(frm_configs.frm_preferred_flow_type);
let frm_data = fraud_check_operation
.to_get_tracker()?
.get_trackers(state, payment_to_frm_data, frm_connector_details)
.await?;
Ok(FrmInfo {
fraud_check_operation,
frm_data,
suggested_action: None,
})
}
fn fraud_check_operation_by_frm_preferred_flow_type<F, D>(
frm_preferred_flow_type: api_enums::FrmPreferredFlowTypes,
) -> operation::BoxedFraudCheckOperation<F, D>
where
operation::FraudCheckPost: operation::FraudCheckOperation<F, D>,
operation::FraudCheckPre: operation::FraudCheckOperation<F, D>,
{
match frm_preferred_flow_type {
api_enums::FrmPreferredFlowTypes::Pre => Box::new(operation::FraudCheckPre),
api_enums::FrmPreferredFlowTypes::Post => Box::new(operation::FraudCheckPost),
}
}
#[allow(clippy::too_many_arguments)]
pub async fn pre_payment_frm_core<F, Req, D>(
state: &SessionState,
platform: &domain::Platform,
payment_data: &mut D,
frm_info: &mut FrmInfo<F, D>,
frm_configs: FrmConfigsObject,
customer: &Option<domain::Customer>,
should_continue_transaction: &mut bool,
should_continue_capture: &mut bool,
operation: &BoxedOperation<'_, F, Req, D>,
) -> RouterResult<Option<FrmData>>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
let mut frm_data = None;
if is_operation_allowed(operation) {
frm_data = if let Some(frm_data) = &mut frm_info.frm_data {
if matches!(
frm_configs.frm_preferred_flow_type,
api_enums::FrmPreferredFlowTypes::Pre
) {
let fraud_check_operation = &mut frm_info.fraud_check_operation;
let frm_router_data = fraud_check_operation
.to_domain()?
.pre_payment_frm(state, payment_data, frm_data, platform, customer)
.await?;
let _router_data = call_frm_service::<F, frm_api::Transaction, _, D>(
state,
payment_data,
frm_data,
platform,
customer,
)
.await?;
let frm_data_updated = fraud_check_operation
.to_update_tracker()?
.update_tracker(
state,
platform.get_processor().get_key_store(),
frm_data.clone(),
payment_data,
None,
frm_router_data,
)
.await?;
let frm_fraud_check = frm_data_updated.fraud_check.clone();
payment_data.set_frm_message(frm_fraud_check.clone());
if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) {
*should_continue_transaction = false;
frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction);
}
logger::debug!(
"frm_updated_data: {:?} {:?}",
frm_info.fraud_check_operation,
frm_info.suggested_action
);
Some(frm_data_updated)
} else if matches!(
frm_configs.frm_preferred_flow_type,
api_enums::FrmPreferredFlowTypes::Post
) && !matches!(
frm_data.fraud_check.frm_status,
FraudCheckStatus::TransactionFailure // Incase of TransactionFailure frm status(No frm decision is taken by frm processor), if capture method is automatic we should not change it to manual.
) {
*should_continue_capture = false;
Some(frm_data.to_owned())
} else {
Some(frm_data.to_owned())
}
} else {
None
};
}
Ok(frm_data)
}
#[allow(clippy::too_many_arguments)]
pub async fn post_payment_frm_core<F, D>(
state: &SessionState,
req_state: ReqState,
platform: &domain::Platform,
payment_data: &mut D,
frm_info: &mut FrmInfo<F, D>,
frm_configs: FrmConfigsObject,
customer: &Option<domain::Customer>,
should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
if let Some(frm_data) = &mut frm_info.frm_data {
// Allow the Post flow only if the payment is authorized,
// this logic has to be removed if we are going to call /sale or /transaction after failed transaction
let fraud_check_operation = &mut frm_info.fraud_check_operation;
if payment_data.get_payment_attempt().status == AttemptStatus::Authorized {
let frm_router_data_opt = fraud_check_operation
.to_domain()?
.post_payment_frm(
state,
req_state.clone(),
payment_data,
frm_data,
platform,
customer,
)
.await?;
if let Some(frm_router_data) = frm_router_data_opt {
let mut frm_data = fraud_check_operation
.to_update_tracker()?
.update_tracker(
state,
platform.get_processor().get_key_store(),
frm_data.to_owned(),
payment_data,
None,
frm_router_data.to_owned(),
)
.await?;
let frm_fraud_check = frm_data.fraud_check.clone();
let mut frm_suggestion = None;
payment_data.set_frm_message(frm_fraud_check.clone());
if matches!(frm_fraud_check.frm_status, FraudCheckStatus::Fraud) {
frm_info.suggested_action = Some(FrmSuggestion::FrmCancelTransaction);
} else if matches!(frm_fraud_check.frm_status, FraudCheckStatus::ManualReview) {
frm_info.suggested_action = Some(FrmSuggestion::FrmManualReview);
}
fraud_check_operation
.to_domain()?
.execute_post_tasks(
state,
req_state,
&mut frm_data,
platform,
frm_configs,
&mut frm_suggestion,
payment_data,
customer,
should_continue_capture,
)
.await?;
logger::debug!("frm_post_tasks_data: {:?}", frm_data);
let updated_frm_data = fraud_check_operation
.to_update_tracker()?
.update_tracker(
state,
platform.get_processor().get_key_store(),
frm_data.to_owned(),
payment_data,
frm_suggestion,
frm_router_data.to_owned(),
)
.await?;
return Ok(Some(updated_frm_data));
}
}
Ok(Some(frm_data.to_owned()))
} else {
Ok(None)
}
}
#[allow(clippy::too_many_arguments)]
pub async fn call_frm_before_connector_call<F, Req, D>(
operation: &BoxedOperation<'_, F, Req, D>,
platform: &domain::Platform,
payment_data: &mut D,
state: &SessionState,
frm_info: &mut Option<FrmInfo<F, D>>,
customer: &Option<domain::Customer>,
should_continue_transaction: &mut bool,
should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmConfigsObject>>
where
F: Send + Clone,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
let (is_frm_enabled, frm_routing_algorithm, frm_connector_label, frm_configs) =
should_call_frm(platform, payment_data, state).await?;
if let Some((frm_routing_algorithm_val, profile_id)) =
frm_routing_algorithm.zip(frm_connector_label)
{
if let Some(frm_configs) = frm_configs.clone() {
let mut updated_frm_info = Box::pin(make_frm_data_and_fraud_check_operation(
&*state.store,
state,
platform,
payment_data.to_owned(),
frm_routing_algorithm_val,
profile_id,
frm_configs.clone(),
customer,
))
.await?;
if is_frm_enabled {
pre_payment_frm_core(
state,
platform,
payment_data,
&mut updated_frm_info,
frm_configs,
customer,
should_continue_transaction,
should_continue_capture,
operation,
)
.await?;
}
*frm_info = Some(updated_frm_info);
}
}
let fraud_capture_method = frm_info.as_ref().and_then(|frm_info| {
frm_info
.frm_data
.as_ref()
.map(|frm_data| frm_data.fraud_check.payment_capture_method)
});
if matches!(fraud_capture_method, Some(Some(CaptureMethod::Manual)))
&& matches!(
payment_data.get_payment_attempt().status,
AttemptStatus::Unresolved
)
{
if let Some(info) = frm_info {
info.suggested_action = Some(FrmSuggestion::FrmAuthorizeTransaction)
};
*should_continue_transaction = false;
logger::debug!(
"skipping connector call since payment_capture_method is already {:?}",
fraud_capture_method
);
};
logger::debug!("frm_configs: {:?} {:?}", frm_configs, is_frm_enabled);
Ok(frm_configs)
}
pub fn is_operation_allowed<Op: Debug>(operation: &Op) -> bool {
![
"PaymentSession",
"PaymentApprove",
"PaymentReject",
"PaymentCapture",
"PaymentsCancel",
]
.contains(&format!("{operation:?}").as_str())
}
#[cfg(feature = "v1")]
impl From<PaymentToFrmData> for PaymentDetails {
fn from(payment_data: PaymentToFrmData) -> Self {
Self {
amount: common_utils::types::MinorUnit::from(payment_data.amount).get_amount_as_i64(),
currency: payment_data.payment_attempt.currency,
payment_method: payment_data.payment_attempt.payment_method,
payment_method_type: payment_data.payment_attempt.payment_method_type,
refund_transaction_id: None,
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn frm_fulfillment_core(
state: SessionState,
platform: domain::Platform,
req: frm_core_types::FrmFulfillmentRequest,
) -> RouterResponse<frm_types::FraudCheckResponseData> {
let db = &*state.clone().store;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&req.payment_id.clone(),
platform.get_processor().get_account().get_id(),
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
match payment_intent.status {
IntentStatus::Succeeded => {
let invalid_request_error = errors::ApiErrorResponse::InvalidRequestData {
message: "no fraud check entry found for this payment_id".to_string(),
};
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
req.payment_id.clone(),
platform.get_processor().get_account().get_id().clone(),
)
.await
.change_context(invalid_request_error.to_owned())?;
match existing_fraud_check {
Some(fraud_check) => {
if (matches!(fraud_check.frm_transaction_type, FraudCheckType::PreFrm)
&& fraud_check.last_step == FraudCheckLastStep::TransactionOrRecordRefund)
|| (matches!(fraud_check.frm_transaction_type, FraudCheckType::PostFrm)
&& fraud_check.last_step == FraudCheckLastStep::CheckoutOrSale)
{
Box::pin(make_fulfillment_api_call(
db,
fraud_check,
payment_intent,
state,
platform,
req,
))
.await
} else {
Err(errors::ApiErrorResponse::PreconditionFailed {message:"Frm pre/post flow hasn't terminated yet, so fulfillment cannot be called".to_string(),}.into())
}
}
None => Err(invalid_request_error.into()),
}
}
_ => Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Fulfillment can be performed only for succeeded payment".to_string(),
}
.into()),
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn make_fulfillment_api_call(
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/revenue_recovery_data_backfill.rs | crates/router/src/core/revenue_recovery_data_backfill.rs | use std::collections::HashMap;
use api_models::revenue_recovery_data_backfill::{
BackfillError, ComprehensiveCardData, GetRedisDataQuery, RedisDataResponse, RedisKeyType,
RevenueRecoveryBackfillRequest, RevenueRecoveryDataBackfillResponse, ScheduledAtUpdate,
UnlockStatusResponse, UpdateTokenStatusRequest, UpdateTokenStatusResponse,
};
use common_enums::{CardNetwork, PaymentMethodType};
use common_utils::id_type;
use error_stack::ResultExt;
use hyperswitch_domain_models::api::ApplicationResponse;
use masking::ExposeInterface;
use router_env::{instrument, logger};
use time::{macros::format_description, Date};
use crate::{
connection,
core::errors::{self, RouterResult},
routes::SessionState,
types::{domain, storage},
};
pub async fn revenue_recovery_data_backfill(
state: SessionState,
records: Vec<RevenueRecoveryBackfillRequest>,
cutoff_datetime: Option<time::PrimitiveDateTime>,
) -> RouterResult<ApplicationResponse<RevenueRecoveryDataBackfillResponse>> {
let mut processed_records = 0;
let mut failed_records = 0;
// Process each record
for record in records {
match process_payment_method_record(&state, &record, cutoff_datetime).await {
Ok(_) => {
processed_records += 1;
logger::info!(
"Successfully processed record with connector customer id: {}",
record.customer_id_resp
);
}
Err(e) => {
failed_records += 1;
logger::error!(
"Payment method backfill failed: customer_id={}, error={}",
record.customer_id_resp,
e
);
}
}
}
let response = RevenueRecoveryDataBackfillResponse {
processed_records,
failed_records,
};
logger::info!(
"Revenue recovery data backfill completed - Processed: {}, Failed: {}",
processed_records,
failed_records
);
Ok(ApplicationResponse::Json(response))
}
pub async fn unlock_connector_customer_status_handler(
state: SessionState,
connector_customer_id: String,
payment_id: id_type::GlobalPaymentId,
) -> RouterResult<ApplicationResponse<UnlockStatusResponse>> {
let unlocked = storage::revenue_recovery_redis_operation::
RedisTokenManager::unlock_connector_customer_status(&state, &connector_customer_id, &payment_id)
.await
.map_err(|e| {
logger::error!(
"Failed to unlock connector customer status for {}: {:?}",
connector_customer_id,
e
);
match e.current_context() {
errors::StorageError::RedisError(redis_error) => {
match redis_error.current_context() {
storage_impl::errors::RedisError::DeleteFailed => {
// This indicates the payment_id doesn't own the lock
errors::ApiErrorResponse::InvalidPaymentIdProvided {
resource: format!("The Status token for connector costumer id:- {} is locked by different PaymentIntent ID", connector_customer_id)
}
}
_ => {
// Other Redis errors - infrastructure issue
errors::ApiErrorResponse::InternalServerError
}
}
}
errors::StorageError::ValueNotFound(_) => {
// Lock doesn't exist
errors::ApiErrorResponse::GenericNotFoundError {
message: format!("Lock not found for connector customer id: {}", connector_customer_id)
}
}
_ => {
// Fallback for other storage errors
errors::ApiErrorResponse::InternalServerError
}
}
})?;
let response = UnlockStatusResponse { unlocked };
logger::info!(
"Unlock operation completed for connector customer {}: {}",
connector_customer_id,
unlocked
);
Ok(ApplicationResponse::Json(response))
}
pub async fn get_redis_data(
state: SessionState,
connector_customer_id: &str,
key_type: &RedisKeyType,
) -> RouterResult<ApplicationResponse<RedisDataResponse>> {
match storage::revenue_recovery_redis_operation::RedisTokenManager::get_redis_key_data_raw(
&state,
connector_customer_id,
key_type,
)
.await
{
Ok((exists, ttl_seconds, data)) => {
let response = RedisDataResponse {
exists,
ttl_seconds,
data,
};
logger::info!(
"Retrieved Redis data for connector customer {}, exists={}, ttl={}",
connector_customer_id,
exists,
ttl_seconds
);
Ok(ApplicationResponse::Json(response))
}
Err(error) => Err(
error.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: format!(
"Redis data not found for connector customer id:- '{}'",
connector_customer_id
),
}),
),
}
}
pub async fn redis_update_additional_details_for_revenue_recovery(
state: SessionState,
request: UpdateTokenStatusRequest,
) -> RouterResult<ApplicationResponse<UpdateTokenStatusResponse>> {
// Get existing token
let existing_token = storage::revenue_recovery_redis_operation::
RedisTokenManager::get_payment_processor_token_using_token_id(
&state,
&request.connector_customer_id,
&request.payment_processor_token.clone().expose(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve existing token data")?;
// Check if token exists
let mut token_status = existing_token.ok_or_else(|| {
error_stack::Report::new(errors::ApiErrorResponse::GenericNotFoundError {
message: format!(
"Token '{:?}' not found for connector customer id:- '{}'",
request.payment_processor_token, request.connector_customer_id
),
})
})?;
let mut updated_fields = Vec::new();
// Handle scheduled_at update
match request.scheduled_at {
Some(ScheduledAtUpdate::SetToDateTime(dt)) => {
// Field provided with datetime - update schedule_at field with datetime
token_status.scheduled_at = Some(dt);
updated_fields.push(format!("scheduled_at: {}", dt));
logger::info!(
"Set scheduled_at to '{}' for token '{:?}'",
dt,
request.payment_processor_token
);
}
Some(ScheduledAtUpdate::SetToNull) => {
// Field provided with "null" variable - set schedule_at field to null
token_status.scheduled_at = None;
updated_fields.push("scheduled_at: set to null".to_string());
logger::info!(
"Set scheduled_at to null for token '{:?}'",
request.payment_processor_token
);
}
None => {
// Field not provided - we don't update schedule_at field
logger::debug!("scheduled_at not provided in request - leaving unchanged");
}
}
// Update is_hard_decline field
request.is_hard_decline.map(|is_hard_decline| {
token_status.is_hard_decline = Some(is_hard_decline);
updated_fields.push(format!("is_hard_decline: {}", is_hard_decline));
});
// Update error_code field
request.error_code.as_ref().map(|error_code| {
token_status.error_code = Some(error_code.clone());
updated_fields.push(format!("error_code: {}", error_code));
});
// Update Redis with modified token
let mut tokens_map = HashMap::new();
tokens_map.insert(
request.payment_processor_token.clone().expose(),
token_status,
);
storage::revenue_recovery_redis_operation::
RedisTokenManager::update_or_add_connector_customer_payment_processor_tokens(
&state,
&request.connector_customer_id,
tokens_map,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update token status in Redis")?;
let updated_fields_str = if updated_fields.is_empty() {
"no fields were updated".to_string()
} else {
updated_fields.join(", ")
};
let response = UpdateTokenStatusResponse {
updated: true,
message: format!(
"Successfully updated token '{:?}' for connector customer '{}'. Updated fields: {}",
request.payment_processor_token, request.connector_customer_id, updated_fields_str
),
};
logger::info!(
"Updated token status for connector customer {}, token: {:?}",
request.connector_customer_id,
request.payment_processor_token
);
Ok(ApplicationResponse::Json(response))
}
async fn process_payment_method_record(
state: &SessionState,
record: &RevenueRecoveryBackfillRequest,
cutoff_datetime: Option<time::PrimitiveDateTime>,
) -> Result<(), BackfillError> {
// Build comprehensive card data from CSV record
let card_data = match build_comprehensive_card_data(record) {
Ok(data) => data,
Err(e) => {
logger::warn!(
"Failed to build card data for connector customer id: {}, error: {}.",
record.customer_id_resp,
e
);
ComprehensiveCardData {
card_type: Some("card".to_string()),
card_exp_month: None,
card_exp_year: None,
card_network: None,
card_issuer: None,
card_issuing_country: None,
daily_retry_history: None,
is_active: None,
account_update_history: None,
}
}
};
logger::info!(
"Built comprehensive card data - card_type: {:?}, exp_month: {}, exp_year: {}, network: {:?}, issuer: {:?}, country: {:?}, daily_retry_history: {:?}",
card_data.card_type,
card_data.card_exp_month.as_ref().map(|_| "**").unwrap_or("None"),
card_data.card_exp_year.as_ref().map(|_| "**").unwrap_or("None"),
card_data.card_network,
card_data.card_issuer,
card_data.card_issuing_country,
card_data.daily_retry_history
);
// Update Redis if token exists and is valid
match record.token.as_ref().map(|token| token.clone().expose()) {
Some(token) if !token.is_empty() => {
logger::info!("Updating Redis for customer: {}", record.customer_id_resp,);
storage::revenue_recovery_redis_operation::
RedisTokenManager::update_redis_token_with_comprehensive_card_data(
state,
&record.customer_id_resp,
&token,
&card_data,
cutoff_datetime,
)
.await
.map_err(|e| {
logger::error!("Redis update failed: {}", e);
BackfillError::RedisError(format!("Token not found in Redis: {}", e))
})?;
}
_ => {
logger::info!(
"Skipping Redis update - token is missing, empty or 'nan': {:?}",
record.token
);
}
}
logger::info!(
"Successfully completed processing for connector customer id: {}",
record.customer_id_resp
);
Ok(())
}
/// Parse daily retry history from CSV
fn parse_daily_retry_history(
json_str: Option<&str>,
) -> Option<HashMap<time::PrimitiveDateTime, i32>> {
match json_str {
Some(json) if !json.is_empty() => {
match serde_json::from_str::<HashMap<String, i32>>(json) {
Ok(string_retry_history) => {
let date_format = format_description!("[year]-[month]-[day]");
let datetime_format = format_description!(
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"
);
let mut hourly_retry_history = HashMap::new();
for (key, count) in string_retry_history {
// Try parsing full datetime first
let parsed_dt = time::PrimitiveDateTime::parse(&key, &datetime_format)
.or_else(|_| {
// Fallback to date only
Date::parse(&key, &date_format).map(|date| {
time::PrimitiveDateTime::new(date, time::Time::MIDNIGHT)
})
});
match parsed_dt {
Ok(dt) => {
hourly_retry_history.insert(dt, count);
}
Err(_) => {
logger::error!("Error: failed to parse retry history key '{}'", key)
}
}
}
logger::debug!(
"Successfully parsed daily_retry_history with {} entries",
hourly_retry_history.len()
);
Some(hourly_retry_history)
}
Err(e) => {
logger::warn!("Failed to parse daily_retry_history JSON '{}': {}", json, e);
None
}
}
}
_ => {
logger::debug!("Daily retry history not present or invalid, preserving existing data");
None
}
}
}
/// Build comprehensive card data from CSV record
fn build_comprehensive_card_data(
record: &RevenueRecoveryBackfillRequest,
) -> Result<ComprehensiveCardData, BackfillError> {
// Extract card type from request, if not present then update it with 'card'
let card_type = determine_card_type(record.payment_method_sub_type);
// Parse expiration date
let (exp_month, exp_year) = parse_expiration_date(
record
.exp_date
.as_ref()
.map(|date| date.clone().expose())
.as_deref(),
)?;
let card_exp_month = exp_month.map(masking::Secret::new);
let card_exp_year = exp_year.map(masking::Secret::new);
// Extract card network
let card_network = record.card_network.clone();
// Extract card issuer and issuing country
let card_issuer = record
.clean_bank_name
.as_ref()
.filter(|value| !value.is_empty())
.cloned();
let card_issuing_country = record
.country_name
.as_ref()
.filter(|value| !value.is_empty())
.cloned();
// Parse daily retry history
let daily_retry_history = parse_daily_retry_history(record.daily_retry_history.as_deref());
Ok(ComprehensiveCardData {
card_type,
card_exp_month,
card_exp_year,
card_network,
card_issuer,
card_issuing_country,
daily_retry_history,
is_active: record.is_active,
account_update_history: record.account_update_history.clone(),
})
}
/// Determine card type with fallback logic: payment_method_sub_type if not present -> "Card"
fn determine_card_type(payment_method_sub_type: Option<PaymentMethodType>) -> Option<String> {
match payment_method_sub_type {
Some(card_type_enum) => {
let mapped_type = match card_type_enum {
PaymentMethodType::Credit => "credit".to_string(),
PaymentMethodType::Debit => "debit".to_string(),
PaymentMethodType::Card => "card".to_string(),
// For all other payment method types, default to "card"
_ => "card".to_string(),
};
logger::debug!(
"Using payment_method_sub_type enum '{:?}' -> '{}'",
card_type_enum,
mapped_type
);
Some(mapped_type)
}
None => {
logger::info!("In CSV payment_method_sub_type not present...");
None
}
}
}
/// Parse expiration date
fn parse_expiration_date(
exp_date: Option<&str>,
) -> Result<(Option<String>, Option<String>), BackfillError> {
exp_date
.filter(|date| !date.is_empty())
.map(|date| {
date.split_once('/')
.ok_or_else(|| {
logger::warn!("Unrecognized expiration date format (MM/YY expected)");
BackfillError::CsvParsingError(
"Invalid expiration date format: expected MM/YY".to_string(),
)
})
.and_then(|(month_part, year_part)| {
let month = month_part.trim();
let year = year_part.trim();
logger::debug!("Split expiration date - parsing month and year");
// Validate and parse month
let month_num = month.parse::<u8>().map_err(|_| {
logger::warn!("Failed to parse month component in expiration date");
BackfillError::CsvParsingError(
"Invalid month format in expiration date".to_string(),
)
})?;
if !(1..=12).contains(&month_num) {
logger::warn!("Invalid month value in expiration date (not in range 1-12)");
return Err(BackfillError::CsvParsingError(
"Invalid month value in expiration date".to_string(),
));
}
// Handle year conversion
let final_year = match year.len() {
4 => &year[2..4], // Convert 4-digit to 2-digit
2 => year, // Already 2-digit
_ => {
logger::warn!(
"Invalid year length in expiration date (expected 2 or 4 digits)"
);
return Err(BackfillError::CsvParsingError(
"Invalid year format in expiration date".to_string(),
));
}
};
logger::debug!("Successfully parsed expiration date... ",);
Ok((Some(month.to_string()), Some(final_year.to_string())))
})
})
.unwrap_or_else(|| {
logger::debug!("Empty expiration date, returning None");
Ok((None, None))
})
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/refunds.rs | crates/router/src/core/refunds.rs | #[cfg(feature = "olap")]
use std::collections::HashMap;
#[cfg(feature = "olap")]
use api_models::admin::MerchantConnectorInfo;
use common_enums::ExecutionMode;
use common_utils::{
ext_traits::{AsyncExt, StringExt},
types::{ConnectorTransactionId, MinorUnit},
};
use diesel_models::{process_tracker::business_status, refund as diesel_refund};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::ErrorResponse, router_request_types::SplitRefundsRequest,
};
use hyperswitch_interfaces::integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject};
use router_env::{instrument, tracing, tracing::Instrument};
use scheduler::{
consumer::types::process_data, errors as sch_errors, utils as process_tracker_utils,
};
#[cfg(feature = "olap")]
use strum::IntoEnumIterator;
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt},
payments::{
self, access_token, gateway::context as gateway_context, helpers,
helpers::MerchantConnectorAccountType,
},
refunds::transformers::SplitRefundInput,
unified_connector_service,
utils::{
self as core_utils, refunds_transformers as transformers,
refunds_validator as validator,
},
},
db, logger,
routes::{metrics, SessionState},
services,
types::{
self,
api::{self, refunds},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto},
},
utils::{self, OptionExt},
};
// ********************************************** REFUND EXECUTE **********************************************
#[instrument(skip_all)]
pub async fn refund_create_core(
state: SessionState,
platform: domain::Platform,
_profile_id: Option<common_utils::id_type::ProfileId>,
req: refunds::RefundRequest,
) -> RouterResponse<refunds::RefundResponse> {
let db = &*state.store;
let (merchant_id, payment_intent, payment_attempt, amount);
merchant_id = platform.get_processor().get_account().get_id();
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&req.payment_id,
merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
utils::when(
!(payment_intent.status == enums::IntentStatus::Succeeded
|| payment_intent.status == enums::IntentStatus::PartiallyCaptured),
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: "refund".into(),
field_name: "status".into(),
current_value: payment_intent.status.to_string(),
states: "succeeded, partially_captured".to_string(),
})
.attach_printable("unable to refund for a unsuccessful payment intent"))
},
)?;
// Amount is not passed in request refer from payment intent.
amount = req
.amount
.or(payment_intent.amount_captured)
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("amount captured is none in a successful payment")?;
//[#299]: Can we change the flow based on some workflow idea
utils::when(amount <= MinorUnit::new(0), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount".to_string(),
expected_format: "positive integer".to_string(),
})
.attach_printable("amount less than or equal to zero"))
})?;
payment_attempt = db
.find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&req.payment_id,
merchant_id,
platform.get_processor().get_account().storage_scheme,
platform.get_processor().get_key_store()
).await
.to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?;
let creds_identifier = req
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
req.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(db, platform.get_processor(), mcd)
.await
})
.await
.transpose()?;
Box::pin(validate_and_create_refund(
&state,
&platform,
&payment_attempt,
&payment_intent,
amount,
req,
creds_identifier,
))
.await
.map(services::ApplicationResponse::Json)
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
platform: &domain::Platform,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
all_keys_required: Option<bool>,
) -> RouterResult<(diesel_refund::Refund, Option<masking::Secret<String>>)> {
let routed_through = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve connector from payment attempt")?;
let storage_scheme = platform.get_processor().get_account().storage_scheme;
metrics::REFUND_COUNT.add(
1,
router_env::metric_attributes!(("connector", routed_through.clone())),
);
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&routed_through,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)?;
let currency = payment_attempt.currency.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Transaction in invalid. Missing field \"currency\" in payment_attempt.",
)
})?;
validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
// Fetch merchant connector account
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,
platform.get_processor().get_account().get_id(),
creds_identifier.as_deref(),
platform.get_processor().get_key_store(),
profile_id,
&routed_through,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let mut router_data = core_utils::construct_refund_router_data(
state,
&routed_through,
platform,
(payment_attempt.get_total_amount(), currency),
payment_intent,
payment_attempt,
refund,
split_refunds,
&merchant_connector_account,
)
.await?;
let gateway_context = gateway_context::RouterGatewayContext::direct(
platform.clone(),
merchant_connector_account.clone(),
payment_intent.merchant_id.clone(),
profile_id.clone(),
creds_identifier.clone(),
);
// Add access token for both UCS and direct connector paths
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
&router_data,
creds_identifier.as_deref(),
&gateway_context,
))
.await?;
logger::debug!(refund_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
// Common access token handling for all flows
let router_data_res = if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
// Access token available or not needed - proceed with execution
// Check which gateway system to use for refunds
let (execution_path, updated_state) =
unified_connector_service::should_call_unified_connector_service(
state,
platform,
&router_data,
None, // No previous gateway information required for refunds
payments::CallConnectorAction::Trigger,
None,
)
.await?;
router_env::logger::info!(
refund_id = refund.refund_id,
execution_path = ?execution_path,
"Executing refund via {execution_path:?}"
);
// Execute refund based on gateway system decision
match execution_path {
common_enums::ExecutionPath::UnifiedConnectorService => {
unified_connector_service::call_unified_connector_service_for_refund_execute(
state,
platform,
router_data.clone(),
ExecutionMode::Primary,
merchant_connector_account,
)
.await
.attach_printable(format!(
"UCS refund execution failed for connector: {}, refund_id: {}",
connector.connector_name, router_data.request.refund_id
))?
}
common_enums::ExecutionPath::Direct => {
Box::pin(execute_refund_execute_via_direct(
state,
&connector,
platform,
refund,
router_data,
all_keys_required,
))
.await?
}
common_enums::ExecutionPath::ShadowUnifiedConnectorService => {
Box::pin(execute_refund_execute_via_direct_with_ucs_shadow(
&updated_state,
&connector,
platform,
refund,
router_data,
merchant_connector_account.clone(),
all_keys_required,
))
.await?
}
}
} else {
// Access token needed but not available - return error router_data
router_data
};
let refund_update = match router_data_res.response {
Err(err) => {
let option_gsm = helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::REFUND_FLOW_STR,
consts::DEFAULT_SUBFLOW_STR,
)
.await;
// Note: Some connectors do not have a separate list of refund errors
// In such cases, the error codes and messages are stored under "Authorize" flow in GSM table
// So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow"
let option_gsm = if option_gsm.is_none() {
helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::PAYMENT_FLOW_STR,
consts::AUTHORIZE_FLOW_STR,
)
.await
} else {
option_gsm
};
let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());
let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message);
let (unified_code, unified_message) = if let Some((code, message)) =
gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref())
{
(code.to_owned(), message.to_owned())
} else {
(
consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(),
consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(),
)
};
diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: err.reason.or(Some(err.message)),
refund_error_code: Some(err.code),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: Some(unified_code),
unified_message: Some(unified_message),
issuer_error_code: err.network_decline_code,
issuer_error_message: err.network_error_message,
}
}
Ok(response) => {
// match on connector integrity checks
match router_data_res.integrity_check.clone() {
Err(err) => {
let (refund_connector_transaction_id, processor_refund_data) =
err.connector_transaction_id.map_or((None, None), |txn_id| {
let (refund_id, refund_data) =
ConnectorTransactionId::form_id_and_data(txn_id);
(Some(refund_id), refund_data)
});
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
(
"merchant_id",
platform.get_processor().get_account().get_id().clone()
)
),
);
diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::ManualReview),
refund_error_message: Some(format!(
"Integrity Check Failed! as data mismatched for fields {}",
err.field_names
)),
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: refund_connector_transaction_id,
processor_refund_data,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
}
}
Ok(()) => {
if response.refund_status == diesel_models::enums::RefundStatus::Success {
metrics::SUCCESSFUL_REFUND.add(
1,
router_env::metric_attributes!((
"connector",
connector.connector_name.to_string(),
)),
);
}
let (connector_refund_id, processor_refund_data) =
ConnectorTransactionId::form_id_and_data(response.connector_refund_id);
diesel_refund::RefundUpdate::Update {
connector_refund_id,
refund_status: response.refund_status,
sent_to_gateway: true,
refund_error_message: None,
refund_arn: "".to_string(),
updated_by: storage_scheme.to_string(),
processor_refund_data,
}
}
}
}
};
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.refund_id
)
})?;
utils::trigger_refund_outgoing_webhook(
state,
platform,
&response,
payment_attempt.profile_id.clone(),
)
.await
.map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))
.ok();
Ok((response, router_data_res.raw_connector_response))
}
// ============================================================================
// REFUND EXECUTION FUNCTIONS
// ============================================================================
/// Execute refund via Direct connector
async fn execute_refund_execute_via_direct(
state: &SessionState,
connector: &api::ConnectorData,
platform: &domain::Platform,
refund: &diesel_refund::Refund,
router_data: types::RefundExecuteRouterData,
all_keys_required: Option<bool>,
) -> RouterResult<types::RefundExecuteRouterData> {
let storage_scheme = platform.get_processor().get_account().storage_scheme;
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::Execute,
types::RefundsData,
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
let router_data_res = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
all_keys_required,
)
.await;
// Handle specific connector errors and update refund status if needed
let option_refund_error_update =
router_data_res
.as_ref()
.err()
.and_then(|error| match error.current_context() {
errors::ConnectorError::NotImplemented(message) => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(
errors::ConnectorError::NotImplemented(message.to_owned()).to_string(),
),
refund_error_code: Some("NOT_IMPLEMENTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
})
}
errors::ConnectorError::FlowNotSupported { flow, connector } => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(format!(
"{flow} is not supported by {connector}"
)),
refund_error_code: Some("NOT_SUPPORTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
})
}
errors::ConnectorError::NotSupported { message, connector } => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(format!(
"{message} is not supported by {connector}"
)),
refund_error_code: Some("NOT_SUPPORTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
})
}
_ => None,
});
// Update the refund status as failure if connector_error is NotImplemented or NotSupported
if let Some(refund_error_update) = option_refund_error_update {
state
.store
.update_refund(refund.to_owned(), refund_error_update, storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.refund_id
)
})?;
}
let mut refund_router_data_res = router_data_res.to_refund_failed_response()?;
// Perform integrity check
let integrity_result = check_refund_integrity(
&refund_router_data_res.request,
&refund_router_data_res.response,
);
refund_router_data_res.integrity_check = integrity_result;
Ok(refund_router_data_res)
}
/// Execute refund via Direct connector with UCS shadow comparison
async fn execute_refund_execute_via_direct_with_ucs_shadow(
state: &SessionState,
connector: &api::ConnectorData,
platform: &domain::Platform,
refund: &diesel_refund::Refund,
router_data: types::RefundExecuteRouterData,
merchant_connector_account: MerchantConnectorAccountType,
all_keys_required: Option<bool>,
) -> RouterResult<types::RefundExecuteRouterData> {
// Execute Direct connector (PRIMARY)
let direct_result = Box::pin(execute_refund_execute_via_direct(
state,
connector,
platform,
refund,
router_data.clone(),
all_keys_required,
))
.await;
// Execute UCS in parallel (SHADOW - for comparison only)
let ucs_router_data = router_data.clone();
let ucs_platform = platform.clone();
let ucs_state = state.clone();
// Clone direct result for comparison (if successful)
let direct_router_data_for_comparison = direct_result.as_ref().ok().cloned();
tokio::spawn(
(
async move {
let ucs_result =
unified_connector_service::call_unified_connector_service_for_refund_execute(
&ucs_state,
&ucs_platform,
ucs_router_data,
ExecutionMode::Shadow,
merchant_connector_account
).await;
match (ucs_result, direct_router_data_for_comparison) {
(Ok(ucs_router_data), Some(direct_router_data)) => {
Box::pin(
unified_connector_service::serialize_router_data_and_send_to_comparison_service(
&ucs_state,
direct_router_data,
ucs_router_data
)
).await
.inspect_err(|e| {
router_env::logger::debug!(
"Shadow UCS refund execute comparison failed: {:?}",
e
);
})
.ok();
}
(Err(e), _) => {
router_env::logger::debug!(
"Skipping refund execute comparison - UCS shadow execute failed: {:?}",
e
);
}
(_, None) => {
router_env::logger::debug!(
"Skipping refund execute comparison - direct execute failed"
);
}
}
}
).instrument(tracing::Span::current())
);
// Return PRIMARY result (Direct connector response)
direct_result
}
pub fn check_refund_integrity<T, Request>(
request: &Request,
refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>,
) -> Result<(), common_utils::errors::IntegrityCheckError>
where
T: FlowIntegrity,
Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>,
{
let connector_refund_id = refund_response_data
.as_ref()
.map(|resp_data| resp_data.connector_refund_id.clone())
.ok();
request.check_integrity(request, connector_refund_id.to_owned())
}
// ********************************************** REFUND SYNC **********************************************
pub async fn refund_response_wrapper<F, Fut, T, Req>(
state: SessionState,
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
request: Req,
f: F,
) -> RouterResponse<refunds::RefundResponse>
where
F: Fn(SessionState, domain::Platform, Option<common_utils::id_type::ProfileId>, Req) -> Fut,
Fut: futures::Future<Output = RouterResult<T>>,
T: ForeignInto<refunds::RefundResponse>,
{
Ok(services::ApplicationResponse::Json(
f(state, platform, profile_id, request)
.await?
.foreign_into(),
))
}
#[instrument(skip_all)]
pub async fn refund_retrieve_core(
state: SessionState,
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
request: refunds::RefundsRetrieveRequest,
refund: diesel_refund::Refund,
) -> RouterResult<(diesel_refund::Refund, Option<masking::Secret<String>>)> {
let db = &*state.store;
let merchant_id = platform.get_processor().get_account().get_id();
core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?;
let payment_id = &refund.payment_id;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
payment_id,
merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&refund.connector_transaction_id,
payment_id,
merchant_id,
platform.get_processor().get_account().storage_scheme,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
request
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(db, platform.get_processor(), mcd)
.await
})
.await
.transpose()?;
let split_refunds_req = core_utils::get_split_refunds(SplitRefundInput {
split_payment_request: payment_intent.split_payments.clone(),
payment_charges: payment_attempt.charges.clone(),
charge_id: payment_attempt.charge_id.clone(),
refund_request: refund.split_refunds.clone(),
})?;
let unified_translated_message = if let (Some(unified_code), Some(unified_message)) =
(refund.unified_code.clone(), refund.unified_message.clone())
{
helpers::get_unified_translation(
&state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message))
} else {
refund.unified_message
};
let refund = diesel_refund::Refund {
unified_message: unified_translated_message,
..refund
};
let (response, raw_connector_response) = (if should_call_refund(
&refund,
request.force_sync.unwrap_or(false),
request.all_keys_required.unwrap_or(false),
) {
Box::pin(sync_refund_with_gateway(
&state,
&platform,
&payment_attempt,
&payment_intent,
&refund,
creds_identifier,
split_refunds_req,
request.all_keys_required,
))
.await
} else {
Ok((refund, None))
})?;
Ok((response, raw_connector_response))
}
fn should_call_refund(
refund: &diesel_models::refund::Refund,
force_sync: bool,
all_keys_required: bool,
) -> bool {
// This implies, we cannot perform a refund sync & `the connector_refund_id`
// doesn't exist
let predicate1 = refund.connector_refund_id.is_some();
// This allows refund sync at connector level if all_keys_required or force_sync is enabled, or
// checks if the refund has failed
let predicate2 = all_keys_required
|| force_sync
|| !matches!(
refund.refund_status,
diesel_models::enums::RefundStatus::Failure
| diesel_models::enums::RefundStatus::Success
);
predicate1 && predicate2
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn sync_refund_with_gateway(
state: &SessionState,
platform: &domain::Platform,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &diesel_refund::Refund,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
all_keys_required: Option<bool>,
) -> RouterResult<(diesel_refund::Refund, Option<masking::Secret<String>>)> {
let connector_id = refund.connector.to_string();
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_id,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector")?;
let storage_scheme = platform.get_processor().get_account().storage_scheme;
let currency = payment_attempt.currency.get_required_value("currency")?;
// Fetch merchant connector account
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,
platform.get_processor().get_account().get_id(),
creds_identifier.as_deref(),
platform.get_processor().get_key_store(),
profile_id,
&connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let mut router_data = core_utils::construct_refund_router_data::<api::RSync>(
state,
&connector_id,
platform,
(payment_attempt.get_total_amount(), currency),
payment_intent,
payment_attempt,
refund,
split_refunds,
&merchant_connector_account,
)
.await?;
let gateway_context = gateway_context::RouterGatewayContext::direct(
platform.clone(),
merchant_connector_account.clone(),
payment_intent.merchant_id.clone(),
profile_id.clone(),
creds_identifier.clone(),
);
// Add access token for both UCS and direct connector paths
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
&router_data,
creds_identifier.as_deref(),
&gateway_context,
))
.await?;
logger::debug!(refund_retrieve_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/surcharge_decision_config.rs | crates/router/src/core/surcharge_decision_config.rs | use api_models::surcharge_decision_configs::{
SurchargeDecisionConfigReq, SurchargeDecisionManagerRecord, SurchargeDecisionManagerResponse,
};
use common_utils::ext_traits::StringExt;
use error_stack::ResultExt;
use crate::{
core::errors::{self, RouterResponse},
routes::SessionState,
services::api as service_api,
types::domain,
};
#[cfg(feature = "v1")]
pub async fn upsert_surcharge_decision_config(
state: SessionState,
platform: domain::Platform,
request: SurchargeDecisionConfigReq,
) -> RouterResponse<SurchargeDecisionManagerRecord> {
use common_utils::ext_traits::{Encode, OptionExt, ValueExt};
use diesel_models::configs;
use storage_impl::redis::cache;
use super::routing::helpers::update_merchant_active_algorithm_ref;
let db = state.store.as_ref();
let name = request.name;
let program = request
.algorithm
.get_required_value("algorithm")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "algorithm",
})
.attach_printable("Program for config not given")?;
let merchant_surcharge_configs = request.merchant_surcharge_configs;
let timestamp = common_utils::date_time::now_unix_timestamp();
let mut algo_id: api_models::routing::RoutingAlgorithmRef = platform
.get_processor()
.get_account()
.routing_algorithm
.clone()
.map(|val| val.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
let key = platform
.get_processor()
.get_account()
.get_id()
.get_payment_method_surcharge_routing_id();
let read_config_key = db.find_config_by_key(&key).await;
euclid::frontend::ast::lowering::lower_program(program.clone())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid Request Data".to_string(),
})
.attach_printable("The Request has an Invalid Comparison")?;
let surcharge_cache_key = platform
.get_processor()
.get_account()
.get_id()
.get_surcharge_dsk_key();
match read_config_key {
Ok(config) => {
let previous_record: SurchargeDecisionManagerRecord = config
.config
.parse_struct("SurchargeDecisionManagerRecord")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The Payment Config Key Not Found")?;
let new_algo = SurchargeDecisionManagerRecord {
name: name.unwrap_or(previous_record.name),
algorithm: program,
modified_at: timestamp,
created_at: previous_record.created_at,
merchant_surcharge_configs,
};
let serialize_updated_str = new_algo
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize config to string")?;
let updated_config = configs::ConfigUpdate::Update {
config: Some(serialize_updated_str),
};
db.update_config_by_key(&key, updated_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error serializing the config")?;
algo_id.update_surcharge_config_id(key.clone());
let config_key = cache::CacheKind::Surcharge(surcharge_cache_key.into());
update_merchant_active_algorithm_ref(
&state,
platform.get_processor().get_key_store(),
config_key,
algo_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
Ok(service_api::ApplicationResponse::Json(new_algo))
}
Err(e) if e.current_context().is_db_not_found() => {
let new_rec = SurchargeDecisionManagerRecord {
name: name
.get_required_value("name")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "name",
})
.attach_printable("name of the config not found")?,
algorithm: program,
merchant_surcharge_configs,
modified_at: timestamp,
created_at: timestamp,
};
let serialized_str = new_rec
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error serializing the config")?;
let new_config = configs::ConfigNew {
key: key.clone(),
config: serialized_str,
};
db.insert_config(new_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching the config")?;
algo_id.update_surcharge_config_id(key.clone());
let config_key = cache::CacheKind::Surcharge(surcharge_cache_key.into());
update_merchant_active_algorithm_ref(
&state,
platform.get_processor().get_key_store(),
config_key,
algo_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
Ok(service_api::ApplicationResponse::Json(new_rec))
}
Err(e) => Err(e)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching payment config"),
}
}
#[cfg(feature = "v2")]
pub async fn upsert_surcharge_decision_config(
_state: SessionState,
_platform: domain::Platform,
_request: SurchargeDecisionConfigReq,
) -> RouterResponse<SurchargeDecisionManagerRecord> {
todo!();
}
#[cfg(feature = "v1")]
pub async fn delete_surcharge_decision_config(
state: SessionState,
platform: domain::Platform,
) -> RouterResponse<()> {
use common_utils::ext_traits::ValueExt;
use storage_impl::redis::cache;
use super::routing::helpers::update_merchant_active_algorithm_ref;
let db = state.store.as_ref();
let key = platform
.get_processor()
.get_account()
.get_id()
.get_payment_method_surcharge_routing_id();
let mut algo_id: api_models::routing::RoutingAlgorithmRef = platform
.get_processor()
.get_account()
.routing_algorithm
.clone()
.map(|value| value.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the surcharge conditional_config algorithm")?
.unwrap_or_default();
algo_id.surcharge_config_algo_id = None;
let surcharge_cache_key = platform
.get_processor()
.get_account()
.get_id()
.get_surcharge_dsk_key();
let config_key = cache::CacheKind::Surcharge(surcharge_cache_key.into());
update_merchant_active_algorithm_ref(
&state,
platform.get_processor().get_key_store(),
config_key,
algo_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update deleted algorithm ref")?;
db.delete_config_by_key(&key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete routing config from DB")?;
Ok(service_api::ApplicationResponse::StatusOk)
}
#[cfg(feature = "v2")]
pub async fn delete_surcharge_decision_config(
_state: SessionState,
_platform: domain::Platform,
) -> RouterResponse<()> {
todo!()
}
pub async fn retrieve_surcharge_decision_config(
state: SessionState,
platform: domain::Platform,
) -> RouterResponse<SurchargeDecisionManagerResponse> {
let db = state.store.as_ref();
let algorithm_id = platform
.get_processor()
.get_account()
.get_id()
.get_payment_method_surcharge_routing_id();
let algo_config = db
.find_config_by_key(&algorithm_id)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("The surcharge conditional config was not found in the DB")?;
let record: SurchargeDecisionManagerRecord = algo_config
.config
.parse_struct("SurchargeDecisionConfigsRecord")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The Surcharge Decision Config Record was not found")?;
Ok(service_api::ApplicationResponse::Json(record))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/routing.rs | crates/router/src/core/routing.rs | pub mod helpers;
pub mod transformers;
use std::collections::HashSet;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use api_models::routing::DynamicRoutingAlgoAccessor;
use api_models::{
enums, mandates as mandates_api,
open_router::{
DecideGatewayResponse, OpenRouterDecideGatewayRequest, UpdateScorePayload,
UpdateScoreResponse,
},
routing,
routing::{
self as routing_types, RoutingRetrieveQuery, RuleMigrationError, RuleMigrationResponse,
},
};
use async_trait::async_trait;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use common_utils::ext_traits::AsyncExt;
use common_utils::request::Method;
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use external_services::grpc_client::dynamic_routing::{
contract_routing_client::ContractBasedDynamicRouting,
elimination_based_client::EliminationBasedRouting,
success_rate_client::SuccessBasedDynamicRouting,
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use helpers::{
enable_decision_engine_dynamic_routing_setup, update_decision_engine_dynamic_routing_setup,
};
use hyperswitch_domain_models::{mandates, payment_address};
use payment_methods::helpers::StorageErrorExt;
use rustc_hash::FxHashSet;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use storage_impl::redis::cache;
#[cfg(feature = "payouts")]
use super::payouts;
use super::{
errors::RouterResult,
payments::{
routing::{
utils::*,
{self as payments_routing},
},
OperationSessionGetters,
},
};
#[cfg(feature = "v1")]
use crate::utils::ValueExt;
#[cfg(feature = "v2")]
use crate::{core::admin, utils::ValueExt};
use crate::{
core::{
errors::{self, CustomResult, RouterResponse},
metrics,
payments::routing::get_active_mca_ids,
utils as core_utils,
},
db::StorageInterface,
routes::SessionState,
services::api as service_api,
types::{
api, domain,
storage::{self, enums as storage_enums},
transformers::{ForeignInto, ForeignTryFrom},
},
utils::{self, OptionExt},
};
pub enum TransactionData<'a> {
Payment(PaymentsDslInput<'a>),
#[cfg(feature = "payouts")]
Payout(&'a payouts::PayoutData),
}
#[derive(Debug, Clone)]
pub struct PaymentsDslInput<'a> {
pub setup_mandate: Option<&'a mandates::MandateData>,
pub payment_attempt: &'a storage::PaymentAttempt,
pub payment_intent: &'a storage::PaymentIntent,
pub payment_method_data: Option<&'a domain::PaymentMethodData>,
pub address: &'a payment_address::PaymentAddress,
pub recurring_details: Option<&'a mandates_api::RecurringDetails>,
pub currency: storage_enums::Currency,
}
impl<'a> PaymentsDslInput<'a> {
pub fn new(
setup_mandate: Option<&'a mandates::MandateData>,
payment_attempt: &'a storage::PaymentAttempt,
payment_intent: &'a storage::PaymentIntent,
payment_method_data: Option<&'a domain::PaymentMethodData>,
address: &'a payment_address::PaymentAddress,
recurring_details: Option<&'a mandates_api::RecurringDetails>,
currency: storage_enums::Currency,
) -> Self {
Self {
setup_mandate,
payment_attempt,
payment_intent,
payment_method_data,
address,
recurring_details,
currency,
}
}
}
#[cfg(feature = "v2")]
struct RoutingAlgorithmUpdate(RoutingAlgorithm);
#[cfg(feature = "v2")]
impl RoutingAlgorithmUpdate {
pub fn create_new_routing_algorithm(
request: &routing_types::RoutingConfigRequest,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: common_utils::id_type::ProfileId,
transaction_type: enums::TransactionType,
) -> Self {
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id,
profile_id,
merchant_id: merchant_id.clone(),
name: request.name.clone(),
description: Some(request.description.clone()),
kind: request.algorithm.get_kind().foreign_into(),
algorithm_data: serde_json::json!(request.algorithm),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: transaction_type,
decision_engine_routing_id: None,
};
Self(algo)
}
pub async fn fetch_routing_algo(
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &common_utils::id_type::RoutingId,
db: &dyn StorageInterface,
) -> RouterResult<Self> {
let routing_algo = db
.find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
Ok(Self(routing_algo))
}
}
pub async fn retrieve_merchant_routing_dictionary(
state: SessionState,
platform: domain::Platform,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
query_params: RoutingRetrieveQuery,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingKind> {
metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE.add(1, &[]);
let routing_metadata: Vec<diesel_models::routing_algorithm::RoutingProfileMetadata> = state
.store
.list_routing_algorithm_metadata_by_merchant_id_transaction_type(
platform.get_processor().get_account().get_id(),
&transaction_type,
i64::from(query_params.limit.unwrap_or_default()),
i64::from(query_params.offset.unwrap_or_default()),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let routing_metadata = super::utils::filter_objects_based_on_profile_id_list(
profile_id_list.clone(),
routing_metadata,
);
let mut result = routing_metadata
.into_iter()
.map(ForeignInto::foreign_into)
.collect::<Vec<_>>();
if let Some(profile_ids) = profile_id_list {
let mut de_result: Vec<routing_types::RoutingDictionaryRecord> = vec![];
// DE_TODO: need to replace this with batch API call to reduce the number of network calls
for profile_id in &profile_ids {
let list_request = ListRountingAlgorithmsRequest {
created_by: profile_id.get_string_repr().to_string(),
};
list_de_euclid_routing_algorithms(&state, list_request)
.await
.map_err(|e| {
router_env::logger::error!(decision_engine_error=?e, "decision_engine_euclid");
})
.ok() // Avoid throwing error if Decision Engine is not available or other errors
.map(|mut de_routing| de_result.append(&mut de_routing));
// filter de_result based on transaction type
de_result.retain(|record| record.algorithm_for == Some(transaction_type));
// append dynamic routing algorithms to de_result
de_result.append(
&mut result
.clone()
.into_iter()
.filter(|record: &routing_types::RoutingDictionaryRecord| {
record.kind == routing_types::RoutingAlgorithmKind::Dynamic
})
.collect::<Vec<_>>(),
);
}
compare_and_log_result(
de_result.clone(),
result.clone(),
"list_routing".to_string(),
);
result =
build_list_routing_result(&state, platform, &result, &de_result, profile_ids.clone())
.await?;
}
metrics::ROUTING_MERCHANT_DICTIONARY_RETRIEVE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_types::RoutingKind::RoutingAlgorithm(result),
))
}
async fn build_list_routing_result(
state: &SessionState,
platform: domain::Platform,
hs_results: &[routing_types::RoutingDictionaryRecord],
de_results: &[routing_types::RoutingDictionaryRecord],
profile_ids: Vec<common_utils::id_type::ProfileId>,
) -> RouterResult<Vec<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let mut list_result: Vec<routing_types::RoutingDictionaryRecord> = vec![];
for profile_id in profile_ids.iter() {
let by_profile =
|rec: &&routing_types::RoutingDictionaryRecord| &rec.profile_id == profile_id;
let de_result_for_profile = de_results.iter().filter(by_profile).cloned().collect();
let hs_result_for_profile = hs_results.iter().filter(by_profile).cloned().collect();
let business_profile = core_utils::validate_and_get_business_profile(
db,
platform.get_processor(),
Some(profile_id),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
list_result.append(
&mut select_routing_result(
state,
&business_profile,
hs_result_for_profile,
de_result_for_profile,
)
.await,
);
}
Ok(list_result)
}
#[cfg(feature = "v2")]
pub async fn create_routing_algorithm_under_profile(
state: SessionState,
platform: domain::Platform,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
request: routing_types::RoutingConfigRequest,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]);
let db = &*state.store;
let business_profile = core_utils::validate_and_get_business_profile(
db,
platform.get_processor(),
Some(&request.profile_id),
)
.await?
.get_required_value("Profile")?;
let merchant_id = platform.get_processor().get_account().get_id();
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
let all_mcas = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
merchant_id,
true,
platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_id.get_string_repr().to_owned(),
})?;
let name_mca_id_set = helpers::ConnectNameAndMCAIdForProfile(
all_mcas.filter_by_profile(business_profile.get_id(), |mca| {
(&mca.connector_name, mca.get_id())
}),
);
let name_set = helpers::ConnectNameForProfile(
all_mcas.filter_by_profile(business_profile.get_id(), |mca| &mca.connector_name),
);
let algorithm_helper = helpers::RoutingAlgorithmHelpers {
name_mca_id_set,
name_set,
routing_algorithm: &request.algorithm,
};
algorithm_helper.validate_connectors_in_routing_config()?;
let algo = RoutingAlgorithmUpdate::create_new_routing_algorithm(
&request,
platform.get_processor().get_account().get_id(),
business_profile.get_id().to_owned(),
transaction_type,
);
let record = state
.store
.as_ref()
.insert_routing_algorithm(algo.0)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let new_record = record.foreign_into();
metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[cfg(feature = "v1")]
pub async fn create_routing_algorithm_under_profile(
state: SessionState,
platform: domain::Platform,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
request: routing_types::RoutingConfigRequest,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm;
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]);
let db = state.store.as_ref();
let name = request
.name
.get_required_value("name")
.change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name" })
.attach_printable("Name of config not given")?;
let description = request
.description
.get_required_value("description")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "description",
})
.attach_printable("Description of config not given")?;
let algorithm = request
.algorithm
.clone()
.get_required_value("algorithm")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "algorithm",
})
.attach_printable("Algorithm of config not given")?;
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let profile_id = request
.profile_id
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id",
})
.attach_printable("Profile_id not provided")?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
platform.get_processor(),
Some(&profile_id),
)
.await?
.get_required_value("Profile")?;
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
if algorithm.should_validate_connectors_in_routing_config() {
helpers::validate_connectors_in_routing_config(
&state,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().get_id(),
&profile_id,
&algorithm,
)
.await?;
}
let mut decision_engine_routing_id: Option<String> = None;
if let Some(euclid_algorithm) = request.algorithm.clone() {
let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match euclid_algorithm {
EuclidAlgorithm::Advanced(program) => match program.try_into() {
Ok(internal_program) => Some(StaticRoutingAlgorithm::Advanced(internal_program)),
Err(e) => {
router_env::logger::error!(decision_engine_error = ?e, "decision_engine_euclid");
None
}
},
EuclidAlgorithm::Single(conn) => {
Some(StaticRoutingAlgorithm::Single(Box::new(conn.into())))
}
EuclidAlgorithm::Priority(connectors) => {
let converted: Vec<ConnectorInfo> =
connectors.into_iter().map(Into::into).collect();
Some(StaticRoutingAlgorithm::Priority(converted))
}
EuclidAlgorithm::VolumeSplit(splits) => {
let converted: Vec<VolumeSplit<ConnectorInfo>> =
splits.into_iter().map(Into::into).collect();
Some(StaticRoutingAlgorithm::VolumeSplit(converted))
}
EuclidAlgorithm::ThreeDsDecisionRule(_) => {
router_env::logger::error!(
"decision_engine_euclid: ThreeDsDecisionRules are not yet implemented"
);
None
}
};
if let Some(static_algorithm) = maybe_static_algorithm {
let routing_rule = RoutingRule {
rule_id: Some(algorithm_id.clone().get_string_repr().to_owned()),
name: name.to_string(),
description: Some(description.clone()),
created_by: profile_id.get_string_repr().to_string(),
algorithm: static_algorithm,
algorithm_for: transaction_type.into(),
metadata: Some(RoutingMetadata {
kind: algorithm.get_kind().foreign_into(),
}),
};
match create_de_euclid_routing_algo(&state, &routing_rule).await {
Ok(id) => {
decision_engine_routing_id = Some(id);
}
Err(e)
if matches!(
e.current_context(),
errors::RoutingError::DecisionEngineValidationError(_)
) =>
{
if let errors::RoutingError::DecisionEngineValidationError(msg) =
e.current_context()
{
router_env::logger::error!(
decision_engine_euclid_error = ?msg,
decision_engine_euclid_request = ?routing_rule,
"failed to create rule in decision_engine with validation error"
);
}
}
Err(e) => {
router_env::logger::error!(
decision_engine_euclid_error = ?e,
decision_engine_euclid_request = ?routing_rule,
"failed to create rule in decision_engine"
);
}
}
}
}
if decision_engine_routing_id.is_some() {
router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"true", "decision_engine_euclid");
} else {
router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"false", "decision_engine_euclid");
}
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id,
merchant_id: platform.get_processor().get_account().get_id().to_owned(),
name: name.to_string(),
description: Some(description.clone()),
kind: algorithm.get_kind().foreign_into(),
algorithm_data: serde_json::json!(algorithm),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: transaction_type.to_owned(),
decision_engine_routing_id,
};
let record = db
.insert_routing_algorithm(algo)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let new_record = record.foreign_into();
metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[cfg(feature = "v2")]
pub async fn link_routing_config_under_profile(
state: SessionState,
platform: domain::Platform,
profile_id: common_utils::id_type::ProfileId,
algorithm_id: common_utils::id_type::RoutingId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_LINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo(
platform.get_processor().get_account().get_id(),
&algorithm_id,
db,
)
.await?;
utils::when(routing_algorithm.0.profile_id != profile_id, || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Profile Id is invalid for the routing config".to_string(),
})
})?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
platform.get_processor(),
Some(&profile_id),
)
.await?
.get_required_value("Profile")?;
utils::when(
routing_algorithm.0.algorithm_for != *transaction_type,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"Cannot use {}'s routing algorithm for {} operation",
routing_algorithm.0.algorithm_for, transaction_type
),
})
},
)?;
utils::when(
business_profile.routing_algorithm_id == Some(algorithm_id.clone())
|| business_profile.payout_routing_algorithm_id == Some(algorithm_id.clone()),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already active".to_string(),
})
},
)?;
admin::ProfileWrapper::new(business_profile)
.update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
db,
key_manager_state,
platform.get_processor().get_key_store(),
algorithm_id,
transaction_type,
)
.await?;
metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_algorithm.0.foreign_into(),
))
}
#[cfg(feature = "v1")]
pub async fn link_routing_config(
state: SessionState,
platform: domain::Platform,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_LINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
&algorithm_id,
platform.get_processor().get_account().get_id(),
)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
platform.get_processor(),
Some(&routing_algorithm.profile_id),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: routing_algorithm.profile_id.get_string_repr().to_owned(),
})?;
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
match routing_algorithm.kind {
diesel_models::enums::RoutingAlgorithmKind::Dynamic => {
let mut dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef =
business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize Dynamic routing algorithm ref from business profile",
)?
.unwrap_or_default();
utils::when(
matches!(
dynamic_routing_ref.success_based_algorithm,
Some(routing::SuccessBasedAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp {
algorithm_id: Some(ref id),
timestamp: _
},
enabled_feature: _
}) if id == &algorithm_id
) || matches!(
dynamic_routing_ref.elimination_routing_algorithm,
Some(routing::EliminationRoutingAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp {
algorithm_id: Some(ref id),
timestamp: _
},
enabled_feature: _
}) if id == &algorithm_id
) || matches!(
dynamic_routing_ref.contract_based_routing,
Some(routing::ContractRoutingAlgorithm {
algorithm_id_with_timestamp:
routing_types::DynamicAlgorithmWithTimestamp {
algorithm_id: Some(ref id),
timestamp: _
},
enabled_feature: _
}) if id == &algorithm_id
),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already active".to_string(),
})
},
)?;
if routing_algorithm.name == helpers::SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM {
dynamic_routing_ref.update_algorithm_id(
algorithm_id,
dynamic_routing_ref
.success_based_algorithm
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"missing success_based_algorithm in dynamic_algorithm_ref from business_profile table",
)?
.enabled_feature,
routing_types::DynamicRoutingType::SuccessRateBasedRouting,
);
// Call to DE here to update SR configs
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
{
if state.conf.open_router.dynamic_routing_enabled {
let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm(
&state,
business_profile.get_id(),
api_models::open_router::DecisionEngineDynamicAlgorithmType::SuccessRate,
)
.await;
if let Ok(Some(_config)) = existing_config {
update_decision_engine_dynamic_routing_setup(
&state,
business_profile.get_id(),
routing_algorithm.algorithm_data.clone(),
routing_types::DynamicRoutingType::SuccessRateBasedRouting,
&mut dynamic_routing_ref,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to update the success rate routing config in Decision Engine",
)?;
} else {
let data: routing_types::SuccessBasedRoutingConfig =
routing_algorithm.algorithm_data
.clone()
.parse_value("SuccessBasedRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize SuccessBasedRoutingConfig from routing algorithm data",
)?;
enable_decision_engine_dynamic_routing_setup(
&state,
business_profile.get_id(),
routing_types::DynamicRoutingType::SuccessRateBasedRouting,
&mut dynamic_routing_ref,
Some(routing_types::DynamicRoutingPayload::SuccessBasedRoutingPayload(data)),
)
.await
.map_err(|err| match err.current_context() {
errors::ApiErrorResponse::GenericNotFoundError {..}=> {
err.change_context(errors::ApiErrorResponse::ConfigNotFound)
.attach_printable("Decision engine config not found")
}
_ => err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing"),
})?;
}
}
}
} else if routing_algorithm.name == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM
{
dynamic_routing_ref.update_algorithm_id(
algorithm_id,
dynamic_routing_ref
.elimination_routing_algorithm
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"missing elimination_routing_algorithm in dynamic_algorithm_ref from business_profile table",
)?
.enabled_feature,
routing_types::DynamicRoutingType::EliminationRouting,
);
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
{
if state.conf.open_router.dynamic_routing_enabled {
let existing_config = helpers::get_decision_engine_active_dynamic_routing_algorithm(
&state,
business_profile.get_id(),
api_models::open_router::DecisionEngineDynamicAlgorithmType::Elimination,
)
.await;
if let Ok(Some(_config)) = existing_config {
update_decision_engine_dynamic_routing_setup(
&state,
business_profile.get_id(),
routing_algorithm.algorithm_data.clone(),
routing_types::DynamicRoutingType::EliminationRouting,
&mut dynamic_routing_ref,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to update the elimination routing config in Decision Engine",
)?;
} else {
let data: routing_types::EliminationRoutingConfig =
routing_algorithm.algorithm_data
.clone()
.parse_value("EliminationRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize EliminationRoutingConfig from routing algorithm data",
)?;
enable_decision_engine_dynamic_routing_setup(
&state,
business_profile.get_id(),
routing_types::DynamicRoutingType::EliminationRouting,
&mut dynamic_routing_ref,
Some(
routing_types::DynamicRoutingPayload::EliminationRoutingPayload(
data,
),
),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to setup decision engine dynamic routing")?;
}
}
}
} else if routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM {
dynamic_routing_ref.update_algorithm_id(
algorithm_id,
dynamic_routing_ref
.contract_based_routing
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"missing contract_based_routing in dynamic_algorithm_ref from business_profile table",
)?
.enabled_feature,
routing_types::DynamicRoutingType::ContractBasedRouting,
);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/customers.rs | crates/router/src/core/customers.rs | use common_types::primitive_wrappers::CustomerListLimit;
use common_utils::{
crypto::Encryptable,
errors::ReportSwitchExt,
ext_traits::AsyncExt,
id_type, pii, type_name,
types::{
keymanager::{Identifier, KeyManagerState, ToEncryptable},
Description,
},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payment_methods as payment_methods_domain;
use masking::{ExposeInterface, Secret, SwitchStrategy};
use payment_methods::controller::PaymentMethodsController;
use router_env::{instrument, tracing};
#[cfg(feature = "v2")]
use crate::core::payment_methods::cards::create_encrypted_data;
#[cfg(feature = "v1")]
use crate::utils::CustomerAddress;
use crate::{
core::{
errors::{self, StorageErrorExt},
payment_methods::{cards, network_tokenization},
},
db::StorageInterface,
pii::PeekInterface,
routes::{metrics, SessionState},
services,
types::{
api::customers,
domain::{self, types},
storage::{self, enums},
transformers::ForeignFrom,
},
};
pub const REDACTED: &str = "Redacted";
#[instrument(skip(state))]
pub async fn create_customer(
state: SessionState,
provider: domain::Provider,
customer_data: customers::CustomerRequest,
connector_customer_details: Option<Vec<payment_methods_domain::ConnectorCustomerDetails>>,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db: &dyn StorageInterface = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_reference_id = customer_data.get_merchant_reference_id();
let merchant_id = provider.get_account().get_id();
let merchant_reference_id_customer = MerchantReferenceIdForCustomer {
merchant_reference_id: merchant_reference_id.as_ref(),
merchant_id,
merchant_account: provider.get_account(),
key_store: provider.get_key_store(),
};
// We first need to validate whether the customer with the given customer id already exists
// this may seem like a redundant db call, as the insert_customer will anyway return this error
//
// Consider a scenario where the address is inserted and then when inserting the customer,
// it errors out, now the address that was inserted is not deleted
merchant_reference_id_customer
.verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(db)
.await?;
let domain_customer = customer_data
.create_domain_model_from_request(
&connector_customer_details,
db,
&merchant_reference_id,
&provider,
key_manager_state,
&state,
)
.await?;
let customer = db
.insert_customer(
domain_customer,
provider.get_key_store(),
provider.get_account().storage_scheme,
)
.await
.to_duplicate_response(errors::CustomersErrorResponse::CustomerAlreadyExists)?;
customer_data.generate_response(&customer)
}
#[async_trait::async_trait]
trait CustomerCreateBridge {
async fn create_domain_model_from_request<'a>(
&'a self,
connector_customer_details: &'a Option<
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
db: &'a dyn StorageInterface,
merchant_reference_id: &'a Option<id_type::CustomerId>,
provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>;
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse>;
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl CustomerCreateBridge for customers::CustomerRequest {
async fn create_domain_model_from_request<'a>(
&'a self,
connector_customer_details: &'a Option<
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
db: &'a dyn StorageInterface,
merchant_reference_id: &'a Option<id_type::CustomerId>,
provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
// Setting default billing address to Db
let address = self.get_address();
let merchant_id = provider.get_account().get_id();
let key = provider.get_key_store().key.get_inner().peek();
let customer_billing_address_struct = AddressStructForDbEntry {
address: address.as_ref(),
customer_data: self,
merchant_id,
customer_id: merchant_reference_id.as_ref(),
storage_scheme: provider.get_account().storage_scheme,
key_store: provider.get_key_store(),
state,
};
let address_from_db = customer_billing_address_struct
.encrypt_customer_address_and_set_to_db(db)
.await?;
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: self.name.clone(),
email: self.email.clone().map(|a| a.expose().switch_strategy()),
phone: self.phone.clone(),
tax_registration_id: self.tax_registration_id.clone(),
},
),
),
Identifier::Merchant(provider.get_key_store().merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.switch()
.attach_printable("Failed while encrypting Customer")?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
let connector_customer = connector_customer_details.as_ref().map(|details_vec| {
let mut map = serde_json::Map::new();
for details in details_vec {
let merchant_connector_id =
details.merchant_connector_id.get_string_repr().to_string();
let connector_customer_id = details.connector_customer_id.clone();
map.insert(merchant_connector_id, connector_customer_id.into());
}
pii::SecretSerdeValue::new(serde_json::Value::Object(map))
});
Ok(domain::Customer {
customer_id: merchant_reference_id
.to_owned()
.ok_or(errors::CustomersErrorResponse::InternalServerError)?,
merchant_id: merchant_id.to_owned(),
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
description: self.description.clone(),
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
connector_customer,
address_id: address_from_db.clone().map(|addr| addr.address_id),
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
default_payment_method_id: None,
updated_by: None,
version: common_types::consts::API_VERSION,
tax_registration_id: encryptable_customer.tax_registration_id,
// TODO: Populate created_by from authentication context once it is integrated in auth data
created_by: None,
last_modified_by: None,
})
}
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let address = self.get_address();
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from((customer.clone(), address)),
))
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl CustomerCreateBridge for customers::CustomerRequest {
async fn create_domain_model_from_request<'a>(
&'a self,
connector_customer_details: &'a Option<
Vec<payment_methods_domain::ConnectorCustomerDetails>,
>,
_db: &'a dyn StorageInterface,
merchant_reference_id: &'a Option<id_type::CustomerId>,
provider: &'a domain::Provider,
key_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
let default_customer_billing_address = self.get_default_customer_billing_address();
let encrypted_customer_billing_address = default_customer_billing_address
.async_map(|billing_address| {
create_encrypted_data(key_state, provider.get_key_store(), billing_address)
})
.await
.transpose()
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt default customer billing address")?;
let default_customer_shipping_address = self.get_default_customer_shipping_address();
let encrypted_customer_shipping_address = default_customer_shipping_address
.async_map(|shipping_address| {
create_encrypted_data(key_state, provider.get_key_store(), shipping_address)
})
.await
.transpose()
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt default customer shipping address")?;
let merchant_id = provider.get_account().get_id().clone();
let key = provider.get_key_store().key.get_inner().peek();
let encrypted_data = types::crypto_operation(
key_state,
type_name!(domain::Customer),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: Some(self.name.clone()),
email: Some(self.email.clone().expose().switch_strategy()),
phone: self.phone.clone(),
tax_registration_id: self.tax_registration_id.clone(),
},
),
),
Identifier::Merchant(provider.get_key_store().merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.switch()
.attach_printable("Failed while encrypting Customer")?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
let connector_customer = connector_customer_details.as_ref().map(|details_vec| {
let map: std::collections::HashMap<_, _> = details_vec
.iter()
.map(|details| {
(
details.merchant_connector_id.clone(),
details.connector_customer_id.to_string(),
)
})
.collect();
common_types::customers::ConnectorCustomerMap::new(map)
});
Ok(domain::Customer {
id: id_type::GlobalCustomerId::generate(&state.conf.cell_information.id),
merchant_reference_id: merchant_reference_id.to_owned(),
merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
description: self.description.clone(),
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
connector_customer,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
default_payment_method_id: None,
updated_by: None,
default_billing_address: encrypted_customer_billing_address.map(Into::into),
default_shipping_address: encrypted_customer_shipping_address.map(Into::into),
version: common_types::consts::API_VERSION,
status: common_enums::DeleteStatus::Active,
tax_registration_id: encryptable_customer.tax_registration_id,
// TODO: Populate created_by from authentication context once it is integrated in auth data
created_by: None,
last_modified_by: None,
})
}
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse> {
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from(customer.clone()),
))
}
}
#[cfg(feature = "v1")]
struct AddressStructForDbEntry<'a> {
address: Option<&'a api_models::payments::AddressDetails>,
customer_data: &'a customers::CustomerRequest,
merchant_id: &'a id_type::MerchantId,
customer_id: Option<&'a id_type::CustomerId>,
storage_scheme: common_enums::MerchantStorageScheme,
key_store: &'a domain::MerchantKeyStore,
state: &'a SessionState,
}
#[cfg(feature = "v1")]
impl AddressStructForDbEntry<'_> {
async fn encrypt_customer_address_and_set_to_db(
&self,
db: &dyn StorageInterface,
) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> {
let encrypted_customer_address = self
.address
.async_map(|addr| async {
self.customer_data
.get_domain_address(
self.state,
addr.clone(),
self.merchant_id,
self.customer_id
.ok_or(errors::CustomersErrorResponse::InternalServerError)?, // should we raise error since in v1 appilcation is supposed to have this id or generate it at this point.
self.key_store.key.get_inner().peek(),
self.storage_scheme,
)
.await
.switch()
.attach_printable("Failed while encrypting address")
})
.await
.transpose()?;
encrypted_customer_address
.async_map(|encrypt_add| async {
db.insert_address_for_customers(encrypt_add, self.key_store)
.await
.switch()
.attach_printable("Failed while inserting new address")
})
.await
.transpose()
}
}
struct MerchantReferenceIdForCustomer<'a> {
merchant_reference_id: Option<&'a id_type::CustomerId>,
merchant_id: &'a id_type::MerchantId,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
}
#[cfg(feature = "v1")]
impl<'a> MerchantReferenceIdForCustomer<'a> {
async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(
&self,
db: &dyn StorageInterface,
) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> {
self.merchant_reference_id
.async_map(|cust| async {
self.verify_if_merchant_reference_not_present_by_merchant_reference_id(cust, db)
.await
})
.await
.transpose()
}
async fn verify_if_merchant_reference_not_present_by_merchant_reference_id(
&self,
cus: &'a id_type::CustomerId,
db: &dyn StorageInterface,
) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> {
match db
.find_customer_by_customer_id_merchant_id(
cus,
self.merchant_id,
self.key_store,
self.merchant_account.storage_scheme,
)
.await
{
Err(err) => {
if !err.current_context().is_db_not_found() {
Err(err).switch()
} else {
Ok(())
}
}
Ok(_) => Err(report!(
errors::CustomersErrorResponse::CustomerAlreadyExists
)),
}
}
}
#[cfg(feature = "v2")]
impl<'a> MerchantReferenceIdForCustomer<'a> {
async fn verify_if_merchant_reference_not_present_by_optional_merchant_reference_id(
&self,
db: &dyn StorageInterface,
) -> Result<Option<()>, error_stack::Report<errors::CustomersErrorResponse>> {
self.merchant_reference_id
.async_map(|merchant_ref| async {
self.verify_if_merchant_reference_not_present_by_merchant_reference(
merchant_ref,
db,
)
.await
})
.await
.transpose()
}
async fn verify_if_merchant_reference_not_present_by_merchant_reference(
&self,
merchant_ref: &'a id_type::CustomerId,
db: &dyn StorageInterface,
) -> Result<(), error_stack::Report<errors::CustomersErrorResponse>> {
match db
.find_customer_by_merchant_reference_id_merchant_id(
merchant_ref,
self.merchant_id,
self.key_store,
self.merchant_account.storage_scheme,
)
.await
{
Err(err) => {
if !err.current_context().is_db_not_found() {
Err(err).switch()
} else {
Ok(())
}
}
Ok(_) => Err(report!(
errors::CustomersErrorResponse::CustomerAlreadyExists
)),
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn retrieve_customer(
state: SessionState,
provider: domain::Provider,
_profile_id: Option<id_type::ProfileId>,
customer_id: id_type::CustomerId,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
let response = db
.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&customer_id,
provider.get_account().get_id(),
provider.get_key_store(),
provider.get_account().storage_scheme,
)
.await
.switch()?
.ok_or(errors::CustomersErrorResponse::CustomerNotFound)?;
let address = match &response.address_id {
Some(address_id) => Some(api_models::payments::AddressDetails::from(
db.find_address_by_address_id(address_id, provider.get_key_store())
.await
.switch()?,
)),
None => None,
};
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from((response, address)),
))
}
#[cfg(feature = "v2")]
#[instrument(skip(state))]
pub async fn retrieve_customer(
state: SessionState,
provider: domain::Provider,
id: id_type::GlobalCustomerId,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
let response = db
.find_customer_by_global_id(
&id,
provider.get_key_store(),
provider.get_account().storage_scheme,
)
.await
.switch()?;
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from(response),
))
}
#[instrument(skip(state))]
pub async fn list_customers(
state: SessionState,
provider: domain::Provider,
_profile_id_list: Option<Vec<id_type::ProfileId>>,
request: customers::CustomerListRequest,
) -> errors::CustomerResponse<Vec<customers::CustomerResponse>> {
let db = state.store.as_ref();
let customer_list_constraints = crate::db::customers::CustomerListConstraints {
limit: request
.limit
.unwrap_or(crate::consts::DEFAULT_LIST_API_LIMIT),
offset: request.offset,
customer_id: request.customer_id,
time_range: None,
};
let domain_customers = db
.list_customers_by_merchant_id(
provider.get_account().get_id(),
provider.get_key_store(),
customer_list_constraints,
)
.await
.switch()?;
#[cfg(feature = "v1")]
let customers = domain_customers
.into_iter()
.map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None)))
.collect();
#[cfg(feature = "v2")]
let customers = domain_customers
.into_iter()
.map(customers::CustomerResponse::foreign_from)
.collect();
Ok(services::ApplicationResponse::Json(customers))
}
#[instrument(skip(state))]
pub async fn list_customers_with_count(
state: SessionState,
provider: domain::Provider,
request: customers::CustomerListRequestWithConstraints,
) -> errors::CustomerResponse<customers::CustomerListResponse> {
let db = state.store.as_ref();
let customer_list_constraints = crate::db::customers::CustomerListConstraints {
limit: request
.limit
.map(|l| *l)
.unwrap_or_else(|| *CustomerListLimit::default()),
offset: request.offset,
customer_id: request.customer_id,
time_range: request.time_range,
};
let domain_customers = db
.list_customers_by_merchant_id_with_count(
provider.get_account().get_id(),
provider.get_key_store(),
customer_list_constraints,
)
.await
.switch()?;
#[cfg(feature = "v1")]
let customers: Vec<customers::CustomerResponse> = domain_customers
.0
.into_iter()
.map(|domain_customer| customers::CustomerResponse::foreign_from((domain_customer, None)))
.collect();
#[cfg(feature = "v2")]
let customers: Vec<customers::CustomerResponse> = domain_customers
.0
.into_iter()
.map(customers::CustomerResponse::foreign_from)
.collect();
Ok(services::ApplicationResponse::Json(
customers::CustomerListResponse {
data: customers.into_iter().map(|c| c.0).collect(),
total_count: domain_customers.1,
},
))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_customer(
state: SessionState,
provider: domain::Provider,
id: id_type::GlobalCustomerId,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let db = &*state.store;
let key_manager_state = &(&state).into();
id.redact_customer_details_and_generate_response(db, &provider, key_manager_state, &state)
.await
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl CustomerDeleteBridge for id_type::GlobalCustomerId {
async fn redact_customer_details_and_generate_response<'a>(
&'a self,
db: &'a dyn StorageInterface,
provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let customer_orig = db
.find_customer_by_global_id(
self,
provider.get_key_store(),
provider.get_account().storage_scheme,
)
.await
.switch()?;
let merchant_reference_id = customer_orig.merchant_reference_id.clone();
let customer_mandates = db.find_mandate_by_global_customer_id(self).await.switch()?;
for mandate in customer_mandates.into_iter() {
if mandate.mandate_status == enums::MandateStatus::Active {
Err(errors::CustomersErrorResponse::MandateActive)?
}
}
match db
.find_payment_method_list_by_global_customer_id(provider.get_key_store(), self, None)
.await
{
// check this in review
Ok(customer_payment_methods) => {
for pm in customer_payment_methods.into_iter() {
if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
cards::delete_card_by_locker_id(
state,
self,
provider.get_account().get_id(),
)
.await
.switch()?;
}
// No solution as of now, need to discuss this further with payment_method_v2
// db.delete_payment_method(
// key_manager_state,
// key_store,
// pm,
// )
// .await
// .switch()?;
}
}
Err(error) => {
if error.current_context().is_db_not_found() {
Ok(())
} else {
Err(error)
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable(
"failed find_payment_method_by_customer_id_merchant_id_list",
)
}?
}
};
let key = provider.get_key_store().key.get_inner().peek();
let identifier = Identifier::Merchant(provider.get_key_store().merchant_id.clone());
let redacted_encrypted_value: Encryptable<Secret<_>> = types::crypto_operation(
key_manager_state,
type_name!(storage::Address),
types::CryptoOperation::Encrypt(REDACTED.to_string().into()),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_operation())
.switch()?;
let redacted_encrypted_email = Encryptable::new(
redacted_encrypted_value
.clone()
.into_inner()
.switch_strategy(),
redacted_encrypted_value.clone().into_encrypted(),
);
let updated_customer =
storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate {
name: Some(redacted_encrypted_value.clone()),
email: Box::new(Some(redacted_encrypted_email)),
phone: Box::new(Some(redacted_encrypted_value.clone())),
description: Some(Description::from_str_unchecked(REDACTED)),
phone_country_code: Some(REDACTED.to_string()),
metadata: None,
connector_customer: Box::new(None),
default_billing_address: None,
default_shipping_address: None,
default_payment_method_id: None,
status: Some(common_enums::DeleteStatus::Redacted),
tax_registration_id: Some(redacted_encrypted_value),
last_modified_by: None,
}));
db.update_customer_by_global_id(
self,
customer_orig,
updated_customer,
provider.get_key_store(),
provider.get_account().storage_scheme,
)
.await
.switch()?;
let response = customers::CustomerDeleteResponse {
id: self.clone(),
merchant_reference_id,
customer_deleted: true,
address_deleted: true,
payment_methods_deleted: true,
};
metrics::CUSTOMER_REDACTED.add(1, &[]);
Ok(services::ApplicationResponse::Json(response))
}
}
#[async_trait::async_trait]
trait CustomerDeleteBridge {
async fn redact_customer_details_and_generate_response<'a>(
&'a self,
db: &'a dyn StorageInterface,
provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse>;
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn delete_customer(
state: SessionState,
provider: domain::Provider,
customer_id: id_type::CustomerId,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let db = &*state.store;
let key_manager_state = &(&state).into();
customer_id
.redact_customer_details_and_generate_response(db, &provider, key_manager_state, &state)
.await
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl CustomerDeleteBridge for id_type::CustomerId {
async fn redact_customer_details_and_generate_response<'a>(
&'a self,
db: &'a dyn StorageInterface,
provider: &'a domain::Provider,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let customer_orig = db
.find_customer_by_customer_id_merchant_id(
self,
provider.get_account().get_id(),
provider.get_key_store(),
provider.get_account().storage_scheme,
)
.await
.switch()?;
let customer_mandates = db
.find_mandate_by_merchant_id_customer_id(provider.get_account().get_id(), self)
.await
.switch()?;
for mandate in customer_mandates.into_iter() {
if mandate.mandate_status == enums::MandateStatus::Active {
Err(errors::CustomersErrorResponse::MandateActive)?
}
}
match db
.find_payment_method_by_customer_id_merchant_id_list(
provider.get_key_store(),
self,
provider.get_account().get_id(),
None,
)
.await
{
// check this in review
Ok(customer_payment_methods) => {
for pm in customer_payment_methods.into_iter() {
if pm.get_payment_method_type() == Some(enums::PaymentMethod::Card) {
cards::PmCards { state, provider }
.delete_card_from_locker(
self,
provider.get_account().get_id(),
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.switch()?;
if let Some(network_token_ref_id) = pm.network_token_requestor_reference_id
{
network_tokenization::delete_network_token_from_locker_and_token_service(
state,
self,
provider.get_account().get_id(),
pm.payment_method_id.clone(),
pm.network_token_locker_id,
network_token_ref_id,
provider,
)
.await
.switch()?;
}
}
db.delete_payment_method_by_merchant_id_payment_method_id(
provider.get_key_store(),
provider.get_account().get_id(),
&pm.payment_method_id,
)
.await
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable(
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payout_link.rs | crates/router/src/core/payout_link.rs | use std::{
cmp::Ordering,
collections::{HashMap, HashSet},
};
use actix_web::http::header;
use api_models::payouts;
use common_utils::{
ext_traits::{AsyncExt, Encode, OptionExt},
link_utils,
types::{AmountConvertor, StringMajorUnitForConnector},
};
use diesel_models::PayoutLinkUpdate;
use error_stack::ResultExt;
use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
use super::errors::{RouterResponse, StorageErrorExt};
use crate::{
configs::settings::{PaymentMethodFilterKey, PaymentMethodFilters},
core::payouts::{helpers as payout_helpers, validator},
errors,
routes::{app::StorageInterface, SessionState},
services,
types::{api, domain, transformers::ForeignFrom},
utils::get_payout_attempt_id,
};
#[cfg(feature = "v2")]
pub async fn initiate_payout_link(
_state: SessionState,
_platform: domain::Platform,
_req: payouts::PayoutLinkInitiateRequest,
_request_headers: &header::HeaderMap,
_locale: String,
) -> RouterResponse<services::GenericLinkFormData> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn initiate_payout_link(
state: SessionState,
platform: domain::Platform,
req: payouts::PayoutLinkInitiateRequest,
request_headers: &header::HeaderMap,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
let merchant_id = platform.get_processor().get_account().get_id();
// Fetch payout
let payout = db
.find_payout_by_merchant_id_payout_id(
merchant_id,
&req.payout_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let payout_attempt = db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
&get_payout_attempt_id(payout.payout_id.get_string_repr(), payout.attempt_count),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let payout_link_id = payout
.payout_link_id
.clone()
.get_required_value("payout link id")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "payout link not found".to_string(),
})?;
// Fetch payout link
let payout_link = db
.find_payout_link_by_link_id(&payout_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payout link not found".to_string(),
})?;
let allowed_domains = validator::validate_payout_link_render_request_and_get_allowed_domains(
request_headers,
&payout_link,
)?;
// Check status and return form data accordingly
let has_expired = common_utils::date_time::now() > payout_link.expiry;
let status = payout_link.link_status.clone();
let link_data = payout_link.link_data.clone();
let default_config = &state.conf.generic_link.payout_link.clone();
let default_ui_config = default_config.ui_config.clone();
let ui_config_data = link_utils::GenericLinkUiConfigFormData {
merchant_name: link_data
.ui_config
.merchant_name
.unwrap_or(default_ui_config.merchant_name),
logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo),
theme: link_data
.ui_config
.theme
.clone()
.unwrap_or(default_ui_config.theme.clone()),
};
match (has_expired, &status) {
// Send back generic expired page
(true, _) | (_, &link_utils::PayoutLinkStatus::Invalidated) => {
let expired_link_data = services::GenericExpiredLinkData {
title: "Payout Expired".to_string(),
message: "This payout link has expired.".to_string(),
theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme),
};
if status != link_utils::PayoutLinkStatus::Invalidated {
let payout_link_update = PayoutLinkUpdate::StatusUpdate {
link_status: link_utils::PayoutLinkStatus::Invalidated,
};
db.update_payout_link(payout_link, payout_link_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout links in db")?;
}
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains,
data: GenericLinksData::ExpiredLink(expired_link_data),
locale: state.locale,
},
)))
}
// Initiate Payout link flow
(_, link_utils::PayoutLinkStatus::Initiated) => {
let customer_id = link_data.customer_id;
let required_amount_type = StringMajorUnitForConnector;
let amount = required_amount_type
.convert(payout.amount, payout.destination_currency)
.change_context(errors::ApiErrorResponse::CurrencyConversionFailed)?;
// Fetch customer
let customer = db
.find_customer_by_customer_id_merchant_id(
&customer_id,
&req.merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Customer [{:?}] not found for link_id - {}",
customer_id, payout_link.link_id
),
})
.attach_printable_lazy(|| format!("customer [{customer_id:?}] not found"))?;
let address = payout
.address_id
.as_ref()
.async_map(|address_id| async {
db.find_address_by_address_id(
address_id,
platform.get_processor().get_key_store(),
)
.await
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while fetching address [id - {:?}] for payout [id - {:?}]",
payout.address_id, payout.payout_id
)
})?;
let enabled_payout_methods =
filter_payout_methods(&state, &platform, &payout, address.as_ref()).await?;
// Fetch default enabled_payout_methods
let mut default_enabled_payout_methods: Vec<link_utils::EnabledPaymentMethod> = vec![];
for (payment_method, payment_method_types) in
default_config.enabled_payment_methods.clone().into_iter()
{
let enabled_payment_method = link_utils::EnabledPaymentMethod {
payment_method,
payment_method_types,
};
default_enabled_payout_methods.push(enabled_payment_method);
}
let fallback_enabled_payout_methods = if enabled_payout_methods.is_empty() {
&default_enabled_payout_methods
} else {
&enabled_payout_methods
};
// Fetch enabled payout methods from the request. If not found, fetch the enabled payout methods from MCA,
// If none are configured for merchant connector accounts, fetch them from the default enabled payout methods.
let mut enabled_payment_methods = link_data
.enabled_payment_methods
.unwrap_or(fallback_enabled_payout_methods.to_vec());
// Sort payment methods (cards first)
enabled_payment_methods.sort_by(|a, b| match (a.payment_method, b.payment_method) {
(_, common_enums::PaymentMethod::Card) => Ordering::Greater,
(common_enums::PaymentMethod::Card, _) => Ordering::Less,
_ => Ordering::Equal,
});
let required_field_override = api::RequiredFieldsOverrideRequest {
billing: address
.as_ref()
.map(hyperswitch_domain_models::address::Address::from)
.map(From::from),
};
let enabled_payment_methods_with_required_fields = ForeignFrom::foreign_from((
&state.conf.payouts.required_fields,
enabled_payment_methods.clone(),
required_field_override,
));
let js_data = payouts::PayoutLinkDetails {
publishable_key: masking::Secret::new(
platform
.get_processor()
.get_account()
.clone()
.publishable_key,
),
client_secret: link_data.client_secret.clone(),
payout_link_id: payout_link.link_id,
payout_id: payout_link.primary_reference.clone(),
customer_id: customer.customer_id,
session_expiry: payout_link.expiry,
return_url: payout_link
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse payout status link's return URL")?,
ui_config: ui_config_data,
enabled_payment_methods,
enabled_payment_methods_with_required_fields,
amount,
currency: payout.destination_currency,
locale: state.locale.clone(),
form_layout: link_data.form_layout,
test_mode: link_data.test_mode.unwrap_or(false),
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PAYOUT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")?
);
let generic_form_data = services::GenericLinkFormData {
js_data: serialized_js_content,
css_data: serialized_css_content,
sdk_url: default_config.sdk_url.clone(),
html_meta_tags: String::new(),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains,
data: GenericLinksData::PayoutLink(generic_form_data),
locale: state.locale.clone(),
},
)))
}
// Send back status page
(_, link_utils::PayoutLinkStatus::Submitted) => {
let translated_unified_message =
payout_helpers::get_translated_unified_code_and_message(
&state,
payout_attempt.unified_code.as_ref(),
payout_attempt.unified_message.as_ref(),
&state.locale.clone(),
)
.await?;
let js_data = payouts::PayoutLinkStatusDetails {
payout_link_id: payout_link.link_id,
payout_id: payout_link.primary_reference.clone(),
customer_id: link_data.customer_id,
session_expiry: payout_link.expiry,
return_url: payout_link
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse payout status link's return URL")?,
status: payout.status,
error_code: payout_attempt.unified_code,
error_message: translated_unified_message,
ui_config: ui_config_data,
test_mode: link_data.test_mode.unwrap_or(false),
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PAYOUT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")?
);
let generic_status_data = services::GenericLinkStatusData {
js_data: serialized_js_content,
css_data: serialized_css_content,
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains,
data: GenericLinksData::PayoutLinkStatus(generic_status_data),
locale: state.locale.clone(),
},
)))
}
}
}
#[cfg(all(feature = "payouts", feature = "v1"))]
pub async fn filter_payout_methods(
state: &SessionState,
platform: &domain::Platform,
payout: &hyperswitch_domain_models::payouts::payouts::Payouts,
address: Option<&domain::Address>,
) -> errors::RouterResult<Vec<link_utils::EnabledPaymentMethod>> {
use masking::ExposeInterface;
let db = &*state.store;
//Fetch all merchant connector accounts
let all_mcas = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
platform.get_processor().get_account().get_id(),
false,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
// Filter MCAs based on profile_id and connector_type
let filtered_mcas = all_mcas.filter_based_on_profile_and_connector_type(
&payout.profile_id,
common_enums::ConnectorType::PayoutProcessor,
);
let mut response: Vec<link_utils::EnabledPaymentMethod> = vec![];
let mut payment_method_list_hm: HashMap<
common_enums::PaymentMethod,
HashSet<common_enums::PaymentMethodType>,
> = HashMap::new();
let mut bank_transfer_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new();
let mut card_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new();
let mut wallet_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new();
let mut bank_redirect_hash_set: HashSet<common_enums::PaymentMethodType> = HashSet::new();
let payout_filter_config = &state.conf.payout_method_filters.clone();
for mca in &filtered_mcas {
let payout_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
for payout_method in payout_methods.iter() {
let parse_result = serde_json::from_value::<api_models::admin::PaymentMethodsEnabled>(
payout_method.clone().expose(),
);
if let Ok(payment_methods_enabled) = parse_result {
let payment_method = payment_methods_enabled.payment_method;
let payment_method_types = match payment_methods_enabled.payment_method_types {
Some(payment_method_types) => payment_method_types,
None => continue,
};
let connector = mca.connector_name.clone();
let payout_filter = payout_filter_config.0.get(&connector);
for request_payout_method_type in &payment_method_types {
let currency_country_filter = check_currency_country_filters(
payout_filter,
request_payout_method_type,
payout.destination_currency,
address
.as_ref()
.and_then(|address| address.country)
.as_ref(),
)?;
if currency_country_filter.unwrap_or(true) {
match payment_method {
common_enums::PaymentMethod::Card => {
card_hash_set
.insert(request_payout_method_type.payment_method_type);
payment_method_list_hm
.insert(payment_method, card_hash_set.clone());
}
common_enums::PaymentMethod::Wallet => {
wallet_hash_set
.insert(request_payout_method_type.payment_method_type);
payment_method_list_hm
.insert(payment_method, wallet_hash_set.clone());
}
common_enums::PaymentMethod::BankTransfer => {
bank_transfer_hash_set
.insert(request_payout_method_type.payment_method_type);
payment_method_list_hm
.insert(payment_method, bank_transfer_hash_set.clone());
}
common_enums::PaymentMethod::BankRedirect => {
bank_redirect_hash_set
.insert(request_payout_method_type.payment_method_type);
payment_method_list_hm
.insert(payment_method, bank_redirect_hash_set.clone());
}
common_enums::PaymentMethod::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::OpenBanking
| common_enums::PaymentMethod::GiftCard
| common_enums::PaymentMethod::NetworkToken => continue,
}
}
}
}
}
}
for (payment_method, payment_method_types) in payment_method_list_hm {
if !payment_method_types.is_empty() {
let enabled_payment_method = link_utils::EnabledPaymentMethod {
payment_method,
payment_method_types,
};
response.push(enabled_payment_method);
}
}
Ok(response)
}
pub fn check_currency_country_filters(
payout_method_filter: Option<&PaymentMethodFilters>,
request_payout_method_type: &api_models::payment_methods::RequestPaymentMethodTypes,
currency: common_enums::Currency,
country: Option<&common_enums::CountryAlpha2>,
) -> errors::RouterResult<Option<bool>> {
if matches!(
request_payout_method_type.payment_method_type,
common_enums::PaymentMethodType::Credit | common_enums::PaymentMethodType::Debit
) {
Ok(Some(true))
} else {
let payout_method_type_filter =
payout_method_filter.and_then(|payout_method_filter: &PaymentMethodFilters| {
payout_method_filter
.0
.get(&PaymentMethodFilterKey::PaymentMethodType(
request_payout_method_type.payment_method_type,
))
});
let country_filter = country.as_ref().and_then(|country| {
payout_method_type_filter.and_then(|currency_country_filter| {
currency_country_filter
.country
.as_ref()
.map(|country_hash_set| country_hash_set.contains(country))
})
});
let currency_filter = payout_method_type_filter.and_then(|currency_country_filter| {
currency_country_filter
.currency
.as_ref()
.map(|currency_hash_set| currency_hash_set.contains(¤cy))
});
Ok(currency_filter.or(country_filter))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/poll.rs | crates/router/src/core/poll.rs | use api_models::poll::PollResponse;
use common_utils::ext_traits::StringExt;
use error_stack::ResultExt;
use router_env::{instrument, tracing};
use super::errors;
use crate::{
core::errors::RouterResponse, services::ApplicationResponse, types::domain, SessionState,
};
#[instrument(skip_all)]
pub async fn retrieve_poll_status(
state: SessionState,
req: crate::types::api::PollId,
platform: domain::Platform,
) -> RouterResponse<PollResponse> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let request_poll_id = req.poll_id;
// prepend 'poll_{merchant_id}_' to restrict access to only fetching Poll IDs, as this is a freely passed string in the request
let poll_id = super::utils::get_poll_id(
platform.get_processor().get_account().get_id(),
request_poll_id.clone(),
);
let redis_value = redis_conn
.get_key::<Option<String>>(&poll_id.as_str().into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Error while fetching the value for {} from redis",
poll_id.clone()
)
})?
.ok_or(errors::ApiErrorResponse::PollNotFound {
id: request_poll_id.clone(),
})?;
let status = redis_value
.parse_enum("PollStatus")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing PollStatus")?;
let poll_response = PollResponse {
poll_id: request_poll_id,
status,
};
Ok(ApplicationResponse::Json(poll_response))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/connector_validation.rs | crates/router/src/core/connector_validation.rs | use api_models::enums as api_enums;
use common_utils::pii;
use error_stack::ResultExt;
use external_services::http_client::client;
use masking::PeekInterface;
use pm_auth::connector::plaid::transformers::PlaidAuthType;
use crate::{core::errors, types, types::transformers::ForeignTryFrom};
pub struct ConnectorAuthTypeAndMetadataValidation<'a> {
pub connector_name: &'a api_models::enums::Connector,
pub auth_type: &'a types::ConnectorAuthType,
pub connector_meta_data: &'a Option<pii::SecretSerdeValue>,
}
impl ConnectorAuthTypeAndMetadataValidation<'_> {
pub fn validate_auth_and_metadata_type(
&self,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let connector_auth_type_validation = ConnectorAuthTypeValidation {
auth_type: self.auth_type,
};
connector_auth_type_validation.validate_connector_auth_type()?;
self.validate_auth_and_metadata_type_with_connector()
.map_err(|err| match *err.current_context() {
errors::ConnectorError::InvalidConnectorName => {
err.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "The connector name is invalid".to_string(),
})
}
errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!("The {field_name} is invalid"),
}),
errors::ConnectorError::FailedToObtainAuthType => {
err.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "The auth type is invalid for the connector".to_string(),
})
}
_ => err.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "The request body is invalid".to_string(),
}),
})
}
fn validate_auth_and_metadata_type_with_connector(
&self,
) -> Result<(), error_stack::Report<errors::ConnectorError>> {
use crate::connector::*;
match self.connector_name {
api_enums::Connector::Vgs => {
vgs::transformers::VgsAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Adyenplatform => {
adyenplatform::transformers::AdyenplatformAuthType::try_from(self.auth_type)?;
Ok(())
}
#[cfg(feature = "dummy_connector")]
api_enums::Connector::DummyBillingConnector
| api_enums::Connector::DummyConnector1
| api_enums::Connector::DummyConnector2
| api_enums::Connector::DummyConnector3
| api_enums::Connector::DummyConnector4
| api_enums::Connector::DummyConnector5
| api_enums::Connector::DummyConnector6
| api_enums::Connector::DummyConnector7 => {
hyperswitch_connectors::connectors::dummyconnector::transformers::DummyConnectorAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Aci => {
aci::transformers::AciAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Adyen => {
adyen::transformers::AdyenAuthType::try_from(self.auth_type)?;
adyen::transformers::AdyenConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Affirm => {
affirm::transformers::AffirmAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Airwallex => {
airwallex::transformers::AirwallexAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Amazonpay => {
amazonpay::transformers::AmazonpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Archipel => {
archipel::transformers::ArchipelAuthType::try_from(self.auth_type)?;
archipel::transformers::ArchipelConfigData::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Authipay => {
authipay::transformers::AuthipayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Authorizedotnet => {
authorizedotnet::transformers::AuthorizedotnetAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bankofamerica => {
bankofamerica::transformers::BankOfAmericaAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Barclaycard => {
barclaycard::transformers::BarclaycardAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Billwerk => {
billwerk::transformers::BillwerkAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bitpay => {
bitpay::transformers::BitpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_models::connector_enums::Connector::Zift => {
zift::transformers::ZiftAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bambora => {
bambora::transformers::BamboraAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bamboraapac => {
bamboraapac::transformers::BamboraapacAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Boku => {
boku::transformers::BokuAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Bluesnap => {
bluesnap::transformers::BluesnapAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Blackhawknetwork => {
blackhawknetwork::transformers::BlackhawknetworkAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Calida => {
calida::transformers::CalidaAuthType::try_from(self.auth_type)?;
calida::transformers::CalidaMetadataObject::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Braintree => {
braintree::transformers::BraintreeAuthType::try_from(self.auth_type)?;
braintree::transformers::BraintreeMeta::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Breadpay => {
breadpay::transformers::BreadpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Cardinal => Ok(()),
api_enums::Connector::Cashtocode => {
cashtocode::transformers::CashtocodeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Chargebee => {
chargebee::transformers::ChargebeeAuthType::try_from(self.auth_type)?;
chargebee::transformers::ChargebeeMetadata::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Celero => {
celero::transformers::CeleroAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Checkbook => {
checkbook::transformers::CheckbookAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Checkout => {
checkout::transformers::CheckoutAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Coinbase => {
coinbase::transformers::CoinbaseAuthType::try_from(self.auth_type)?;
coinbase::transformers::CoinbaseConnectorMeta::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Coingate => {
coingate::transformers::CoingateAuthType::try_from(self.auth_type)?;
coingate::transformers::CoingateConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Cryptopay => {
cryptopay::transformers::CryptopayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::CtpMastercard => Ok(()),
api_enums::Connector::Custombilling => Ok(()),
api_enums::Connector::CtpVisa => Ok(()),
api_enums::Connector::Cybersource => {
cybersource::transformers::CybersourceAuthType::try_from(self.auth_type)?;
cybersource::transformers::CybersourceConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Datatrans => {
datatrans::transformers::DatatransAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Deutschebank => {
deutschebank::transformers::DeutschebankAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Digitalvirgo => {
digitalvirgo::transformers::DigitalvirgoAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Dlocal => {
dlocal::transformers::DlocalAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Dwolla => {
dwolla::transformers::DwollaAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Ebanx => {
ebanx::transformers::EbanxAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Elavon => {
elavon::transformers::ElavonAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Facilitapay => {
facilitapay::transformers::FacilitapayAuthType::try_from(self.auth_type)?;
facilitapay::transformers::FacilitapayConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Fiserv => {
fiserv::transformers::FiservAuthType::try_from(self.auth_type)?;
fiserv::transformers::FiservSessionObject::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Fiservemea => {
fiservemea::transformers::FiservemeaAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Fiuu => {
fiuu::transformers::FiuuAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Flexiti => {
flexiti::transformers::FlexitiAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Forte => {
forte::transformers::ForteAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Getnet => {
getnet::transformers::GetnetAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Gigadat => {
gigadat::transformers::GigadatAuthType::try_from(self.auth_type)?;
gigadat::transformers::GigadatConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Globalpay => {
globalpay::transformers::GlobalpayAuthType::try_from(self.auth_type)?;
globalpay::transformers::GlobalPayMeta::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Globepay => {
globepay::transformers::GlobepayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Gocardless => {
gocardless::transformers::GocardlessAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Gpayments => {
gpayments::transformers::GpaymentsAuthType::try_from(self.auth_type)?;
gpayments::transformers::GpaymentsMetaData::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Hipay => {
hipay::transformers::HipayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Helcim => {
helcim::transformers::HelcimAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::HyperswitchVault => {
hyperswitch_vault::transformers::HyperswitchVaultAuthType::try_from(
self.auth_type,
)?;
Ok(())
}
api_enums::Connector::Iatapay => {
iatapay::transformers::IatapayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Inespay => {
inespay::transformers::InespayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Itaubank => {
itaubank::transformers::ItaubankAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Jpmorgan => {
jpmorgan::transformers::JpmorganAuthType::try_from(self.auth_type)?;
jpmorgan::transformers::JpmorganConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Juspaythreedsserver => Ok(()),
api_enums::Connector::Klarna => {
klarna::transformers::KlarnaAuthType::try_from(self.auth_type)?;
klarna::transformers::KlarnaConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Loonio => {
loonio::transformers::LoonioAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Mifinity => {
mifinity::transformers::MifinityAuthType::try_from(self.auth_type)?;
mifinity::transformers::MifinityConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Mollie => {
mollie::transformers::MollieAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Moneris => {
moneris::transformers::MonerisAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Multisafepay => {
multisafepay::transformers::MultisafepayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Netcetera => {
netcetera::transformers::NetceteraAuthType::try_from(self.auth_type)?;
netcetera::transformers::NetceteraMetaData::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Nexinets => {
nexinets::transformers::NexinetsAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nexixpay => {
nexixpay::transformers::NexixpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nmi => {
nmi::transformers::NmiAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nomupay => {
nomupay::transformers::NomupayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Noon => {
noon::transformers::NoonAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nordea => {
nordea::transformers::NordeaAuthType::try_from(self.auth_type)?;
nordea::transformers::NordeaConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Novalnet => {
novalnet::transformers::NovalnetAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Nuvei => {
nuvei::transformers::NuveiAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Opennode => {
opennode::transformers::OpennodeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paybox => {
paybox::transformers::PayboxAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Payload => {
payload::transformers::PayloadAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Payjustnow => {
payjustnow::transformers::PayjustnowAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Payjustnowinstore => {
payjustnowinstore::transformers::PayjustnowinstoreAuthType::try_from(
self.auth_type,
)?;
Ok(())
}
api_enums::Connector::Payme => {
payme::transformers::PaymeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paypal => {
paypal::transformers::PaypalAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paysafe => {
paysafe::transformers::PaysafeAuthType::try_from(self.auth_type)?;
paysafe::transformers::PaysafeConnectorMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Payone => {
payone::transformers::PayoneAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paystack => {
paystack::transformers::PaystackAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Payu => {
payu::transformers::PayuAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Peachpayments => {
peachpayments::transformers::PeachpaymentsAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Placetopay => {
placetopay::transformers::PlacetopayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Powertranz => {
powertranz::transformers::PowertranzAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Prophetpay => {
prophetpay::transformers::ProphetpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Rapyd => {
rapyd::transformers::RapydAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Razorpay => {
razorpay::transformers::RazorpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Recurly => {
recurly::transformers::RecurlyAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Redsys => {
redsys::transformers::RedsysAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Santander => {
santander::transformers::SantanderAuthType::try_from(self.auth_type)?;
santander::transformers::SantanderMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Shift4 => {
shift4::transformers::Shift4AuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Silverflow => {
silverflow::transformers::SilverflowAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Square => {
square::transformers::SquareAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Stax => {
stax::transformers::StaxAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Taxjar => {
taxjar::transformers::TaxjarAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Stripe => {
stripe::transformers::StripeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Stripebilling => {
stripebilling::transformers::StripebillingAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Tesouro => {
tesouro::transformers::TesouroAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Trustpay => {
trustpay::transformers::TrustpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Trustpayments => {
trustpayments::transformers::TrustpaymentsAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Tokenex => {
tokenex::transformers::TokenexAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Tokenio => {
tokenio::transformers::TokenioAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Tsys => {
tsys::transformers::TsysAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Volt => {
volt::transformers::VoltAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Wellsfargo => {
wellsfargo::transformers::WellsfargoAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Wise => {
wise::transformers::WiseAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Worldline => {
worldline::transformers::WorldlineAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Worldpay => {
worldpay::transformers::WorldpayAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Worldpayvantiv => {
worldpayvantiv::transformers::WorldpayvantivAuthType::try_from(self.auth_type)?;
worldpayvantiv::transformers::WorldpayvantivMetadataObject::try_from(
self.connector_meta_data,
)?;
Ok(())
}
api_enums::Connector::Worldpayxml => {
worldpayxml::transformers::WorldpayxmlAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Xendit => {
xendit::transformers::XenditAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Zen => {
zen::transformers::ZenAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Zsl => {
zsl::transformers::ZslAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Signifyd => {
signifyd::transformers::SignifydAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Riskified => {
riskified::transformers::RiskifiedAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Plaid => {
PlaidAuthType::foreign_try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Threedsecureio => {
threedsecureio::transformers::ThreedsecureioAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Phonepe => {
phonepe::transformers::PhonepeAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Paytm => {
paytm::transformers::PaytmAuthType::try_from(self.auth_type)?;
Ok(())
}
api_enums::Connector::Finix => {
finix::transformers::FinixAuthType::try_from(self.auth_type)?;
Ok(())
}
}
}
}
struct ConnectorAuthTypeValidation<'a> {
auth_type: &'a types::ConnectorAuthType,
}
impl ConnectorAuthTypeValidation<'_> {
fn validate_connector_auth_type(
&self,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let validate_non_empty_field = |field_value: &str, field_name: &str| {
if field_value.trim().is_empty() {
Err(errors::ApiErrorResponse::InvalidDataFormat {
field_name: format!("connector_account_details.{field_name}"),
expected_format: "a non empty String".to_string(),
}
.into())
} else {
Ok(())
}
};
match self.auth_type {
hyperswitch_domain_models::router_data::ConnectorAuthType::TemporaryAuth => Ok(()),
hyperswitch_domain_models::router_data::ConnectorAuthType::HeaderKey { api_key } => {
validate_non_empty_field(api_key.peek(), "api_key")
}
hyperswitch_domain_models::router_data::ConnectorAuthType::BodyKey {
api_key,
key1,
} => {
validate_non_empty_field(api_key.peek(), "api_key")?;
validate_non_empty_field(key1.peek(), "key1")
}
hyperswitch_domain_models::router_data::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => {
validate_non_empty_field(api_key.peek(), "api_key")?;
validate_non_empty_field(key1.peek(), "key1")?;
validate_non_empty_field(api_secret.peek(), "api_secret")
}
hyperswitch_domain_models::router_data::ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => {
validate_non_empty_field(api_key.peek(), "api_key")?;
validate_non_empty_field(key1.peek(), "key1")?;
validate_non_empty_field(api_secret.peek(), "api_secret")?;
validate_non_empty_field(key2.peek(), "key2")
}
hyperswitch_domain_models::router_data::ConnectorAuthType::CurrencyAuthKey {
auth_key_map,
} => {
if auth_key_map.is_empty() {
Err(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_account_details.auth_key_map".to_string(),
expected_format: "a non empty map".to_string(),
}
.into())
} else {
Ok(())
}
}
hyperswitch_domain_models::router_data::ConnectorAuthType::CertificateAuth {
certificate,
private_key,
} => {
client::create_identity_from_certificate_and_key(
certificate.to_owned(),
private_key.to_owned(),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name:
"connector_account_details.certificate or connector_account_details.private_key"
.to_string(),
expected_format:
"a valid base64 encoded string of PEM encoded Certificate and Private Key"
.to_string(),
})?;
Ok(())
}
hyperswitch_domain_models::router_data::ConnectorAuthType::NoKey => Ok(()),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/disputes.rs | crates/router/src/core/disputes.rs | use std::{collections::HashMap, ops::Deref, str::FromStr};
use api_models::{
admin::MerchantConnectorInfo, disputes as dispute_models, files as files_api_models,
};
use common_utils::ext_traits::{Encode, ValueExt};
use error_stack::ResultExt;
use router_env::{
instrument, logger,
tracing::{self, Instrument},
};
use strum::IntoEnumIterator;
pub mod transformers;
use common_enums;
use super::{
errors::{self, ConnectorErrorExt, RouterResponse, StorageErrorExt},
metrics,
};
use crate::{
core::{files, payments, utils as core_utils, webhooks},
routes::{app::StorageInterface, metrics::TASKS_ADDED_COUNT, SessionState},
services,
types::{
api::{self, disputes},
domain,
storage::enums as storage_enums,
transformers::{ForeignFrom, ForeignInto},
AcceptDisputeRequestData, AcceptDisputeResponse, DefendDisputeRequestData,
DefendDisputeResponse, DisputePayload, DisputeSyncData, DisputeSyncResponse,
FetchDisputesRequestData, FetchDisputesResponse, SubmitEvidenceRequestData,
SubmitEvidenceResponse,
},
workflows::process_dispute,
};
pub(crate) fn should_call_connector_for_dispute_sync(
force_sync: Option<bool>,
dispute_status: storage_enums::DisputeStatus,
) -> bool {
force_sync == Some(true)
&& matches!(
dispute_status,
common_enums::DisputeStatus::DisputeAccepted
| common_enums::DisputeStatus::DisputeChallenged
| common_enums::DisputeStatus::DisputeOpened
)
}
#[instrument(skip(state))]
pub async fn retrieve_dispute(
state: SessionState,
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
req: dispute_models::DisputeRetrieveRequest,
) -> RouterResponse<api_models::disputes::DisputeResponse> {
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
platform.get_processor().get_account().get_id(),
&req.dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id,
})?;
core_utils::validate_profile_id_from_auth_layer(profile_id.clone(), &dispute)?;
#[cfg(feature = "v1")]
let dispute_response =
if should_call_connector_for_dispute_sync(req.force_sync, dispute.dispute_status) {
let db = &state.store;
core_utils::validate_profile_id_from_auth_layer(profile_id.clone(), &dispute)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&dispute.payment_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
dispute.merchant_connector_id.clone(),
)?;
let connector_integration: services::BoxedDisputeConnectorIntegrationInterface<
api::Dsync,
DisputeSyncData,
DisputeSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data = core_utils::construct_dispute_sync_router_data(
&state,
&payment_intent,
&payment_attempt,
&platform,
&dispute,
)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_dispute_failed_response()
.attach_printable("Failed while calling accept dispute connector api")?;
let dispute_sync_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: dispute.connector.clone(),
status_code: err.status_code,
reason: err.reason,
}
})?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
platform.get_processor().get_key_store(),
&payment_attempt.profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: payment_attempt.profile_id.get_string_repr().to_owned(),
})?;
update_dispute_data(
&state,
platform,
business_profile,
Some(dispute.clone()),
dispute_sync_response,
payment_attempt,
dispute.connector.as_str(),
)
.await
.attach_printable("Dispute update failed")?
} else {
api_models::disputes::DisputeResponse::foreign_from(dispute)
};
#[cfg(not(feature = "v1"))]
let dispute_response = api_models::disputes::DisputeResponse::foreign_from(dispute);
Ok(services::ApplicationResponse::Json(dispute_response))
}
#[instrument(skip(state))]
pub async fn retrieve_disputes_list(
state: SessionState,
platform: domain::Platform,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
constraints: api_models::disputes::DisputeListGetConstraints,
) -> RouterResponse<Vec<api_models::disputes::DisputeResponse>> {
let dispute_list_constraints = &(constraints.clone(), profile_id_list.clone()).try_into()?;
let disputes = state
.store
.find_disputes_by_constraints(
platform.get_processor().get_account().get_id(),
dispute_list_constraints,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to retrieve disputes")?;
let disputes_list = disputes
.into_iter()
.map(api_models::disputes::DisputeResponse::foreign_from)
.collect();
Ok(services::ApplicationResponse::Json(disputes_list))
}
#[cfg(feature = "v2")]
#[instrument(skip(state))]
pub async fn accept_dispute(
state: SessionState,
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
req: disputes::DisputeId,
) -> RouterResponse<dispute_models::DisputeResponse> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn get_filters_for_disputes(
state: SessionState,
platform: domain::Platform,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
) -> RouterResponse<api_models::disputes::DisputeListFilters> {
let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
super::admin::list_payment_connectors(
state,
platform.get_processor().clone(),
profile_id_list,
)
.await?
{
data
} else {
return Err(error_stack::report!(
errors::ApiErrorResponse::InternalServerError
))
.attach_printable(
"Failed to retrieve merchant connector accounts while fetching dispute list filters.",
);
};
let connector_map = merchant_connector_accounts
.into_iter()
.filter_map(|merchant_connector_account| {
merchant_connector_account
.connector_label
.clone()
.map(|label| {
let info = merchant_connector_account.to_merchant_connector_info(&label);
(merchant_connector_account.connector_name, info)
})
})
.fold(
HashMap::new(),
|mut map: HashMap<String, Vec<MerchantConnectorInfo>>, (connector_name, info)| {
map.entry(connector_name).or_default().push(info);
map
},
);
Ok(services::ApplicationResponse::Json(
api_models::disputes::DisputeListFilters {
connector: connector_map,
currency: storage_enums::Currency::iter().collect(),
dispute_status: storage_enums::DisputeStatus::iter().collect(),
dispute_stage: storage_enums::DisputeStage::iter().collect(),
},
))
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn accept_dispute(
state: SessionState,
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
req: disputes::DisputeId,
) -> RouterResponse<dispute_models::DisputeResponse> {
let db = &state.store;
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
platform.get_processor().get_account().get_id(),
&req.dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id,
})?;
core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?;
let dispute_id = dispute.dispute_id.clone();
common_utils::fp_utils::when(
!core_utils::should_proceed_with_accept_dispute(
dispute.dispute_stage,
dispute.dispute_status,
),
|| {
metrics::ACCEPT_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]);
Err(errors::ApiErrorResponse::DisputeStatusValidationFailed {
reason: format!(
"This dispute cannot be accepted because the dispute is in {} stage and has {} status",
dispute.dispute_stage, dispute.dispute_status
),
})
},
)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&dispute.payment_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
dispute.merchant_connector_id.clone(),
)?;
let connector_integration: services::BoxedDisputeConnectorIntegrationInterface<
api::Accept,
AcceptDisputeRequestData,
AcceptDisputeResponse,
> = connector_data.connector.get_connector_integration();
let router_data = core_utils::construct_accept_dispute_router_data(
&state,
&payment_intent,
&payment_attempt,
&platform,
&dispute,
)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_dispute_failed_response()
.attach_printable("Failed while calling accept dispute connector api")?;
let accept_dispute_response =
response
.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: dispute.connector.clone(),
status_code: err.status_code,
reason: err.reason,
})?;
let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate {
dispute_status: accept_dispute_response.dispute_status,
connector_status: accept_dispute_response.connector_status.clone(),
};
let updated_dispute = db
.update_dispute(dispute.clone(), update_dispute)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("Unable to update dispute with dispute_id: {dispute_id}")
})?;
let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute);
Ok(services::ApplicationResponse::Json(dispute_response))
}
#[cfg(feature = "v2")]
#[instrument(skip(state))]
pub async fn submit_evidence(
state: SessionState,
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
req: dispute_models::SubmitEvidenceRequest,
) -> RouterResponse<dispute_models::DisputeResponse> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn submit_evidence(
state: SessionState,
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
req: dispute_models::SubmitEvidenceRequest,
) -> RouterResponse<dispute_models::DisputeResponse> {
let db = &state.store;
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
platform.get_processor().get_account().get_id(),
&req.dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id.clone(),
})?;
core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?;
let dispute_id = dispute.dispute_id.clone();
common_utils::fp_utils::when(
!core_utils::should_proceed_with_submit_evidence(
dispute.dispute_stage,
dispute.dispute_status,
),
|| {
metrics::EVIDENCE_SUBMISSION_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]);
Err(errors::ApiErrorResponse::DisputeStatusValidationFailed {
reason: format!(
"Evidence cannot be submitted because the dispute is in {} stage and has {} status",
dispute.dispute_stage, dispute.dispute_status
),
})
},
)?;
let submit_evidence_request_data =
transformers::get_evidence_request_data(&state, &platform, req, &dispute).await?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&dispute.payment_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
dispute.merchant_connector_id.clone(),
)?;
let connector_integration: services::BoxedDisputeConnectorIntegrationInterface<
api::Evidence,
SubmitEvidenceRequestData,
SubmitEvidenceResponse,
> = connector_data.connector.get_connector_integration();
let router_data = core_utils::construct_submit_evidence_router_data(
&state,
&payment_intent,
&payment_attempt,
&platform,
&dispute,
submit_evidence_request_data,
)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_dispute_failed_response()
.attach_printable("Failed while calling submit evidence connector api")?;
let submit_evidence_response =
response
.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: dispute.connector.clone(),
status_code: err.status_code,
reason: err.reason,
})?;
//Defend Dispute Optionally if connector expects to defend / submit evidence in a separate api call
let (dispute_status, connector_status) = if connector_data
.connector_name
.requires_defend_dispute()
{
let connector_integration_defend_dispute: services::BoxedDisputeConnectorIntegrationInterface<
api::Defend,
DefendDisputeRequestData,
DefendDisputeResponse,
> = connector_data.connector.get_connector_integration();
let defend_dispute_router_data = core_utils::construct_defend_dispute_router_data(
&state,
&payment_intent,
&payment_attempt,
&platform,
&dispute,
)
.await?;
let defend_response = services::execute_connector_processing_step(
&state,
connector_integration_defend_dispute,
&defend_dispute_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_dispute_failed_response()
.attach_printable("Failed while calling defend dispute connector api")?;
let defend_dispute_response = defend_response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: dispute.connector.clone(),
status_code: err.status_code,
reason: err.reason,
}
})?;
(
defend_dispute_response.dispute_status,
defend_dispute_response.connector_status,
)
} else {
(
submit_evidence_response.dispute_status,
submit_evidence_response.connector_status,
)
};
let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate {
dispute_status,
connector_status,
};
let updated_dispute = db
.update_dispute(dispute.clone(), update_dispute)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.to_owned(),
})
.attach_printable_lazy(|| {
format!("Unable to update dispute with dispute_id: {dispute_id}")
})?;
let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute);
Ok(services::ApplicationResponse::Json(dispute_response))
}
pub async fn attach_evidence(
state: SessionState,
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
attach_evidence_request: api::AttachEvidenceRequest,
) -> RouterResponse<files_api_models::CreateFileResponse> {
let db = &state.store;
let dispute_id = attach_evidence_request
.create_file_request
.dispute_id
.clone()
.ok_or(errors::ApiErrorResponse::MissingDisputeId)?;
let dispute = db
.find_dispute_by_merchant_id_dispute_id(
platform.get_processor().get_account().get_id(),
&dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.clone(),
})?;
core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?;
common_utils::fp_utils::when(
!(dispute.dispute_stage == storage_enums::DisputeStage::Dispute
&& dispute.dispute_status == storage_enums::DisputeStatus::DisputeOpened),
|| {
metrics::ATTACH_EVIDENCE_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]);
Err(errors::ApiErrorResponse::DisputeStatusValidationFailed {
reason: format!(
"Evidence cannot be attached because the dispute is in {} stage and has {} status",
dispute.dispute_stage, dispute.dispute_status
),
})
},
)?;
let create_file_response = Box::pin(files::files_create_core(
state.clone(),
platform,
attach_evidence_request.create_file_request,
))
.await?;
let file_id = match &create_file_response {
services::ApplicationResponse::Json(res) => res.file_id.clone(),
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response received from files create core")?,
};
let dispute_evidence: api::DisputeEvidence = dispute
.evidence
.clone()
.parse_value("DisputeEvidence")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing dispute evidence record")?;
let updated_dispute_evidence = transformers::update_dispute_evidence(
dispute_evidence,
attach_evidence_request.evidence_type,
file_id,
);
let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate {
evidence: updated_dispute_evidence
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while encoding dispute evidence")?
.into(),
};
db.update_dispute(dispute, update_dispute)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.to_owned(),
})
.attach_printable_lazy(|| {
format!("Unable to update dispute with dispute_id: {dispute_id}")
})?;
Ok(create_file_response)
}
#[instrument(skip(state))]
pub async fn retrieve_dispute_evidence(
state: SessionState,
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
req: disputes::DisputeId,
) -> RouterResponse<Vec<api_models::disputes::DisputeEvidenceBlock>> {
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
platform.get_processor().get_account().get_id(),
&req.dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id,
})?;
core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?;
let dispute_evidence: api::DisputeEvidence = dispute
.evidence
.clone()
.parse_value("DisputeEvidence")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing dispute evidence record")?;
let dispute_evidence_vec =
transformers::get_dispute_evidence_vec(&state, platform, dispute_evidence).await?;
Ok(services::ApplicationResponse::Json(dispute_evidence_vec))
}
pub async fn delete_evidence(
state: SessionState,
platform: domain::Platform,
delete_evidence_request: dispute_models::DeleteEvidenceRequest,
) -> RouterResponse<serde_json::Value> {
let dispute_id = delete_evidence_request.dispute_id.clone();
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
platform.get_processor().get_account().get_id(),
&dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.clone(),
})?;
let dispute_evidence: api::DisputeEvidence = dispute
.evidence
.clone()
.parse_value("DisputeEvidence")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing dispute evidence record")?;
let updated_dispute_evidence =
transformers::delete_evidence_file(dispute_evidence, delete_evidence_request.evidence_type);
let update_dispute = diesel_models::dispute::DisputeUpdate::EvidenceUpdate {
evidence: updated_dispute_evidence
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while encoding dispute evidence")?
.into(),
};
state
.store
.update_dispute(dispute, update_dispute)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.to_owned(),
})
.attach_printable_lazy(|| {
format!("Unable to update dispute with dispute_id: {dispute_id}")
})?;
Ok(services::ApplicationResponse::StatusOk)
}
#[instrument(skip(state))]
pub async fn get_aggregates_for_disputes(
state: SessionState,
platform: domain::Platform,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: common_utils::types::TimeRange,
) -> RouterResponse<dispute_models::DisputesAggregateResponse> {
let db = state.store.as_ref();
let dispute_status_with_count = db
.get_dispute_status_with_count(
platform.get_processor().get_account().get_id(),
profile_id_list,
&time_range,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to retrieve disputes aggregate")?;
let mut status_map: HashMap<storage_enums::DisputeStatus, i64> =
dispute_status_with_count.into_iter().collect();
for status in storage_enums::DisputeStatus::iter() {
status_map.entry(status).or_default();
}
Ok(services::ApplicationResponse::Json(
dispute_models::DisputesAggregateResponse {
status_with_count: status_map,
},
))
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn connector_sync_disputes(
state: SessionState,
platform: domain::Platform,
merchant_connector_id: String,
payload: disputes::DisputeFetchQueryData,
) -> RouterResponse<FetchDisputesResponse> {
let connector_id =
common_utils::id_type::MerchantConnectorAccountId::wrap(merchant_connector_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse merchant connector account id format")?;
let format = time::format_description::parse("[year]-[month]-[day]T[hour]:[minute]:[second]")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse the date-time format")?;
let created_from = time::PrimitiveDateTime::parse(&payload.fetch_from, &format)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "fetch_from".to_string(),
expected_format: "YYYY-MM-DDTHH:MM:SS".to_string(),
})?;
let created_till = time::PrimitiveDateTime::parse(&payload.fetch_till, &format)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "fetch_till".to_string(),
expected_format: "YYYY-MM-DDTHH:MM:SS".to_string(),
})?;
let fetch_dispute_request = FetchDisputesRequestData {
created_from,
created_till,
};
Box::pin(fetch_disputes_from_connector(
state,
platform,
connector_id,
fetch_dispute_request,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn fetch_disputes_from_connector(
state: SessionState,
platform: domain::Platform,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
req: FetchDisputesRequestData,
) -> RouterResponse<FetchDisputesResponse> {
let db = &*state.store;
let merchant_id = platform.get_processor().get_account().get_id();
let merchant_connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
merchant_id,
&merchant_connector_id,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
})?;
let connector_name = merchant_connector_account.connector_name.clone();
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
Some(merchant_connector_id.clone()),
)?;
let connector_integration: services::BoxedDisputeConnectorIntegrationInterface<
api::Fetch,
FetchDisputesRequestData,
FetchDisputesResponse,
> = connector_data.connector.get_connector_integration();
let router_data =
core_utils::construct_dispute_list_router_data(&state, merchant_connector_account, req)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_dispute_failed_response()
.attach_printable("Failed while calling accept dispute connector api")?;
let fetch_dispute_response =
response
.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_name.clone(),
status_code: err.status_code,
reason: err.reason,
})?;
for dispute in &fetch_dispute_response {
// check if payment already exist
let payment_attempt = webhooks::incoming::get_payment_attempt_from_object_reference_id(
&state,
dispute.object_reference_id.clone(),
&platform,
)
.await;
if payment_attempt.is_ok() {
let schedule_time = process_dispute::get_sync_process_schedule_time(
&*state.store,
&connector_name,
merchant_id,
0,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting process schedule time")?;
let response = add_process_dispute_task_to_pt(
db,
&connector_name,
dispute,
merchant_id.clone(),
schedule_time,
state.conf.application_source,
)
.await;
match response {
Err(report)
if report
.downcast_ref::<errors::StorageError>()
.is_some_and(|error| {
matches!(error, errors::StorageError::DuplicateValue { .. })
}) =>
{
Ok(())
}
Ok(_) => Ok(()),
Err(_) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while adding task to process tracker"),
}?;
} else {
router_env::logger::info!("Disputed payment does not exist in our records");
}
}
Ok(services::ApplicationResponse::Json(fetch_dispute_response))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn update_dispute_data(
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/revenue_recovery.rs | crates/router/src/core/revenue_recovery.rs | pub mod api;
pub mod transformers;
pub mod types;
use std::marker::PhantomData;
use api_models::{
enums,
payments::{
self as api_payments, PaymentsGetIntentRequest, PaymentsResponse,
RecoveryPaymentsListResponseItem,
},
process_tracker::revenue_recovery,
webhooks,
};
use common_enums::enums::{IntentStatus, RecoveryStatus};
use common_utils::{
self,
errors::CustomResult,
ext_traits::{AsyncExt, OptionExt, ValueExt},
id_type,
id_type::GlobalPaymentId,
};
use diesel_models::{enums as diesel_enum, process_tracker::business_status};
use error_stack::{self, report, ResultExt};
use hyperswitch_domain_models::{
payments::{PaymentIntent, PaymentIntentData, PaymentStatusData},
platform, revenue_recovery as domain_revenue_recovery, ApiModelToDieselModelConvertor,
};
use scheduler::errors as sch_errors;
use crate::{
core::{
errors::{self, RouterResponse, RouterResult, StorageErrorExt},
payments::{
self,
operations::{GetTrackerResponse, Operation},
transformers::GenerateResponse,
},
revenue_recovery::types::{
reopen_calculate_workflow_on_payment_failure, RevenueRecoveryOutgoingWebhook,
},
revenue_recovery_data_backfill::unlock_connector_customer_status_handler,
},
db::StorageInterface,
logger,
routes::{app::ReqState, metrics, SessionState},
services::ApplicationResponse,
types::{
api as router_api_types, domain,
storage::{
self, revenue_recovery as pcr, PaymentAttempt, ProcessTracker as ProcessTrackerStorage,
},
transformers::{ForeignFrom, ForeignInto},
},
workflows::revenue_recovery as revenue_recovery_workflow,
};
pub const CALCULATE_WORKFLOW: &str = "CALCULATE_WORKFLOW";
pub const PSYNC_WORKFLOW: &str = "PSYNC_WORKFLOW";
pub const EXECUTE_WORKFLOW: &str = "EXECUTE_WORKFLOW";
use common_enums::enums::ProcessTrackerStatus;
#[cfg(feature = "v1")]
use crate::types::common_enums;
#[allow(clippy::too_many_arguments)]
pub async fn upsert_calculate_pcr_task(
billing_connector_account: &domain::MerchantConnectorAccount,
state: &SessionState,
platform: &domain::Platform,
recovery_intent_from_payment_intent: &domain_revenue_recovery::RecoveryPaymentIntent,
business_profile: &domain::Profile,
intent_retry_count: u16,
payment_attempt_id: Option<id_type::GlobalAttemptId>,
runner: storage::ProcessTrackerRunner,
revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
router_env::logger::info!("Starting calculate_job...");
let task = "CALCULATE_WORKFLOW";
let db = &*state.store;
let payment_id = &recovery_intent_from_payment_intent.payment_id;
// Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id}
let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr());
// Scheduled time is now because this will be the first entry in
// process tracker and we dont want to wait
let schedule_time = common_utils::date_time::now();
let payment_attempt_id = payment_attempt_id
.ok_or(error_stack::report!(
errors::RevenueRecoveryError::PaymentAttemptIdNotFound
))
.attach_printable("payment attempt id is required for calculate workflow tracking")?;
// Check if a process tracker entry already exists for this payment intent
let existing_entry = db
.as_scheduler()
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError)
.attach_printable(
"Failed to check for existing calculate workflow process tracker entry",
)?;
match existing_entry {
Some(existing_process) => {
router_env::logger::error!(
"Found existing CALCULATE_WORKFLOW task with id: {}",
existing_process.id
);
}
None => {
// No entry exists - create a new one
router_env::logger::info!(
"No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry scheduled for 1 hour from now",
payment_id.get_string_repr()
);
// Create tracking data
let calculate_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
billing_mca_id: billing_connector_account.get_id(),
global_payment_id: payment_id.clone(),
merchant_id: platform.get_processor().get_account().get_id().to_owned(),
profile_id: business_profile.get_id().to_owned(),
payment_attempt_id,
revenue_recovery_retry,
invoice_scheduled_time: None,
};
let tag = ["PCR"];
let task = "CALCULATE_WORKFLOW";
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
calculate_workflow_tracking_data,
Some(1),
schedule_time,
common_types::consts::API_VERSION,
state.conf.application_source,
)
.change_context(errors::RevenueRecoveryError::ProcessTrackerCreationError)
.attach_printable("Failed to construct calculate workflow process tracker entry")?;
// Insert into process tracker with status New
db.as_scheduler()
.insert_process(process_tracker_entry)
.await
.change_context(errors::RevenueRecoveryError::ProcessTrackerResponseError)
.attach_printable(
"Failed to enter calculate workflow process_tracker_entry in DB",
)?;
router_env::logger::info!(
"Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}",
payment_id.get_string_repr()
);
metrics::TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", "CalculateWorkflow")),
);
}
}
Ok(webhooks::WebhookResponseTracker::Payment {
payment_id: payment_id.clone(),
status: recovery_intent_from_payment_intent.status,
})
}
#[allow(clippy::too_many_arguments)]
pub async fn record_internal_attempt_and_execute_payment(
state: &SessionState,
execute_task_process: &storage::ProcessTracker,
profile: &domain::Profile,
platform: domain::Platform,
tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,
revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
payment_intent: &PaymentIntent,
payment_processor_token: &storage::revenue_recovery_redis_operation::PaymentProcessorTokenStatus,
revenue_recovery_metadata: &mut api_models::payments::PaymentRevenueRecoveryMetadata,
) -> Result<(), sch_errors::ProcessTrackerError> {
let db = &*state.store;
let card_info = api_models::payments::AdditionalCardInfo::foreign_from(payment_processor_token);
// record attempt call
let record_attempt = api::record_internal_attempt_api(
state,
payment_intent,
revenue_recovery_payment_data,
revenue_recovery_metadata,
card_info,
&payment_processor_token
.payment_processor_token_details
.payment_processor_token,
)
.await;
match record_attempt {
Ok(record_attempt_response) => {
let action = Box::pin(types::Action::execute_payment(
state,
revenue_recovery_payment_data.merchant_account.get_id(),
payment_intent,
execute_task_process,
profile,
platform,
revenue_recovery_payment_data,
revenue_recovery_metadata,
&record_attempt_response.id,
payment_processor_token,
))
.await?;
Box::pin(action.execute_payment_task_response_handler(
state,
payment_intent,
execute_task_process,
revenue_recovery_payment_data,
revenue_recovery_metadata,
))
.await?;
}
Err(err) => {
logger::error!("Error while recording attempt: {:?}", err);
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: ProcessTrackerStatus::Pending,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_REQUEUE)),
};
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
}
}
Ok(())
}
pub async fn perform_execute_payment(
state: &SessionState,
execute_task_process: &storage::ProcessTracker,
profile: &domain::Profile,
platform: domain::Platform,
tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,
revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
payment_intent: &PaymentIntent,
) -> Result<(), sch_errors::ProcessTrackerError> {
let db = &*state.store;
let mut revenue_recovery_metadata = payment_intent
.feature_metadata
.as_ref()
.and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())
.get_required_value("Payment Revenue Recovery Metadata")?
.convert_back();
let decision = types::Decision::get_decision_based_on_params(
state,
payment_intent.status,
revenue_recovery_metadata
.payment_connector_transmission
.unwrap_or_default(),
payment_intent.active_attempt_id.as_ref(),
revenue_recovery_payment_data,
&tracking_data.global_payment_id,
)
.await?;
// TODO decide if its a global failure or is it requeueable error
match decision {
types::Decision::Execute => {
let connector_customer_id = revenue_recovery_metadata.get_connector_customer_id();
let last_token_used = payment_intent
.feature_metadata
.as_ref()
.and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())
.map(|rr| {
rr.billing_connector_payment_details
.payment_processor_token
.clone()
});
let processor_token = storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(
state,
&connector_customer_id,
tracking_data.revenue_recovery_retry,
last_token_used.as_deref(),
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Failed to fetch token details from redis".to_string(),
})?;
match processor_token {
None => {
logger::info!("No Token fetched from redis");
// Close the job if there is no token available
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_FAILURE,
)
.await?;
Box::pin(reopen_calculate_workflow_on_payment_failure(
state,
execute_task_process,
profile,
platform,
payment_intent,
revenue_recovery_payment_data,
&tracking_data.payment_attempt_id,
))
.await?;
// Unlock the customer status only if all tokens are hard declined and payment intent is in Failed status
let _unlocked = match payment_intent.status {
IntentStatus::Failed => {
storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
&payment_intent.id,
)
.await?
}
_ => false,
};
}
Some(payment_processor_token) => {
logger::info!("Token fetched from redis success");
record_internal_attempt_and_execute_payment(
state,
execute_task_process,
profile,
platform,
tracking_data,
revenue_recovery_payment_data,
payment_intent,
&payment_processor_token,
&mut revenue_recovery_metadata,
)
.await?;
}
};
}
types::Decision::Psync(intent_status, attempt_id) => {
// find if a psync task is already present
let task = PSYNC_WORKFLOW;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_id = attempt_id.get_psync_revenue_recovery_id(task, runner);
let psync_process = db.find_process_by_id(&process_tracker_id).await?;
match psync_process {
Some(_) => {
let pcr_status: types::RevenueRecoveryPaymentIntentStatus =
intent_status.foreign_into();
pcr_status
.update_pt_status_based_on_intent_status_for_execute_payment(
db,
execute_task_process,
)
.await?;
}
None => {
// insert new psync task
insert_psync_pcr_task_to_pt(
revenue_recovery_payment_data.billing_mca.get_id().clone(),
db,
revenue_recovery_payment_data
.merchant_account
.get_id()
.clone(),
payment_intent.get_id().clone(),
revenue_recovery_payment_data.profile.get_id().clone(),
attempt_id.clone(),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
tracking_data.revenue_recovery_retry,
state.conf.application_source,
)
.await?;
// finish the current task
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
)
.await?;
}
};
}
types::Decision::ReviewForSuccessfulPayment => {
// Finish the current task since the payment was a success
// And mark it as review as it might have happened through the external system
db.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW,
)
.await?;
}
types::Decision::ReviewForFailedPayment(triggered_by) => {
match triggered_by {
enums::TriggeredBy::Internal => {
// requeue the current tasks to update the fields for rescheduling a payment
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: ProcessTrackerStatus::Pending,
business_status: Some(String::from(
business_status::EXECUTE_WORKFLOW_REQUEUE,
)),
};
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
}
enums::TriggeredBy::External => {
logger::debug!("Failed Payment Attempt Triggered By External");
// Finish the current task since the payment was a failure by an external source
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW,
)
.await?;
}
};
}
types::Decision::InvalidDecision => {
db.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE,
)
.await?;
logger::warn!("Abnormal State Identified")
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn insert_psync_pcr_task_to_pt(
billing_mca_id: id_type::MerchantConnectorAccountId,
db: &dyn StorageInterface,
merchant_id: id_type::MerchantId,
payment_id: GlobalPaymentId,
profile_id: id_type::ProfileId,
payment_attempt_id: id_type::GlobalAttemptId,
runner: storage::ProcessTrackerRunner,
revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,
application_source: common_enums::ApplicationSource,
) -> RouterResult<storage::ProcessTracker> {
let task = PSYNC_WORKFLOW;
let process_tracker_id = payment_attempt_id.get_psync_revenue_recovery_id(task, runner);
let schedule_time = common_utils::date_time::now();
let psync_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
billing_mca_id,
global_payment_id: payment_id,
merchant_id,
profile_id,
payment_attempt_id,
revenue_recovery_retry,
invoice_scheduled_time: Some(schedule_time),
};
let tag = ["REVENUE_RECOVERY"];
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
psync_workflow_tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
application_source,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct delete tokenized data process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct delete tokenized data process tracker task")?;
metrics::TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", "RevenueRecoveryPsync")),
);
Ok(response)
}
pub async fn perform_payments_sync(
state: &SessionState,
process: &storage::ProcessTracker,
profile: &domain::Profile,
platform: domain::Platform,
tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,
revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
payment_intent: &PaymentIntent,
) -> Result<(), errors::ProcessTrackerError> {
let psync_data = api::call_psync_api(
state,
&tracking_data.global_payment_id,
revenue_recovery_payment_data,
true,
true,
)
.await?;
let payment_attempt = psync_data.payment_attempt.clone();
let mut revenue_recovery_metadata = payment_intent
.feature_metadata
.as_ref()
.and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())
.get_required_value("Payment Revenue Recovery Metadata")?
.convert_back();
let pcr_status: types::RevenueRecoveryPaymentIntentStatus =
payment_intent.status.foreign_into();
let new_revenue_recovery_payment_data = &pcr::RevenueRecoveryPaymentData {
psync_data: Some(psync_data),
..revenue_recovery_payment_data.clone()
};
Box::pin(
pcr_status.update_pt_status_based_on_attempt_status_for_payments_sync(
state,
payment_intent,
process.clone(),
profile,
platform,
new_revenue_recovery_payment_data,
payment_attempt,
&mut revenue_recovery_metadata,
),
)
.await?;
Ok(())
}
pub async fn perform_calculate_workflow(
state: &SessionState,
process: &storage::ProcessTracker,
profile: &domain::Profile,
platform: domain::Platform,
tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,
revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
payment_intent: &PaymentIntent,
) -> Result<(), sch_errors::ProcessTrackerError> {
let db = &*state.store;
let merchant_id = revenue_recovery_payment_data.merchant_account.get_id();
let profile_id = revenue_recovery_payment_data.profile.get_id();
let billing_mca_id = revenue_recovery_payment_data.billing_mca.get_id();
let mut event_type: Option<common_enums::EventType> = None;
logger::info!(
process_id = %process.id,
payment_id = %tracking_data.global_payment_id.get_string_repr(),
"Starting CALCULATE_WORKFLOW..."
);
// 1. Extract connector_customer_id and token_list from tracking_data
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let platform_from_revenue_recovery_payment_data = domain::Platform::new(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
None,
);
let retry_algorithm_type = match profile
.revenue_recovery_retry_algorithm_type
.filter(|retry_type|
*retry_type != common_enums::RevenueRecoveryAlgorithmType::Monitoring) // ignore Monitoring in profile
.unwrap_or(tracking_data.revenue_recovery_retry) // fallback to tracking_data
{
common_enums::RevenueRecoveryAlgorithmType::Smart => common_enums::RevenueRecoveryAlgorithmType::Smart,
common_enums::RevenueRecoveryAlgorithmType::Cascading => common_enums::RevenueRecoveryAlgorithmType::Cascading,
common_enums::RevenueRecoveryAlgorithmType::Monitoring => {
return Err(sch_errors::ProcessTrackerError::ProcessUpdateFailed);
}
};
// External Payments which enter the calculate workflow for the first time will have active attempt id as None
// Then we dont need to send an webhook to the merchant as its not a failure from our side.
// Thus we dont need to a payment get call for such payments.
let active_payment_attempt_id = payment_intent.active_attempt_id.as_ref();
let payments_response = get_payment_response_using_payment_get_operation(
state,
&tracking_data.global_payment_id,
revenue_recovery_payment_data,
&platform_from_revenue_recovery_payment_data,
active_payment_attempt_id,
)
.await?;
// 2. Get best available token
let payment_processor_token_response =
match revenue_recovery_workflow::get_token_with_schedule_time_based_on_retry_algorithm_type(
state,
&connector_customer_id,
payment_intent,
retry_algorithm_type,
process.retry_count,
)
.await
{
Ok(token_opt) => token_opt,
Err(e) => {
logger::error!(
error = ?e,
connector_customer_id = %connector_customer_id,
"Failed to get best PSP token"
);
revenue_recovery_workflow::PaymentProcessorTokenResponse::None
}
};
match payment_processor_token_response {
revenue_recovery_workflow::PaymentProcessorTokenResponse::ScheduledTime {
scheduled_time,
} => {
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"Found best available token, creating EXECUTE_WORKFLOW task"
);
// reset active attmept id and payment connector transmission before going to execute workflow
let _ = Box::pin(reset_connector_transmission_and_active_attempt_id_before_pushing_to_execute_workflow(
state,
payment_intent,
revenue_recovery_payment_data,
active_payment_attempt_id
)).await?;
// 3. If token found: create EXECUTE_WORKFLOW task and finish CALCULATE_WORKFLOW
insert_execute_pcr_task_to_pt(
&tracking_data.billing_mca_id,
state,
&tracking_data.merchant_id,
payment_intent,
&tracking_data.profile_id,
&tracking_data.payment_attempt_id,
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
retry_algorithm_type,
scheduled_time,
)
.await?;
db.as_scheduler()
.finish_process_with_business_status(
process.clone(),
business_status::CALCULATE_WORKFLOW_SCHEDULED,
)
.await
.map_err(|e| {
logger::error!(
process_id = %process.id,
error = ?e,
"Failed to update CALCULATE_WORKFLOW status to complete"
);
sch_errors::ProcessTrackerError::ProcessUpdateFailed
})?;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"CALCULATE_WORKFLOW completed successfully"
);
}
revenue_recovery_workflow::PaymentProcessorTokenResponse::NextAvailableTime {
next_available_time,
} => {
// Update scheduled time to next_available_time + Buffer
// here next_available_time is the wait time
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"No token but time available, rescheduling for scheduled time "
);
update_calculate_job_schedule_time(
db,
process,
time::Duration::seconds(
state
.conf
.revenue_recovery
.recovery_timestamp
.job_schedule_buffer_time_in_seconds,
),
Some(next_available_time),
&connector_customer_id,
retry_algorithm_type,
)
.await?;
}
revenue_recovery_workflow::PaymentProcessorTokenResponse::None => {
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"Hard decline flag is false, rescheduling after job_schedule_buffer_time_in_seconds"
);
update_calculate_job_schedule_time(
db,
process,
time::Duration::seconds(
state
.conf
.revenue_recovery
.recovery_timestamp
.job_schedule_buffer_time_in_seconds,
),
Some(common_utils::date_time::now()),
&connector_customer_id,
retry_algorithm_type,
)
.await?;
}
revenue_recovery_workflow::PaymentProcessorTokenResponse::HardDecline => {
// Finish calculate workflow with CALCULATE_WORKFLOW_FINISH
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"Token/Tokens is/are Hard decline, finishing CALCULATE_WORKFLOW"
);
db.as_scheduler()
.finish_process_with_business_status(
process.clone(),
business_status::CALCULATE_WORKFLOW_FINISH,
)
.await
.map_err(|e| {
logger::error!(
process_id = %process.id,
error = ?e,
"Failed to finish CALCULATE_WORKFLOW"
);
sch_errors::ProcessTrackerError::ProcessUpdateFailed
})?;
event_type = Some(common_enums::EventType::PaymentFailed);
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"CALCULATE_WORKFLOW finished successfully"
);
}
}
let _outgoing_webhook = event_type.and_then(|event_kind| {
payments_response.map(|resp| Some((event_kind, resp)))
})
.flatten()
.async_map(|(event_kind, response)| async move {
let _ = RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(
state,
common_enums::EventClass::Payments,
event_kind,
payment_intent,
&platform,
profile,
tracking_data.payment_attempt_id.get_string_repr().to_string(),
response
)
.await
.map_err(|e| {
logger::error!(
error = ?e,
"Failed to send outgoing webhook"
);
e
})
.ok();
}
).await;
Ok(())
}
/// Update the schedule time for a CALCULATE_WORKFLOW process tracker
async fn update_calculate_job_schedule_time(
db: &dyn StorageInterface,
process: &storage::ProcessTracker,
additional_time: time::Duration,
base_time: Option<time::PrimitiveDateTime>,
connector_customer_id: &str,
retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType,
) -> Result<(), sch_errors::ProcessTrackerError> {
let now = common_utils::date_time::now();
let new_schedule_time = base_time.filter(|&t| t > now).unwrap_or(now) + additional_time;
logger::info!(
new_schedule_time = %new_schedule_time,
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"Rescheduling Calculate Job at "
);
let mut old_tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
serde_json::from_value(process.tracking_data.clone())
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to deserialize the tracking data from process tracker")?;
old_tracking_data.revenue_recovery_retry = retry_algorithm_type;
let tracking_data = serde_json::to_value(old_tracking_data)
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to serialize the tracking data for process tracker")?;
let pt_update = storage::ProcessTrackerUpdate::Update {
name: Some("CALCULATE_WORKFLOW".to_string()),
retry_count: Some(process.clone().retry_count),
schedule_time: Some(new_schedule_time),
tracking_data: Some(tracking_data),
business_status: Some(String::from(business_status::PENDING)),
status: Some(ProcessTrackerStatus::Pending),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/profile_acquirer.rs | crates/router/src/core/profile_acquirer.rs | use api_models::profile_acquirer;
use error_stack::ResultExt;
use crate::{
core::errors::{self, utils::StorageErrorExt, RouterResponse},
services::api,
types::domain,
SessionState,
};
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn create_profile_acquirer(
state: SessionState,
request: profile_acquirer::ProfileAcquirerCreate,
platform: domain::Platform,
) -> RouterResponse<profile_acquirer::ProfileAcquirerResponse> {
let db = state.store.as_ref();
let profile_acquirer_id = common_utils::generate_profile_acquirer_id_of_default_length();
let merchant_key_store = platform.get_processor().get_key_store();
let mut business_profile = db
.find_business_profile_by_profile_id(merchant_key_store, &request.profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: request.profile_id.get_string_repr().to_owned(),
})?;
let incoming_acquirer_config = common_types::domain::AcquirerConfig {
acquirer_assigned_merchant_id: request.acquirer_assigned_merchant_id.clone(),
merchant_name: request.merchant_name.clone(),
network: request.network.clone(),
acquirer_bin: request.acquirer_bin.clone(),
acquirer_ica: request.acquirer_ica.clone(),
acquirer_fraud_rate: request.acquirer_fraud_rate,
};
// Check for duplicates before proceeding
business_profile
.acquirer_config_map
.as_ref()
.map_or(Ok(()), |configs_wrapper| {
match configs_wrapper.0.values().any(|existing_config| existing_config == &incoming_acquirer_config) {
true => Err(error_stack::report!(
errors::ApiErrorResponse::GenericDuplicateError {
message: format!(
"Duplicate acquirer configuration found for profile_id: {}. Conflicting configuration: {:?}",
request.profile_id.get_string_repr(),
incoming_acquirer_config
),
}
)),
false => Ok(()),
}
})?;
// Get a mutable reference to the HashMap inside AcquirerConfigMap,
// initializing if it's None or the inner HashMap is not present.
let configs_map = &mut business_profile
.acquirer_config_map
.get_or_insert_with(|| {
common_types::domain::AcquirerConfigMap(std::collections::HashMap::new())
})
.0;
configs_map.insert(
profile_acquirer_id.clone(),
incoming_acquirer_config.clone(),
);
let profile_update = domain::ProfileUpdate::AcquirerConfigMapUpdate {
acquirer_config_map: business_profile.acquirer_config_map.clone(),
};
let updated_business_profile = db
.update_profile_by_profile_id(merchant_key_store, business_profile, profile_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update business profile with new acquirer config")?;
let updated_acquire_details = updated_business_profile
.acquirer_config_map
.as_ref()
.and_then(|acquirer_configs_wrapper| acquirer_configs_wrapper.0.get(&profile_acquirer_id))
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get updated acquirer config")?;
let response = profile_acquirer::ProfileAcquirerResponse::from((
profile_acquirer_id,
&request.profile_id,
updated_acquire_details,
));
Ok(api::ApplicationResponse::Json(response))
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn update_profile_acquirer_config(
state: SessionState,
profile_id: common_utils::id_type::ProfileId,
profile_acquirer_id: common_utils::id_type::ProfileAcquirerId,
request: profile_acquirer::ProfileAcquirerUpdate,
platform: domain::Platform,
) -> RouterResponse<profile_acquirer::ProfileAcquirerResponse> {
let db = state.store.as_ref();
let merchant_key_store = platform.get_processor().get_key_store();
let mut business_profile = db
.find_business_profile_by_profile_id(merchant_key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let acquirer_config_map = business_profile
.acquirer_config_map
.as_mut()
.ok_or(errors::ApiErrorResponse::ProfileAcquirerNotFound {
profile_id: profile_id.get_string_repr().to_owned(),
profile_acquirer_id: profile_acquirer_id.get_string_repr().to_owned(),
})
.attach_printable("no acquirer config found in business profile")?;
let mut potential_updated_config = acquirer_config_map
.0
.get(&profile_acquirer_id)
.ok_or_else(|| errors::ApiErrorResponse::ProfileAcquirerNotFound {
profile_id: profile_id.get_string_repr().to_owned(),
profile_acquirer_id: profile_acquirer_id.get_string_repr().to_owned(),
})?
.clone();
// updating value in existing acquirer config
request
.acquirer_assigned_merchant_id
.map(|val| potential_updated_config.acquirer_assigned_merchant_id = val);
request
.merchant_name
.map(|val| potential_updated_config.merchant_name = val);
request
.network
.map(|val| potential_updated_config.network = val);
request
.acquirer_bin
.map(|val| potential_updated_config.acquirer_bin = val);
request
.acquirer_ica
.map(|val| potential_updated_config.acquirer_ica = Some(val.clone()));
request
.acquirer_fraud_rate
.map(|val| potential_updated_config.acquirer_fraud_rate = val);
// checking for duplicates in the acquirerConfigMap
match acquirer_config_map
.0
.iter()
.find(|(_existing_id, existing_config_val_ref)| {
**existing_config_val_ref == potential_updated_config
}) {
Some((conflicting_id_of_found_item, _)) => {
Err(error_stack::report!(errors::ApiErrorResponse::GenericDuplicateError {
message: format!(
"Duplicate acquirer configuration. This configuration already exists for profile_acquirer_id '{}' under profile_id '{}'.",
conflicting_id_of_found_item.get_string_repr(),
profile_id.get_string_repr()
),
}))
}
None => Ok(()),
}?;
acquirer_config_map
.0
.insert(profile_acquirer_id.clone(), potential_updated_config);
let updated_map_for_db_update = business_profile.acquirer_config_map.clone();
let profile_update = domain::ProfileUpdate::AcquirerConfigMapUpdate {
acquirer_config_map: updated_map_for_db_update,
};
let updated_business_profile = db
.update_profile_by_profile_id(merchant_key_store, business_profile, profile_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update business profile with updated acquirer config")?;
let final_acquirer_details = updated_business_profile
.acquirer_config_map
.as_ref()
.and_then(|configs_wrapper| configs_wrapper.0.get(&profile_acquirer_id))
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get updated acquirer config after DB update")?;
let response = profile_acquirer::ProfileAcquirerResponse::from((
profile_acquirer_id,
&profile_id,
final_acquirer_details,
));
Ok(api::ApplicationResponse::Json(response))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payment_link.rs | crates/router/src/core/payment_link.rs | pub mod validator;
use actix_web::http::header;
use api_models::{
admin::PaymentLinkConfig,
payments::{PaymentLinkData, PaymentLinkStatusWrap},
};
use common_utils::{
consts::{DEFAULT_LOCALE, DEFAULT_SESSION_EXPIRY},
ext_traits::{OptionExt, ValueExt},
types::{AmountConvertor, StringMajorUnitForCore},
};
use error_stack::{report, ResultExt};
use futures::future;
use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
use masking::{PeekInterface, Secret};
use router_env::logger;
use time::PrimitiveDateTime;
use super::{
errors::{self, RouterResult, StorageErrorExt},
payments::helpers,
};
use crate::{
consts::{
self, DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY,
DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY, DEFAULT_ENABLE_SAVED_PAYMENT_METHOD,
DEFAULT_HIDE_CARD_NICKNAME_FIELD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG,
DEFAULT_SDK_LAYOUT, DEFAULT_SHOW_CARD_FORM,
},
errors::RouterResponse,
get_payment_link_config_value, get_payment_link_config_value_based_on_priority,
routes::SessionState,
services,
types::{
api::payment_link::PaymentLinkResponseExt,
domain,
storage::{enums as storage_enums, payment_link::PaymentLink},
transformers::{ForeignFrom, ForeignInto},
},
};
pub async fn retrieve_payment_link(
state: SessionState,
payment_link_id: String,
) -> RouterResponse<api_models::payments::RetrievePaymentLinkResponse> {
let db = &*state.store;
let payment_link_config = db
.find_payment_link_by_payment_link_id(&payment_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
let session_expiry = payment_link_config.fulfilment_time.unwrap_or_else(|| {
common_utils::date_time::now()
.saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
});
let status = check_payment_link_status(session_expiry);
let response = api_models::payments::RetrievePaymentLinkResponse::foreign_from((
payment_link_config,
status,
));
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn form_payment_link_data(
state: &SessionState,
platform: domain::Platform,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn form_payment_link_data(
state: &SessionState,
platform: domain::Platform,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> {
let db = &*state.store;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&payment_id,
&merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_link_id = payment_intent
.payment_link_id
.get_required_value("payment_link_id")
.change_context(errors::ApiErrorResponse::PaymentLinkNotFound)?;
let merchant_name_from_merchant_account = platform
.get_processor()
.get_account()
.merchant_name
.clone()
.map(|merchant_name| merchant_name.into_inner().peek().to_owned())
.unwrap_or_default();
let payment_link = db
.find_payment_link_by_payment_link_id(&payment_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
let payment_link_config =
if let Some(pl_config_value) = payment_link.payment_link_config.clone() {
extract_payment_link_config(pl_config_value)?
} else {
PaymentLinkConfig {
theme: DEFAULT_BACKGROUND_COLOR.to_string(),
logo: DEFAULT_MERCHANT_LOGO.to_string(),
seller_name: merchant_name_from_merchant_account,
sdk_layout: DEFAULT_SDK_LAYOUT.to_owned(),
display_sdk_only: DEFAULT_DISPLAY_SDK_ONLY,
enabled_saved_payment_method: DEFAULT_ENABLE_SAVED_PAYMENT_METHOD,
hide_card_nickname_field: DEFAULT_HIDE_CARD_NICKNAME_FIELD,
show_card_form_by_default: DEFAULT_SHOW_CARD_FORM,
allowed_domains: DEFAULT_ALLOWED_DOMAINS,
transaction_details: None,
background_image: None,
details_layout: None,
branding_visibility: None,
payment_button_text: None,
custom_message_for_card_terms: None,
custom_message_for_payment_method_types: None,
payment_button_colour: None,
skip_status_screen: None,
background_colour: None,
payment_button_text_colour: None,
sdk_ui_rules: None,
payment_link_ui_rules: None,
enable_button_only_on_form_ready: DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY,
payment_form_header_text: None,
payment_form_label_type: None,
show_card_terms: None,
is_setup_mandate_flow: None,
color_icon_card_cvc_error: None,
}
};
let profile_id = payment_link
.profile_id
.clone()
.or(payment_intent.profile_id)
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Profile id missing in payment link and payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let return_url = if let Some(payment_create_return_url) = payment_intent.return_url.clone() {
payment_create_return_url
} else {
business_profile
.return_url
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "return_url",
})?
};
let (currency, client_secret) = validate_sdk_requirements(
payment_intent.currency,
payment_intent.client_secret.clone(),
)?;
let required_conversion_type = StringMajorUnitForCore;
let amount = required_conversion_type
.convert(payment_intent.amount, currency)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
let order_details = validate_order_details(payment_intent.order_details.clone(), currency)?;
let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| {
payment_intent
.created_at
.saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
});
// converting first letter of merchant name to upperCase
let merchant_name = capitalize_first_char(&payment_link_config.seller_name);
let payment_link_status = check_payment_link_status(session_expiry);
let is_payment_link_terminal_state = check_payment_link_invalid_conditions(
payment_intent.status,
&[
storage_enums::IntentStatus::Cancelled,
storage_enums::IntentStatus::Failed,
storage_enums::IntentStatus::Processing,
storage_enums::IntentStatus::RequiresCapture,
storage_enums::IntentStatus::RequiresMerchantAction,
storage_enums::IntentStatus::Succeeded,
storage_enums::IntentStatus::PartiallyCaptured,
storage_enums::IntentStatus::RequiresCustomerAction,
],
);
let attempt_id = payment_intent.active_attempt.get_id().clone();
let payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
&merchant_id,
&attempt_id.clone(),
platform.get_processor().get_account().storage_scheme,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
if is_payment_link_terminal_state
|| payment_link_status == api_models::payments::PaymentLinkStatus::Expired
{
let status = match payment_link_status {
api_models::payments::PaymentLinkStatus::Active => {
logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status);
PaymentLinkStatusWrap::IntentStatus(payment_intent.status)
}
api_models::payments::PaymentLinkStatus::Expired => {
if is_payment_link_terminal_state {
logger::info!("displaying status page as the requested payment link has reached terminal state with payment status as {:?}", payment_intent.status);
PaymentLinkStatusWrap::IntentStatus(payment_intent.status)
} else {
logger::info!(
"displaying status page as the requested payment link has expired"
);
PaymentLinkStatusWrap::PaymentLinkStatus(
api_models::payments::PaymentLinkStatus::Expired,
)
}
}
};
let attempt_id = payment_intent.active_attempt.get_id().clone();
let payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
&merchant_id,
&attempt_id.clone(),
platform.get_processor().get_account().storage_scheme,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_details = api_models::payments::PaymentLinkStatusDetails {
amount,
currency,
payment_id: payment_intent.payment_id,
merchant_name,
merchant_logo: payment_link_config.logo.clone(),
created: payment_link.created_at,
status,
error_code: payment_attempt.error_code,
error_message: payment_attempt.error_message,
redirect: false,
theme: payment_link_config.theme.clone(),
return_url: return_url.clone(),
locale: Some(state.clone().locale),
transaction_details: payment_link_config.transaction_details.clone(),
unified_code: payment_attempt.unified_code,
unified_message: payment_attempt.unified_message,
capture_method: payment_attempt.capture_method,
setup_future_usage_applied: payment_attempt.setup_future_usage_applied,
};
return Ok((
payment_link,
PaymentLinkData::PaymentLinkStatusDetails(Box::new(payment_details)),
payment_link_config,
));
};
let payment_link_details = api_models::payments::PaymentLinkDetails {
amount,
currency,
payment_id: payment_intent.payment_id,
merchant_name,
order_details,
return_url,
session_expiry,
pub_key: platform
.get_processor()
.get_account()
.publishable_key
.to_owned(),
client_secret,
merchant_logo: payment_link_config.logo.clone(),
max_items_visible_after_collapse: 3,
theme: payment_link_config.theme.clone(),
merchant_description: payment_intent.description,
sdk_layout: payment_link_config.sdk_layout.clone(),
display_sdk_only: payment_link_config.display_sdk_only,
hide_card_nickname_field: payment_link_config.hide_card_nickname_field,
show_card_form_by_default: payment_link_config.show_card_form_by_default,
locale: Some(state.clone().locale),
transaction_details: payment_link_config.transaction_details.clone(),
background_image: payment_link_config.background_image.clone(),
details_layout: payment_link_config.details_layout,
branding_visibility: payment_link_config.branding_visibility,
payment_button_text: payment_link_config.payment_button_text.clone(),
custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms.clone(),
custom_message_for_payment_method_types: payment_link_config
.custom_message_for_payment_method_types
.clone(),
payment_button_colour: payment_link_config.payment_button_colour.clone(),
skip_status_screen: payment_link_config.skip_status_screen,
background_colour: payment_link_config.background_colour.clone(),
payment_button_text_colour: payment_link_config.payment_button_text_colour.clone(),
sdk_ui_rules: payment_link_config.sdk_ui_rules.clone(),
status: payment_intent.status,
enable_button_only_on_form_ready: payment_link_config.enable_button_only_on_form_ready,
payment_form_header_text: payment_link_config.payment_form_header_text.clone(),
payment_form_label_type: payment_link_config.payment_form_label_type,
show_card_terms: payment_link_config.show_card_terms,
is_setup_mandate_flow: payment_link_config.is_setup_mandate_flow,
color_icon_card_cvc_error: payment_link_config.color_icon_card_cvc_error.clone(),
capture_method: payment_attempt.capture_method,
setup_future_usage_applied: payment_attempt.setup_future_usage_applied,
};
Ok((
payment_link,
PaymentLinkData::PaymentLinkDetails(Box::new(payment_link_details)),
payment_link_config,
))
}
pub async fn initiate_secure_payment_link_flow(
state: SessionState,
platform: domain::Platform,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
request_headers: &header::HeaderMap,
) -> RouterResponse<services::PaymentLinkFormData> {
let (payment_link, payment_link_details, payment_link_config) =
form_payment_link_data(&state, platform, merchant_id, payment_id).await?;
validator::validate_secure_payment_link_render_request(
request_headers,
&payment_link,
&payment_link_config,
)?;
let css_script = get_payment_link_css_script(&payment_link_config)?;
match payment_link_details {
PaymentLinkData::PaymentLinkStatusDetails(ref status_details) => {
let js_script = get_js_script(&payment_link_details)?;
let payment_link_error_data = services::PaymentLinkStatusData {
js_script,
css_script,
};
logger::info!(
"payment link data, for building payment link status page {:?}",
status_details
);
Ok(services::ApplicationResponse::PaymentLinkForm(Box::new(
services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data),
)))
}
PaymentLinkData::PaymentLinkDetails(link_details) => {
let secure_payment_link_details = api_models::payments::SecurePaymentLinkDetails {
enabled_saved_payment_method: payment_link_config.enabled_saved_payment_method,
hide_card_nickname_field: payment_link_config.hide_card_nickname_field,
show_card_form_by_default: payment_link_config.show_card_form_by_default,
payment_link_details: *link_details.to_owned(),
payment_button_text: payment_link_config.payment_button_text,
custom_message_for_card_terms: payment_link_config.custom_message_for_card_terms,
custom_message_for_payment_method_types: payment_link_config
.custom_message_for_payment_method_types,
payment_button_colour: payment_link_config.payment_button_colour,
skip_status_screen: payment_link_config.skip_status_screen,
background_colour: payment_link_config.background_colour,
payment_button_text_colour: payment_link_config.payment_button_text_colour,
sdk_ui_rules: payment_link_config.sdk_ui_rules,
enable_button_only_on_form_ready: payment_link_config
.enable_button_only_on_form_ready,
payment_form_header_text: payment_link_config.payment_form_header_text,
payment_form_label_type: payment_link_config.payment_form_label_type,
show_card_terms: payment_link_config.show_card_terms,
color_icon_card_cvc_error: payment_link_config.color_icon_card_cvc_error,
};
let payment_details_str = serde_json::to_string(&secure_payment_link_details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentLinkData")?;
let url_encoded_str = urlencoding::encode(&payment_details_str);
let js_script = format!("window.__PAYMENT_DETAILS = '{url_encoded_str}';");
let html_meta_tags = get_meta_tags_html(&link_details);
let payment_link_data = services::PaymentLinkFormData {
js_script,
sdk_url: state.conf.payment_link.sdk_url.clone(),
css_script,
html_meta_tags,
};
let allowed_domains = payment_link_config
.allowed_domains
.clone()
.ok_or(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| {
format!(
"Invalid list of allowed_domains found - {:?}",
payment_link_config.allowed_domains.clone()
)
})?;
if allowed_domains.is_empty() {
return Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| {
format!(
"Invalid list of allowed_domains found - {:?}",
payment_link_config.allowed_domains.clone()
)
});
}
let link_data = GenericLinks {
allowed_domains,
data: GenericLinksData::SecurePaymentLink(payment_link_data),
locale: DEFAULT_LOCALE.to_string(),
};
logger::info!(
"payment link data, for building secure payment link {:?}",
link_data
);
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
link_data,
)))
}
}
}
pub async fn initiate_payment_link_flow(
state: SessionState,
platform: domain::Platform,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResponse<services::PaymentLinkFormData> {
let (_, payment_details, payment_link_config) =
form_payment_link_data(&state, platform, merchant_id, payment_id).await?;
let css_script = get_payment_link_css_script(&payment_link_config)?;
let js_script = get_js_script(&payment_details)?;
match payment_details {
PaymentLinkData::PaymentLinkStatusDetails(status_details) => {
let payment_link_error_data = services::PaymentLinkStatusData {
js_script,
css_script,
};
logger::info!(
"payment link data, for building payment link status page {:?}",
status_details
);
Ok(services::ApplicationResponse::PaymentLinkForm(Box::new(
services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_error_data),
)))
}
PaymentLinkData::PaymentLinkDetails(payment_details) => {
let html_meta_tags = get_meta_tags_html(&payment_details);
let payment_link_data = services::PaymentLinkFormData {
js_script,
sdk_url: state.conf.payment_link.sdk_url.clone(),
css_script,
html_meta_tags,
};
logger::info!(
"payment link data, for building open payment link {:?}",
payment_link_data
);
Ok(services::ApplicationResponse::PaymentLinkForm(Box::new(
services::api::PaymentLinkAction::PaymentLinkFormData(payment_link_data),
)))
}
}
}
pub fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> {
payment_link::get_js_script(payment_details)
.change_context(errors::ApiErrorResponse::InternalServerError)
}
pub fn get_payment_link_css_script(
payment_link_config: &PaymentLinkConfig,
) -> RouterResult<String> {
payment_link::get_css_script(payment_link_config)
.change_context(errors::ApiErrorResponse::InternalServerError)
}
pub fn get_meta_tags_html(payment_details: &api_models::payments::PaymentLinkDetails) -> String {
payment_link::get_meta_tags_html(payment_details)
}
fn validate_sdk_requirements(
currency: Option<api_models::enums::Currency>,
client_secret: Option<String>,
) -> Result<(api_models::enums::Currency, String), errors::ApiErrorResponse> {
let currency = currency.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "currency",
})?;
let client_secret = client_secret.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})?;
Ok((currency, client_secret))
}
pub async fn list_payment_link(
state: SessionState,
merchant: domain::MerchantAccount,
constraints: api_models::payments::PaymentLinkListConstraints,
) -> RouterResponse<Vec<api_models::payments::RetrievePaymentLinkResponse>> {
let db = state.store.as_ref();
let payment_link = db
.list_payment_link_by_merchant_id(merchant.get_id(), constraints)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to retrieve payment link")?;
let payment_link_list = future::try_join_all(payment_link.into_iter().map(|payment_link| {
api_models::payments::RetrievePaymentLinkResponse::from_db_payment_link(payment_link)
}))
.await?;
Ok(services::ApplicationResponse::Json(payment_link_list))
}
pub fn check_payment_link_status(
payment_link_expiry: PrimitiveDateTime,
) -> api_models::payments::PaymentLinkStatus {
let curr_time = common_utils::date_time::now();
if curr_time > payment_link_expiry {
api_models::payments::PaymentLinkStatus::Expired
} else {
api_models::payments::PaymentLinkStatus::Active
}
}
fn validate_order_details(
order_details: Option<Vec<Secret<serde_json::Value>>>,
currency: api_models::enums::Currency,
) -> Result<
Option<Vec<api_models::payments::OrderDetailsWithStringAmount>>,
error_stack::Report<errors::ApiErrorResponse>,
> {
let required_conversion_type = StringMajorUnitForCore;
let order_details = order_details
.map(|order_details| {
order_details
.iter()
.map(|data| {
data.to_owned()
.parse_value("OrderDetailsWithAmount")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "OrderDetailsWithAmount",
})
.attach_printable("Unable to parse OrderDetailsWithAmount")
})
.collect::<Result<Vec<api_models::payments::OrderDetailsWithAmount>, _>>()
})
.transpose()?;
let updated_order_details = match order_details {
Some(mut order_details) => {
let mut order_details_amount_string_array: Vec<
api_models::payments::OrderDetailsWithStringAmount,
> = Vec::new();
for order in order_details.iter_mut() {
let mut order_details_amount_string : api_models::payments::OrderDetailsWithStringAmount = Default::default();
if order.product_img_link.is_none() {
order_details_amount_string.product_img_link =
Some(DEFAULT_PRODUCT_IMG.to_string())
} else {
order_details_amount_string
.product_img_link
.clone_from(&order.product_img_link)
};
order_details_amount_string.amount = required_conversion_type
.convert(order.amount, currency)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
order_details_amount_string.product_name =
capitalize_first_char(&order.product_name.clone());
order_details_amount_string.quantity = order.quantity;
order_details_amount_string_array.push(order_details_amount_string)
}
Some(order_details_amount_string_array)
}
None => None,
};
Ok(updated_order_details)
}
pub fn extract_payment_link_config(
pl_config: serde_json::Value,
) -> Result<PaymentLinkConfig, error_stack::Report<errors::ApiErrorResponse>> {
serde_json::from_value::<PaymentLinkConfig>(pl_config).change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_link_config",
},
)
}
pub fn get_payment_link_config_based_on_priority(
payment_create_link_config: Option<api_models::payments::PaymentCreatePaymentLinkConfig>,
business_link_config: Option<diesel_models::business_profile::BusinessPaymentLinkConfig>,
processor: &domain::Processor,
default_domain_name: String,
payment_link_config_id: Option<String>,
) -> Result<(PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> {
let merchant_name = processor
.get_account()
.merchant_name
.clone()
.map(|name| name.into_inner().peek().to_owned())
.unwrap_or_default();
let (domain_name, business_theme_configs, allowed_domains, branding_visibility) =
if let Some(business_config) = business_link_config {
(
business_config
.domain_name
.clone()
.map(|d_name| {
logger::info!("domain name set to custom domain https://{:?}", d_name);
format!("https://{d_name}")
})
.unwrap_or_else(|| default_domain_name.clone()),
payment_link_config_id
.and_then(|id| {
business_config
.business_specific_configs
.as_ref()
.and_then(|specific_configs| specific_configs.get(&id).cloned())
})
.or(business_config.default_config),
business_config.allowed_domains,
business_config.branding_visibility,
)
} else {
(default_domain_name, None, None, None)
};
let (
theme,
logo,
seller_name,
sdk_layout,
display_sdk_only,
enabled_saved_payment_method,
hide_card_nickname_field,
show_card_form_by_default,
enable_button_only_on_form_ready,
) = get_payment_link_config_value!(
payment_create_link_config,
business_theme_configs,
(theme, DEFAULT_BACKGROUND_COLOR.to_string()),
(logo, DEFAULT_MERCHANT_LOGO.to_string()),
(seller_name, merchant_name.clone()),
(sdk_layout, DEFAULT_SDK_LAYOUT.to_owned()),
(display_sdk_only, DEFAULT_DISPLAY_SDK_ONLY),
(
enabled_saved_payment_method,
DEFAULT_ENABLE_SAVED_PAYMENT_METHOD
),
(hide_card_nickname_field, DEFAULT_HIDE_CARD_NICKNAME_FIELD),
(show_card_form_by_default, DEFAULT_SHOW_CARD_FORM),
(
enable_button_only_on_form_ready,
DEFAULT_ENABLE_BUTTON_ONLY_ON_FORM_READY
)
);
let (
details_layout,
background_image,
payment_button_text,
custom_message_for_card_terms,
custom_message_for_payment_method_types,
payment_button_colour,
skip_status_screen,
background_colour,
payment_button_text_colour,
sdk_ui_rules,
payment_link_ui_rules,
payment_form_header_text,
payment_form_label_type,
show_card_terms,
is_setup_mandate_flow,
color_icon_card_cvc_error,
) = get_payment_link_config_value!(
payment_create_link_config,
business_theme_configs,
(details_layout),
(background_image, |background_image| background_image
.foreign_into()),
(payment_button_text),
(custom_message_for_card_terms),
(custom_message_for_payment_method_types),
(payment_button_colour),
(skip_status_screen),
(background_colour),
(payment_button_text_colour),
(sdk_ui_rules),
(payment_link_ui_rules),
(payment_form_header_text),
(payment_form_label_type),
(show_card_terms),
(is_setup_mandate_flow),
(color_icon_card_cvc_error),
);
let payment_link_config =
PaymentLinkConfig {
theme,
logo,
seller_name,
sdk_layout,
display_sdk_only,
enabled_saved_payment_method,
hide_card_nickname_field,
show_card_form_by_default,
allowed_domains,
branding_visibility,
skip_status_screen,
transaction_details: payment_create_link_config.as_ref().and_then(
|payment_link_config| payment_link_config.theme_config.transaction_details.clone(),
),
details_layout,
background_image,
payment_button_text,
custom_message_for_card_terms,
custom_message_for_payment_method_types,
payment_button_colour,
background_colour,
payment_button_text_colour,
sdk_ui_rules,
payment_link_ui_rules,
enable_button_only_on_form_ready,
payment_form_header_text,
payment_form_label_type,
show_card_terms,
is_setup_mandate_flow,
color_icon_card_cvc_error,
};
Ok((payment_link_config, domain_name))
}
fn capitalize_first_char(s: &str) -> String {
if let Some(first_char) = s.chars().next() {
let capitalized = first_char.to_uppercase();
let mut result = capitalized.to_string();
if let Some(remaining) = s.get(1..) {
result.push_str(remaining);
}
result
} else {
s.to_owned()
}
}
fn check_payment_link_invalid_conditions(
intent_status: storage_enums::IntentStatus,
not_allowed_statuses: &[storage_enums::IntentStatus],
) -> bool {
not_allowed_statuses.contains(&intent_status)
}
#[cfg(feature = "v2")]
pub async fn get_payment_link_status(
_state: SessionState,
_platform: domain::Platform,
_merchant_id: common_utils::id_type::MerchantId,
_payment_id: common_utils::id_type::PaymentId,
) -> RouterResponse<services::PaymentLinkFormData> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn get_payment_link_status(
state: SessionState,
platform: domain::Platform,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResponse<services::PaymentLinkFormData> {
let db = &*state.store;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&payment_id,
&merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/three_ds_decision_rule.rs | crates/router/src/core/three_ds_decision_rule.rs | pub mod utils;
use common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule;
use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use euclid::{
backend::{self, inputs as dsl_inputs, EuclidBackend},
frontend::ast,
};
use hyperswitch_domain_models::platform::Platform;
use router_env::{instrument, tracing};
use crate::{
core::{
errors,
errors::{RouterResponse, StorageErrorExt},
},
services,
types::transformers::ForeignFrom,
SessionState,
};
#[instrument(skip_all)]
pub async fn execute_three_ds_decision_rule(
state: SessionState,
platform: Platform,
request: api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
) -> RouterResponse<api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse> {
let decision = get_three_ds_decision_rule_output(
&state,
platform.get_processor().get_account().get_id(),
request.clone(),
)
.await?;
// Construct response
let response =
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse { decision };
Ok(services::ApplicationResponse::Json(response))
}
pub async fn get_three_ds_decision_rule_output(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
request: api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
) -> errors::RouterResult<common_types::three_ds_decision_rule_engine::ThreeDSDecision> {
let db = state.store.as_ref();
// Retrieve the rule from database
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(&request.routing_id, merchant_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let algorithm: Algorithm = routing_algorithm
.algorithm_data
.parse_value("Algorithm")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing program from three_ds_decision rule algorithm")?;
let program: ast::Program<ThreeDSDecisionRule> = algorithm
.data
.parse_value("Program<ThreeDSDecisionRule>")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing program from three_ds_decision rule algorithm")?;
// Construct backend input from request
let backend_input = dsl_inputs::BackendInput::foreign_from(request.clone());
// Initialize interpreter with the rule program
let interpreter = backend::VirInterpreterBackend::with_program(program)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error initializing DSL interpreter backend")?;
// Execute the rule
let result = interpreter
.execute(backend_input)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error executing 3DS decision rule")?;
// Apply PSD2 validations to the decision
let final_decision =
utils::apply_psd2_validations_during_execute(result.get_output().get_decision(), &request);
Ok(final_decision)
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Algorithm {
data: serde_json::Value,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/encryption.rs | crates/router/src/core/encryption.rs | use api_models::admin::MerchantKeyTransferRequest;
use base64::Engine;
use common_utils::{
keymanager::transfer_key_to_key_manager,
types::keymanager::{EncryptionTransferRequest, Identifier},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
use masking::{ExposeInterface, StrongSecret};
use crate::{consts::BASE64_ENGINE, errors, types::domain::UserKeyStore, SessionState};
pub async fn transfer_encryption_key(
state: &SessionState,
req: MerchantKeyTransferRequest,
) -> errors::CustomResult<usize, errors::ApiErrorResponse> {
let db = &*state.store;
let key_stores = db
.get_all_key_stores(&db.get_master_key().to_vec().into(), req.from, req.limit)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
send_request_to_key_service_for_merchant(state, key_stores).await
}
pub async fn send_request_to_key_service_for_merchant(
state: &SessionState,
keys: Vec<MerchantKeyStore>,
) -> errors::CustomResult<usize, errors::ApiErrorResponse> {
let total = keys.len();
for key in keys {
let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose());
let req = EncryptionTransferRequest {
identifier: Identifier::Merchant(key.merchant_id.clone()),
key: StrongSecret::new(key_encoded),
};
transfer_key_to_key_manager(&state.into(), req)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
}
Ok(total)
}
pub async fn send_request_to_key_service_for_user(
state: &SessionState,
keys: Vec<UserKeyStore>,
) -> errors::CustomResult<usize, errors::ApiErrorResponse> {
futures::future::try_join_all(keys.into_iter().map(|key| async move {
let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose());
let req = EncryptionTransferRequest {
identifier: Identifier::User(key.user_id.clone()),
key: StrongSecret::new(key_encoded),
};
transfer_key_to_key_manager(&state.into(), req).await
}))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(|v| v.len())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/verification.rs | crates/router/src/core/verification.rs | pub mod utils;
use api_models::verifications::{self, ApplepayMerchantResponse};
use common_utils::{errors::CustomResult, request::RequestContent};
use error_stack::ResultExt;
use masking::ExposeInterface;
use crate::{core::errors, headers, logger, routes::SessionState, services};
const APPLEPAY_INTERNAL_MERCHANT_NAME: &str = "Applepay_merchant";
pub async fn verify_merchant_creds_for_applepay(
state: SessionState,
body: verifications::ApplepayMerchantVerificationRequest,
merchant_id: common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
) -> CustomResult<services::ApplicationResponse<ApplepayMerchantResponse>, errors::ApiErrorResponse>
{
let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner();
let applepay_internal_merchant_identifier = applepay_merchant_configs
.common_merchant_identifier
.clone()
.expose();
let cert_data = applepay_merchant_configs.merchant_cert.clone();
let key_data = applepay_merchant_configs.merchant_cert_key.clone();
let applepay_endpoint = &applepay_merchant_configs.applepay_endpoint;
let request_body = verifications::ApplepayMerchantVerificationConfigs {
domain_names: body.domain_names.clone(),
encrypt_to: applepay_internal_merchant_identifier.clone(),
partner_internal_merchant_identifier: applepay_internal_merchant_identifier,
partner_merchant_name: APPLEPAY_INTERNAL_MERCHANT_NAME.to_string(),
};
let apple_pay_merch_verification_req = services::RequestBuilder::new()
.method(services::Method::Post)
.url(applepay_endpoint)
.attach_default_headers()
.headers(vec![(
headers::CONTENT_TYPE.to_string(),
"application/json".to_string().into(),
)])
.set_body(RequestContent::Json(Box::new(request_body)))
.add_certificate(Some(cert_data))
.add_certificate_key(Some(key_data))
.build();
let response = services::call_connector_api(
&state,
apple_pay_merch_verification_req,
"verify_merchant_creds_for_applepay",
)
.await;
utils::log_applepay_verification_response_if_error(&response);
let applepay_response =
response.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Error is already logged
match applepay_response {
Ok(_) => {
utils::check_existence_and_add_domain_to_db(
&state,
merchant_id,
profile_id,
body.merchant_connector_account_id.clone(),
body.domain_names.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(services::api::ApplicationResponse::Json(
ApplepayMerchantResponse {
status_message: "Applepay verification Completed".to_string(),
},
))
}
Err(error) => {
logger::error!(?error);
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Applepay verification Failed".to_string(),
}
.into())
}
}
}
pub async fn get_verified_apple_domains_with_mid_mca_id(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
) -> CustomResult<
services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>,
errors::ApiErrorResponse,
> {
let db = state.store.as_ref();
let key_store = db
.get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())
.await
.change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?;
#[cfg(feature = "v1")]
let verified_domains = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&merchant_id,
&merchant_connector_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?
.applepay_verified_domains
.unwrap_or_default();
#[cfg(feature = "v2")]
let verified_domains = db
.find_merchant_connector_account_by_id(&merchant_connector_id, &key_store)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?
.applepay_verified_domains
.unwrap_or_default();
Ok(services::api::ApplicationResponse::Json(
verifications::ApplepayVerifiedDomainsResponse { verified_domains },
))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/pm_auth.rs | crates/router/src/core/pm_auth.rs | use std::{collections::HashMap, str::FromStr};
use api_models::{
enums,
payment_methods::{self, BankAccountAccessCreds},
};
use common_enums::{enums::MerchantStorageScheme, PaymentMethodType};
pub mod helpers;
pub mod transformers;
use common_utils::{
consts,
crypto::{HmacSha256, SignMessage},
ext_traits::{AsyncExt, ValueExt},
generate_id,
types::{self as util_types, AmountConvertor},
};
use error_stack::ResultExt;
use helpers::PaymentAuthConnectorDataExt;
use hyperswitch_domain_models::payments::PaymentIntent;
use masking::{ExposeInterface, PeekInterface, Secret};
use pm_auth::{
connector::plaid::transformers::PlaidAuthType,
types::{
self as pm_auth_types,
api::{
auth_service::{BankAccountCredentials, ExchangeToken, LinkToken},
BoxedConnectorIntegration, PaymentAuthConnectorData,
},
},
};
use crate::{
core::{
errors::{self, ApiErrorResponse, RouterResponse, RouterResult, StorageErrorExt},
payment_methods::cards,
payments::helpers as oss_helpers,
pm_auth::helpers as pm_auth_helpers,
},
db::StorageInterface,
logger,
routes::SessionState,
services::{pm_auth as pm_auth_services, ApplicationResponse},
types::{self, domain, storage, transformers::ForeignTryFrom},
};
#[cfg(feature = "v1")]
pub async fn create_link_token(
state: SessionState,
platform: domain::Platform,
payload: api_models::pm_auth::LinkTokenCreateRequest,
headers: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> {
let db = &*state.store;
let redis_conn = db
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let pm_auth_key = payload.payment_id.get_pm_auth_key();
redis_conn
.exists::<Vec<u8>>(&pm_auth_key.as_str().into())
.await
.change_context(ApiErrorResponse::InvalidRequestData {
message: "Incorrect payment_id provided in request".to_string(),
})
.attach_printable("Corresponding pm_auth_key does not exist in redis")?
.then_some(())
.ok_or(ApiErrorResponse::InvalidRequestData {
message: "Incorrect payment_id provided in request".to_string(),
})
.attach_printable("Corresponding pm_auth_key does not exist in redis")?;
let pm_auth_configs = redis_conn
.get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>(
&pm_auth_key.as_str().into(),
"Vec<PaymentMethodAuthConnectorChoice>",
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get payment method auth choices from redis")?;
let selected_config = pm_auth_configs
.into_iter()
.find(|config| {
config.payment_method == payload.payment_method
&& config.payment_method_type == payload.payment_method_type
})
.ok_or(ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector name not found".to_string(),
})?;
let connector_name = selected_config.connector_name.as_str();
let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?;
let connector_integration: BoxedConnectorIntegration<
'_,
LinkToken,
pm_auth_types::LinkTokenRequest,
pm_auth_types::LinkTokenResponse,
> = connector.connector.get_connector_integration();
let payment_intent = oss_helpers::verify_payment_intent_time_and_client_secret(
&state,
&platform,
payload.client_secret,
)
.await?;
let billing_country = payment_intent
.as_ref()
.async_map(|pi| async {
oss_helpers::get_address_by_id(
&state,
pi.billing_address_id.clone(),
platform.get_processor().get_key_store(),
&pi.payment_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_account().storage_scheme,
)
.await
})
.await
.transpose()?
.flatten()
.and_then(|address| address.country)
.map(|country| country.to_string());
#[cfg(feature = "v1")]
let merchant_connector_account = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
platform.get_processor().get_account().get_id(),
&selected_config.mca_id,
platform.get_processor().get_key_store(),
)
.await
.change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: platform
.get_processor()
.get_account()
.get_id()
.get_string_repr()
.to_owned(),
})?;
#[cfg(feature = "v2")]
let merchant_connector_account = {
let _ = billing_country;
todo!()
};
let auth_type = helpers::get_connector_auth_type(merchant_connector_account)?;
let router_data = pm_auth_types::LinkTokenRouterData {
flow: std::marker::PhantomData,
merchant_id: Some(platform.get_processor().get_account().get_id().clone()),
connector: Some(connector_name.to_string()),
request: pm_auth_types::LinkTokenRequest {
client_name: "HyperSwitch".to_string(),
country_codes: Some(vec![billing_country.ok_or(
ApiErrorResponse::MissingRequiredField {
field_name: "billing_country",
},
)?]),
language: payload.language,
user_info: payment_intent.and_then(|pi| pi.customer_id),
client_platform: headers
.as_ref()
.and_then(|header| header.x_client_platform.clone()),
android_package_name: headers.as_ref().and_then(|header| header.x_app_id.clone()),
redirect_uri: headers
.as_ref()
.and_then(|header| header.x_redirect_uri.clone()),
},
response: Ok(pm_auth_types::LinkTokenResponse {
link_token: "".to_string(),
}),
connector_http_status_code: None,
connector_auth_type: auth_type,
};
let connector_resp = pm_auth_services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
&connector.connector_name,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed while calling link token creation connector api")?;
let link_token_resp =
connector_resp
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
let response = api_models::pm_auth::LinkTokenCreateResponse {
link_token: link_token_resp.link_token,
connector: connector.connector_name.to_string(),
};
Ok(ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn create_link_token(
_state: SessionState,
_platform: domain::Platform,
_payload: api_models::pm_auth::LinkTokenCreateRequest,
_headers: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResponse<api_models::pm_auth::LinkTokenCreateResponse> {
todo!()
}
impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType {
type Error = errors::ConnectorError;
fn foreign_try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
types::ConnectorAuthType::BodyKey { api_key, key1 } => {
Ok::<Self, errors::ConnectorError>(Self {
client_id: api_key.to_owned(),
secret: key1.to_owned(),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
}
}
}
pub async fn exchange_token_core(
state: SessionState,
platform: domain::Platform,
payload: api_models::pm_auth::ExchangeTokenCreateRequest,
) -> RouterResponse<()> {
let db = &*state.store;
let config = get_selected_config_from_redis(db, &payload).await?;
let connector_name = config.connector_name.as_str();
let connector = PaymentAuthConnectorData::get_connector_by_name(connector_name)?;
#[cfg(feature = "v1")]
let merchant_connector_account = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
platform.get_processor().get_account().get_id(),
&config.mca_id,
platform.get_processor().get_key_store(),
)
.await
.change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: platform
.get_processor()
.get_account()
.get_id()
.get_string_repr()
.to_owned(),
})?;
#[cfg(feature = "v2")]
let merchant_connector_account: domain::MerchantConnectorAccount = {
let _ = platform.get_processor().get_account();
let _ = connector;
let _ = platform.get_processor().get_key_store();
todo!()
};
let auth_type = helpers::get_connector_auth_type(merchant_connector_account.clone())?;
let access_token = get_access_token_from_exchange_api(
&connector,
connector_name,
&payload,
&auth_type,
&state,
)
.await?;
let bank_account_details_resp = get_bank_account_creds(
connector,
&platform,
connector_name,
&access_token,
auth_type,
&state,
None,
)
.await?;
Box::pin(store_bank_details_in_payment_methods(
payload,
platform,
state,
bank_account_details_resp,
(connector_name, access_token),
merchant_connector_account.get_id(),
))
.await?;
Ok(ApplicationResponse::StatusOk)
}
#[cfg(feature = "v1")]
async fn store_bank_details_in_payment_methods(
payload: api_models::pm_auth::ExchangeTokenCreateRequest,
platform: domain::Platform,
state: SessionState,
bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse,
connector_details: (&str, Secret<String>),
mca_id: common_utils::id_type::MerchantConnectorAccountId,
) -> RouterResult<()> {
let db = &*state.clone().store;
let (connector_name, access_token) = connector_details;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&payload.payment_id,
platform.get_processor().get_account().get_id(),
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(ApiErrorResponse::PaymentNotFound)?;
let customer_id = payment_intent
.customer_id
.ok_or(ApiErrorResponse::CustomerNotFound)?;
let payment_methods = db
.find_payment_method_by_customer_id_merchant_id_list(
platform.get_processor().get_key_store(),
&customer_id,
platform.get_processor().get_account().get_id(),
None,
)
.await
.change_context(ApiErrorResponse::InternalServerError)?;
let mut hash_to_payment_method: HashMap<
String,
(
domain::PaymentMethod,
payment_methods::PaymentMethodDataBankCreds,
),
> = HashMap::new();
let key_manager_state = (&state).into();
for pm in payment_methods {
if pm.get_payment_method_type() == Some(enums::PaymentMethod::BankDebit)
&& pm.payment_method_data.is_some()
{
let bank_details_pm_data = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.map(|v| v.parse_value("PaymentMethodsData"))
.transpose()
.unwrap_or_else(|error| {
logger::error!(?error);
None
})
.and_then(|pmd| match pmd {
payment_methods::PaymentMethodsData::BankDetails(bank_creds) => {
Some(bank_creds)
}
_ => None,
})
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse PaymentMethodsData")?;
hash_to_payment_method.insert(
bank_details_pm_data.hash.clone(),
(pm, bank_details_pm_data),
);
}
}
let pm_auth_key = state
.conf
.payment_method_auth
.get_inner()
.pm_auth_key
.clone()
.expose();
let mut update_entries: Vec<(domain::PaymentMethod, storage::PaymentMethodUpdate)> = Vec::new();
let mut new_entries: Vec<domain::PaymentMethod> = Vec::new();
for creds in bank_account_details_resp.credentials {
let (account_number, hash_string) = match creds.account_details {
pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => (
ach.account_number.clone(),
format!(
"{}-{}-{}",
ach.account_number.peek(),
ach.routing_number.peek(),
PaymentMethodType::Ach,
),
),
pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => (
bacs.account_number.clone(),
format!(
"{}-{}-{}",
bacs.account_number.peek(),
bacs.sort_code.peek(),
PaymentMethodType::Bacs
),
),
pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => (
sepa.iban.clone(),
format!("{}-{}", sepa.iban.expose(), PaymentMethodType::Sepa),
),
};
let generated_hash = hex::encode(
HmacSha256::sign_message(&HmacSha256, pm_auth_key.as_bytes(), hash_string.as_bytes())
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to sign the message")?,
);
let contains_account = hash_to_payment_method.get(&generated_hash);
let mut pmd = payment_methods::PaymentMethodDataBankCreds {
mask: account_number
.peek()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>(),
hash: generated_hash,
account_type: creds.account_type,
account_name: creds.account_name,
payment_method_type: creds.payment_method_type,
connector_details: vec![payment_methods::BankAccountConnectorDetails {
connector: connector_name.to_string(),
mca_id: mca_id.clone(),
access_token: BankAccountAccessCreds::AccessToken(access_token.clone()),
account_id: creds.account_id,
}],
};
if let Some((pm, details)) = contains_account {
pmd.connector_details.extend(
details
.connector_details
.clone()
.into_iter()
.filter(|conn| conn.mca_id != mca_id),
);
let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd);
let encrypted_data = cards::create_encrypted_data(
&key_manager_state,
platform.get_processor().get_key_store(),
payment_method_data,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?;
let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data: Some(encrypted_data.into()),
last_modified_by: None,
};
update_entries.push((pm.clone(), pm_update));
} else {
let payment_method_data = payment_methods::PaymentMethodsData::BankDetails(pmd);
let encrypted_data = cards::create_encrypted_data(
&key_manager_state,
platform.get_processor().get_key_store(),
Some(payment_method_data),
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?;
let pm_id = generate_id(consts::ID_LENGTH, "pm");
let now = common_utils::date_time::now();
let pm_new = domain::PaymentMethod {
customer_id: customer_id.clone(),
merchant_id: platform.get_processor().get_account().get_id().clone(),
payment_method_id: pm_id,
payment_method: Some(enums::PaymentMethod::BankDebit),
payment_method_type: Some(creds.payment_method_type),
status: enums::PaymentMethodStatus::Active,
payment_method_issuer: None,
scheme: None,
metadata: None,
payment_method_data: Some(encrypted_data),
payment_method_issuer_code: None,
accepted_currency: None,
token: None,
cardholder_name: None,
issuer_name: None,
issuer_country: None,
payer_country: None,
is_stored: None,
swift_code: None,
direct_debit_token: None,
created_at: now,
last_modified: now,
locker_id: None,
last_used_at: now,
connector_mandate_details: None,
customer_acceptance: None,
network_transaction_id: None,
client_secret: None,
payment_method_billing_address: None,
updated_by: None,
version: common_types::consts::API_VERSION,
network_token_requestor_reference_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
vault_source_details: Default::default(),
created_by: None,
last_modified_by: None,
};
new_entries.push(pm_new);
};
}
store_in_db(
platform.get_processor().get_key_store(),
update_entries,
new_entries,
db,
platform.get_processor().get_account().storage_scheme,
)
.await?;
Ok(())
}
#[cfg(feature = "v2")]
async fn store_bank_details_in_payment_methods(
_payload: api_models::pm_auth::ExchangeTokenCreateRequest,
_platform: domain::Platform,
_state: SessionState,
_bank_account_details_resp: pm_auth_types::BankAccountCredentialsResponse,
_connector_details: (&str, Secret<String>),
_mca_id: common_utils::id_type::MerchantConnectorAccountId,
) -> RouterResult<()> {
todo!()
}
async fn store_in_db(
key_store: &domain::MerchantKeyStore,
update_entries: Vec<(domain::PaymentMethod, storage::PaymentMethodUpdate)>,
new_entries: Vec<domain::PaymentMethod>,
db: &dyn StorageInterface,
storage_scheme: MerchantStorageScheme,
) -> RouterResult<()> {
let update_entries_futures = update_entries
.into_iter()
.map(|(pm, pm_update)| db.update_payment_method(key_store, pm, pm_update, storage_scheme))
.collect::<Vec<_>>();
let new_entries_futures = new_entries
.into_iter()
.map(|pm_new| db.insert_payment_method(key_store, pm_new, storage_scheme))
.collect::<Vec<_>>();
let update_futures = futures::future::join_all(update_entries_futures);
let new_futures = futures::future::join_all(new_entries_futures);
let (update, new) = tokio::join!(update_futures, new_futures);
let _ = update
.into_iter()
.map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}")));
let _ = new
.into_iter()
.map(|res| res.map_err(|err| logger::error!("Payment method storage failed {err:?}")));
Ok(())
}
pub async fn get_bank_account_creds(
connector: PaymentAuthConnectorData,
platform: &domain::Platform,
connector_name: &str,
access_token: &Secret<String>,
auth_type: pm_auth_types::ConnectorAuthType,
state: &SessionState,
bank_account_id: Option<Secret<String>>,
) -> RouterResult<pm_auth_types::BankAccountCredentialsResponse> {
let connector_integration_bank_details: BoxedConnectorIntegration<
'_,
BankAccountCredentials,
pm_auth_types::BankAccountCredentialsRequest,
pm_auth_types::BankAccountCredentialsResponse,
> = connector.connector.get_connector_integration();
let router_data_bank_details = pm_auth_types::BankDetailsRouterData {
flow: std::marker::PhantomData,
merchant_id: Some(platform.get_processor().get_account().get_id().clone()),
connector: Some(connector_name.to_string()),
request: pm_auth_types::BankAccountCredentialsRequest {
access_token: access_token.clone(),
optional_ids: bank_account_id
.map(|id| pm_auth_types::BankAccountOptionalIDs { ids: vec![id] }),
},
response: Ok(pm_auth_types::BankAccountCredentialsResponse {
credentials: Vec::new(),
}),
connector_http_status_code: None,
connector_auth_type: auth_type,
};
let bank_details_resp = pm_auth_services::execute_connector_processing_step(
state,
connector_integration_bank_details,
&router_data_bank_details,
&connector.connector_name,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed while calling bank account details connector api")?;
let bank_account_details_resp =
bank_details_resp
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(bank_account_details_resp)
}
async fn get_access_token_from_exchange_api(
connector: &PaymentAuthConnectorData,
connector_name: &str,
payload: &api_models::pm_auth::ExchangeTokenCreateRequest,
auth_type: &pm_auth_types::ConnectorAuthType,
state: &SessionState,
) -> RouterResult<Secret<String>> {
let connector_integration: BoxedConnectorIntegration<
'_,
ExchangeToken,
pm_auth_types::ExchangeTokenRequest,
pm_auth_types::ExchangeTokenResponse,
> = connector.connector.get_connector_integration();
let router_data = pm_auth_types::ExchangeTokenRouterData {
flow: std::marker::PhantomData,
merchant_id: None,
connector: Some(connector_name.to_string()),
request: pm_auth_types::ExchangeTokenRequest {
public_token: payload.public_token.clone(),
},
response: Ok(pm_auth_types::ExchangeTokenResponse {
access_token: "".to_string(),
}),
connector_http_status_code: None,
connector_auth_type: auth_type.clone(),
};
let resp = pm_auth_services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
&connector.connector_name,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed while calling exchange token connector api")?;
let exchange_token_resp =
resp.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
let access_token = exchange_token_resp.access_token;
Ok(Secret::new(access_token))
}
async fn get_selected_config_from_redis(
db: &dyn StorageInterface,
payload: &api_models::pm_auth::ExchangeTokenCreateRequest,
) -> RouterResult<api_models::pm_auth::PaymentMethodAuthConnectorChoice> {
let redis_conn = db
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let pm_auth_key = payload.payment_id.get_pm_auth_key();
redis_conn
.exists::<Vec<u8>>(&pm_auth_key.as_str().into())
.await
.change_context(ApiErrorResponse::InvalidRequestData {
message: "Incorrect payment_id provided in request".to_string(),
})
.attach_printable("Corresponding pm_auth_key does not exist in redis")?
.then_some(())
.ok_or(ApiErrorResponse::InvalidRequestData {
message: "Incorrect payment_id provided in request".to_string(),
})
.attach_printable("Corresponding pm_auth_key does not exist in redis")?;
let pm_auth_configs = redis_conn
.get_and_deserialize_key::<Vec<api_models::pm_auth::PaymentMethodAuthConnectorChoice>>(
&pm_auth_key.as_str().into(),
"Vec<PaymentMethodAuthConnectorChoice>",
)
.await
.change_context(ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector name not found".to_string(),
})
.attach_printable("Failed to get payment method auth choices from redis")?;
let selected_config = pm_auth_configs
.iter()
.find(|conf| {
conf.payment_method == payload.payment_method
&& conf.payment_method_type == payload.payment_method_type
})
.ok_or(ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector name not found".to_string(),
})?
.clone();
Ok(selected_config)
}
#[cfg(feature = "v2")]
pub async fn retrieve_payment_method_from_auth_service(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
auth_token: &payment_methods::BankAccountTokenData,
payment_intent: &PaymentIntent,
_customer: &Option<domain::Customer>,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn retrieve_payment_method_from_auth_service(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
auth_token: &payment_methods::BankAccountTokenData,
payment_intent: &PaymentIntent,
_customer: &Option<domain::Customer>,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
let db = state.store.as_ref();
let connector = PaymentAuthConnectorData::get_connector_by_name(
auth_token.connector_details.connector.as_str(),
)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(&payment_intent.merchant_id, key_store)
.await
.to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&payment_intent.merchant_id,
&auth_token.connector_details.mca_id,
key_store,
)
.await
.to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: auth_token
.connector_details
.mca_id
.get_string_repr()
.to_string()
.clone(),
})
.attach_printable(
"error while fetching merchant_connector_account from merchant_id and connector name",
)?;
let auth_type = pm_auth_helpers::get_connector_auth_type(mca)?;
let BankAccountAccessCreds::AccessToken(access_token) =
&auth_token.connector_details.access_token;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
let bank_account_creds = get_bank_account_creds(
connector,
&platform,
&auth_token.connector_details.connector,
access_token,
auth_type,
state,
Some(auth_token.connector_details.account_id.clone()),
)
.await?;
let bank_account = bank_account_creds
.credentials
.iter()
.find(|acc| {
acc.payment_method_type == auth_token.payment_method_type
&& acc.payment_method == auth_token.payment_method
})
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Bank account details not found")?;
if let (Some(balance), Some(currency)) = (bank_account.balance, payment_intent.currency) {
let required_conversion = util_types::FloatMajorUnitForConnector;
let converted_amount = required_conversion
.convert_back(balance, currency)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert FloatMajorUnit to MinorUnit")?;
if converted_amount < payment_intent.amount {
return Err((ApiErrorResponse::PreconditionFailed {
message: "selected bank account has insufficient balance".to_string(),
})
.into());
}
}
let mut bank_type = None;
if let Some(account_type) = bank_account.account_type.clone() {
bank_type = common_enums::BankType::from_str(account_type.as_str())
.map_err(|error| logger::error!(%error,"unable to parse account_type {account_type:?}"))
.ok();
}
let payment_method_data = match &bank_account.account_details {
pm_auth_types::PaymentMethodTypeDetails::Ach(ach) => {
domain::PaymentMethodData::BankDebit(domain::BankDebitData::AchBankDebit {
account_number: ach.account_number.clone(),
routing_number: ach.routing_number.clone(),
bank_name: None,
bank_type,
bank_holder_type: None,
card_holder_name: None,
bank_account_holder_name: None,
})
}
pm_auth_types::PaymentMethodTypeDetails::Bacs(bacs) => {
domain::PaymentMethodData::BankDebit(domain::BankDebitData::BacsBankDebit {
account_number: bacs.account_number.clone(),
sort_code: bacs.sort_code.clone(),
bank_account_holder_name: None,
})
}
pm_auth_types::PaymentMethodTypeDetails::Sepa(sepa) => {
domain::PaymentMethodData::BankDebit(domain::BankDebitData::SepaBankDebit {
iban: sepa.iban.clone(),
bank_account_holder_name: None,
})
}
};
Ok(Some((payment_method_data, enums::PaymentMethod::BankDebit)))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/cards_info.rs | crates/router/src/core/cards_info.rs | use actix_multipart::form::{bytes::Bytes, MultipartForm};
use api_models::cards_info as cards_info_api_types;
use common_utils::fp_utils::when;
use csv::Reader;
use diesel_models::cards_info as card_info_models;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::cards_info;
use rdkafka::message::ToBytes;
use router_env::{instrument, tracing};
use crate::{
core::{
errors::{self, RouterResponse, RouterResult, StorageErrorExt},
payments::helpers,
},
routes,
services::ApplicationResponse,
types::{
domain,
transformers::{ForeignFrom, ForeignInto},
},
};
fn verify_iin_length(card_iin: &str) -> Result<(), errors::ApiErrorResponse> {
let is_bin_length_in_range = card_iin.len() == 6 || card_iin.len() == 8;
when(!is_bin_length_in_range, || {
Err(errors::ApiErrorResponse::InvalidCardIinLength)
})
}
#[instrument(skip_all)]
pub async fn retrieve_card_info(
state: routes::SessionState,
platform: domain::Platform,
request: cards_info_api_types::CardsInfoRequest,
) -> RouterResponse<cards_info_api_types::CardInfoResponse> {
let db = state.store.as_ref();
verify_iin_length(&request.card_iin)?;
helpers::verify_payment_intent_time_and_client_secret(&state, &platform, request.client_secret)
.await?;
let card_info = db
.get_card_info(&request.card_iin)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve card information")?
.ok_or(report!(errors::ApiErrorResponse::InvalidCardIin))?;
Ok(ApplicationResponse::Json(
cards_info_api_types::CardInfoResponse::foreign_from(card_info),
))
}
#[instrument(skip_all)]
pub async fn create_card_info(
state: routes::SessionState,
card_info_request: cards_info_api_types::CardInfoCreateRequest,
) -> RouterResponse<cards_info_api_types::CardInfoResponse> {
let db = state.store.as_ref();
cards_info::CardsInfoInterface::add_card_info(db, card_info_request.foreign_into())
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "CardInfo with given key already exists in our records".to_string(),
})
.map(|card_info| ApplicationResponse::Json(card_info.foreign_into()))
}
#[instrument(skip_all)]
pub async fn update_card_info(
state: routes::SessionState,
card_info_request: cards_info_api_types::CardInfoUpdateRequest,
) -> RouterResponse<cards_info_api_types::CardInfoResponse> {
let db = state.store.as_ref();
cards_info::CardsInfoInterface::update_card_info(
db,
card_info_request.card_iin,
card_info_models::UpdateCardInfo {
card_issuer: card_info_request.card_issuer,
card_network: card_info_request.card_network,
card_type: card_info_request.card_type,
card_subtype: card_info_request.card_subtype,
card_issuing_country: card_info_request.card_issuing_country,
bank_code_id: card_info_request.bank_code_id,
bank_code: card_info_request.bank_code,
country_code: card_info_request.country_code,
last_updated: Some(common_utils::date_time::now()),
last_updated_provider: card_info_request.last_updated_provider,
},
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "Card info with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while updating card info")
.map(|card_info| ApplicationResponse::Json(card_info.foreign_into()))
}
#[derive(Debug, MultipartForm)]
pub struct CardsInfoUpdateForm {
#[multipart(limit = "1MB")]
pub file: Bytes,
}
fn parse_cards_bin_csv(
data: &[u8],
) -> csv::Result<Vec<cards_info_api_types::CardInfoUpdateRequest>> {
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: cards_info_api_types::CardInfoUpdateRequest = result?;
id_counter += 1;
record.line_number = Some(id_counter);
records.push(record);
}
Ok(records)
}
pub fn get_cards_bin_records(
form: CardsInfoUpdateForm,
) -> Result<Vec<cards_info_api_types::CardInfoUpdateRequest>, errors::ApiErrorResponse> {
match parse_cards_bin_csv(form.file.data.to_bytes()) {
Ok(records) => Ok(records),
Err(e) => Err(errors::ApiErrorResponse::PreconditionFailed {
message: e.to_string(),
}),
}
}
#[instrument(skip_all)]
pub async fn migrate_cards_info(
state: routes::SessionState,
card_info_records: Vec<cards_info_api_types::CardInfoUpdateRequest>,
) -> RouterResponse<Vec<cards_info_api_types::CardInfoMigrationResponse>> {
let mut result = Vec::new();
for record in card_info_records {
let res = card_info_flow(record.clone(), state.clone()).await;
result.push(cards_info_api_types::CardInfoMigrationResponse::from((
match res {
Ok(ApplicationResponse::Json(response)) => Ok(response),
Err(e) => Err(e.to_string()),
_ => Err("Failed to migrate card info".to_string()),
},
record,
)));
}
Ok(ApplicationResponse::Json(result))
}
pub trait State {}
pub trait TransitionTo<S: State> {}
// Available states for card info migration
pub struct CardInfoFetch;
pub struct CardInfoAdd;
pub struct CardInfoUpdate;
pub struct CardInfoResponse;
impl State for CardInfoFetch {}
impl State for CardInfoAdd {}
impl State for CardInfoUpdate {}
impl State for CardInfoResponse {}
// State transitions for card info migration
impl TransitionTo<CardInfoAdd> for CardInfoFetch {}
impl TransitionTo<CardInfoUpdate> for CardInfoFetch {}
impl TransitionTo<CardInfoResponse> for CardInfoAdd {}
impl TransitionTo<CardInfoResponse> for CardInfoUpdate {}
// Async executor
pub struct CardInfoMigrateExecutor<'a> {
state: &'a routes::SessionState,
record: &'a cards_info_api_types::CardInfoUpdateRequest,
}
impl<'a> CardInfoMigrateExecutor<'a> {
fn new(
state: &'a routes::SessionState,
record: &'a cards_info_api_types::CardInfoUpdateRequest,
) -> Self {
Self { state, record }
}
async fn fetch_card_info(&self) -> RouterResult<Option<card_info_models::CardInfo>> {
let db = self.state.store.as_ref();
let maybe_card_info = db
.get_card_info(&self.record.card_iin)
.await
.change_context(errors::ApiErrorResponse::InvalidCardIin)?;
Ok(maybe_card_info)
}
async fn add_card_info(&self) -> RouterResult<card_info_models::CardInfo> {
let db = self.state.store.as_ref();
let card_info =
cards_info::CardsInfoInterface::add_card_info(db, self.record.clone().foreign_into())
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "CardInfo with given key already exists in our records".to_string(),
})?;
Ok(card_info)
}
async fn update_card_info(&self) -> RouterResult<card_info_models::CardInfo> {
let db = self.state.store.as_ref();
let card_info = cards_info::CardsInfoInterface::update_card_info(
db,
self.record.card_iin.clone(),
card_info_models::UpdateCardInfo {
card_issuer: self.record.card_issuer.clone(),
card_network: self.record.card_network.clone(),
card_type: self.record.card_type.clone(),
card_subtype: self.record.card_subtype.clone(),
card_issuing_country: self.record.card_issuing_country.clone(),
bank_code_id: self.record.bank_code_id.clone(),
bank_code: self.record.bank_code.clone(),
country_code: self.record.country_code.clone(),
last_updated: Some(common_utils::date_time::now()),
last_updated_provider: self.record.last_updated_provider.clone(),
},
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "Card info with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while updating card info")?;
Ok(card_info)
}
}
// Builder
pub struct CardInfoBuilder<S: State> {
state: std::marker::PhantomData<S>,
pub card_info: Option<card_info_models::CardInfo>,
}
impl CardInfoBuilder<CardInfoFetch> {
fn new() -> Self {
Self {
state: std::marker::PhantomData,
card_info: None,
}
}
}
impl CardInfoBuilder<CardInfoFetch> {
fn set_card_info(
self,
card_info: card_info_models::CardInfo,
) -> CardInfoBuilder<CardInfoUpdate> {
CardInfoBuilder {
state: std::marker::PhantomData,
card_info: Some(card_info),
}
}
fn transition(self) -> CardInfoBuilder<CardInfoAdd> {
CardInfoBuilder {
state: std::marker::PhantomData,
card_info: None,
}
}
}
impl CardInfoBuilder<CardInfoUpdate> {
fn set_updated_card_info(
self,
card_info: card_info_models::CardInfo,
) -> CardInfoBuilder<CardInfoResponse> {
CardInfoBuilder {
state: std::marker::PhantomData,
card_info: Some(card_info),
}
}
}
impl CardInfoBuilder<CardInfoAdd> {
fn set_added_card_info(
self,
card_info: card_info_models::CardInfo,
) -> CardInfoBuilder<CardInfoResponse> {
CardInfoBuilder {
state: std::marker::PhantomData,
card_info: Some(card_info),
}
}
}
impl CardInfoBuilder<CardInfoResponse> {
pub fn build(self) -> cards_info_api_types::CardInfoMigrateResponseRecord {
match self.card_info {
Some(card_info) => cards_info_api_types::CardInfoMigrateResponseRecord {
card_iin: Some(card_info.card_iin),
card_issuer: card_info.card_issuer,
card_network: card_info.card_network.map(|cn| cn.to_string()),
card_type: card_info.card_type,
card_sub_type: card_info.card_subtype,
card_issuing_country: card_info.card_issuing_country,
},
None => cards_info_api_types::CardInfoMigrateResponseRecord {
card_iin: None,
card_issuer: None,
card_network: None,
card_type: None,
card_sub_type: None,
card_issuing_country: None,
},
}
}
}
async fn card_info_flow(
record: cards_info_api_types::CardInfoUpdateRequest,
state: routes::SessionState,
) -> RouterResponse<cards_info_api_types::CardInfoMigrateResponseRecord> {
let builder = CardInfoBuilder::new();
let executor = CardInfoMigrateExecutor::new(&state, &record);
let fetched_card_info_details = executor.fetch_card_info().await?;
let builder = match fetched_card_info_details {
Some(card_info) => {
let builder = builder.set_card_info(card_info);
let updated_card_info = executor.update_card_info().await?;
builder.set_updated_card_info(updated_card_info)
}
None => {
let builder = builder.transition();
let added_card_info = executor.add_card_info().await?;
builder.set_added_card_info(added_card_info)
}
};
Ok(ApplicationResponse::Json(builder.build()))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/unified_authentication_service.rs | crates/router/src/core/unified_authentication_service.rs | pub mod types;
use std::str::FromStr;
use common_utils::ext_traits::StringExt;
pub mod utils;
#[cfg(feature = "v1")]
use api_models::authentication::{
AuthenticationEligibilityCheckData, AuthenticationEligibilityCheckRequest,
AuthenticationEligibilityCheckResponse, AuthenticationEligibilityCheckResponseData,
AuthenticationEligibilityRequest, AuthenticationEligibilityResponse,
AuthenticationRetrieveEligibilityCheckRequest, AuthenticationRetrieveEligibilityCheckResponse,
AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest, AuthenticationSyncResponse,
ClickToPayEligibilityCheckResponseData,
};
use api_models::{
authentication::{
AcquirerDetails, AuthenticationAuthenticateRequest, AuthenticationAuthenticateResponse,
AuthenticationCreateRequest, AuthenticationResponse, AuthenticationSdkNextAction,
AuthenticationSessionTokenRequest,
},
payments::{self, CustomerDetails},
};
#[cfg(feature = "v1")]
use common_utils::{errors::CustomResult, ext_traits::ValueExt, types::AmountConvertor};
use diesel_models::authentication::Authentication;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse,
ext_traits::OptionExt,
payment_method_data,
router_request_types::{
authentication::{MessageCategory, PreAuthenticationData},
unified_authentication_service::{
AuthenticationInfo, PaymentDetails, ServiceSessionIds, ThreeDsMetaData,
TransactionDetails, UasAuthenticationRequestData, UasConfirmationRequestData,
UasPostAuthenticationRequestData, UasPreAuthenticationRequestData,
},
BrowserInformation,
},
types::{
UasAuthenticationRouterData, UasPostAuthenticationRouterData,
UasPreAuthenticationRouterData,
},
};
use masking::{ExposeInterface, PeekInterface};
use super::{
errors::{RouterResponse, RouterResult},
payments::helpers::MerchantConnectorAccountType,
};
use crate::{
consts,
core::{
authentication::utils as auth_utils,
errors::utils::StorageErrorExt,
payment_methods,
payments::{helpers, validate_customer_details_for_click_to_pay},
unified_authentication_service::types::{
ClickToPay, ExternalAuthentication, UnifiedAuthenticationService,
UNIFIED_AUTHENTICATION_SERVICE,
},
utils as core_utils,
},
db::domain,
routes::SessionState,
services::AuthFlow,
types::{domain::types::AsyncLift, transformers::ForeignTryFrom},
};
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl UnifiedAuthenticationService for ClickToPay {
fn get_pre_authentication_request_data(
_payment_method_data: Option<&domain::PaymentMethodData>,
service_details: Option<payments::CtpServiceDetails>,
amount: common_utils::types::MinorUnit,
currency: Option<common_enums::Currency>,
merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>,
billing_address: Option<&hyperswitch_domain_models::address::Address>,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<UasPreAuthenticationRequestData> {
let domain_service_details = hyperswitch_domain_models::router_request_types::unified_authentication_service::CtpServiceDetails {
service_session_ids: Some(ServiceSessionIds {
merchant_transaction_id: service_details
.as_ref()
.and_then(|details| details.merchant_transaction_id.clone()),
correlation_id: service_details
.as_ref()
.and_then(|details| details.correlation_id.clone()),
x_src_flow_id: service_details
.as_ref()
.and_then(|details| details.x_src_flow_id.clone()),
}),
payment_details: None,
};
let transaction_details = TransactionDetails {
amount: Some(amount),
currency,
device_channel: None,
message_category: None,
force_3ds_challenge: None,
psd2_sca_exemption_type: None,
};
let authentication_info = Some(AuthenticationInfo {
authentication_type: None,
authentication_reasons: None,
consent_received: false, // This is not relevant in this flow so keeping it as false
is_authenticated: false, // This is not relevant in this flow so keeping it as false
locale: None,
supported_card_brands: None,
encrypted_payload: service_details
.as_ref()
.and_then(|details| details.encrypted_payload.clone()),
});
Ok(UasPreAuthenticationRequestData {
service_details: Some(domain_service_details),
transaction_details: Some(transaction_details),
payment_details: None,
authentication_info,
merchant_details: merchant_details.cloned(),
billing_address: billing_address.cloned(),
acquirer_bin,
acquirer_merchant_id,
})
}
async fn pre_authentication(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: Option<&common_utils::id_type::PaymentId>,
payment_method_data: Option<&domain::PaymentMethodData>,
payment_method_type: Option<common_enums::PaymentMethodType>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
authentication_id: &common_utils::id_type::AuthenticationId,
payment_method: common_enums::PaymentMethod,
amount: common_utils::types::MinorUnit,
currency: Option<common_enums::Currency>,
service_details: Option<payments::CtpServiceDetails>,
merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>,
billing_address: Option<&hyperswitch_domain_models::address::Address>,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
) -> RouterResult<UasPreAuthenticationRouterData> {
let pre_authentication_data = Self::get_pre_authentication_request_data(
payment_method_data,
service_details,
amount,
currency,
merchant_details,
billing_address,
acquirer_bin,
acquirer_merchant_id,
payment_method_type,
)?;
let pre_auth_router_data: UasPreAuthenticationRouterData =
utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
merchant_id.clone(),
None,
pre_authentication_data,
merchant_connector_account,
Some(authentication_id.to_owned()),
payment_id.cloned(),
)?;
Box::pin(utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
pre_auth_router_data,
))
.await
}
async fn post_authentication(
state: &SessionState,
_business_profile: &domain::Profile,
payment_id: Option<&common_utils::id_type::PaymentId>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
authentication_id: &common_utils::id_type::AuthenticationId,
payment_method: common_enums::PaymentMethod,
merchant_id: &common_utils::id_type::MerchantId,
_authentication: Option<&hyperswitch_domain_models::authentication::Authentication>,
) -> RouterResult<UasPostAuthenticationRouterData> {
let post_authentication_data = UasPostAuthenticationRequestData {
threeds_server_transaction_id: None,
};
let post_auth_router_data: UasPostAuthenticationRouterData =
utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
merchant_id.clone(),
None,
post_authentication_data,
merchant_connector_account,
Some(authentication_id.to_owned()),
payment_id.cloned(),
)?;
utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
post_auth_router_data,
)
.await
}
async fn confirmation(
state: &SessionState,
authentication_id: Option<&common_utils::id_type::AuthenticationId>,
currency: Option<common_enums::Currency>,
status: common_enums::AttemptStatus,
service_details: Option<payments::CtpServiceDetails>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
payment_method: common_enums::PaymentMethod,
net_amount: common_utils::types::MinorUnit,
payment_id: Option<&common_utils::id_type::PaymentId>,
merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<()> {
let authentication_id = authentication_id
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Missing authentication id in tracker")?;
let currency = currency.ok_or(ApiErrorResponse::MissingRequiredField {
field_name: "currency",
})?;
let current_time = common_utils::date_time::date_as_yyyymmddthhmmssmmmz()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get current time")?;
let payment_attempt_status = status;
let (checkout_event_status, confirmation_reason) =
utils::get_checkout_event_status_and_reason(payment_attempt_status);
let click_to_pay_details = service_details.clone();
let authentication_confirmation_data = UasConfirmationRequestData {
x_src_flow_id: click_to_pay_details
.as_ref()
.and_then(|details| details.x_src_flow_id.clone()),
transaction_amount: net_amount,
transaction_currency: currency,
checkout_event_type: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented
checkout_event_status: checkout_event_status.clone(),
confirmation_status: checkout_event_status.clone(),
confirmation_reason,
confirmation_timestamp: Some(current_time),
network_authorization_code: Some("01".to_string()), // hardcoded to '01' since only authorise flow is implemented
network_transaction_identifier: Some("mastercard".to_string()), // hardcoded to 'mastercard' since only mastercard has confirmation flow requirement
correlation_id: click_to_pay_details
.clone()
.and_then(|details| details.correlation_id),
merchant_transaction_id: click_to_pay_details
.and_then(|details| details.merchant_transaction_id),
};
let authentication_confirmation_router_data : hyperswitch_domain_models::types::UasAuthenticationConfirmationRouterData = utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
merchant_id.clone(),
None,
authentication_confirmation_data,
merchant_connector_account,
Some(authentication_id.to_owned()),
payment_id.cloned(),
)?;
utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
authentication_confirmation_router_data,
)
.await
.ok(); // marking this as .ok() since this is not a required step at our end for completing the transaction
Ok(())
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl UnifiedAuthenticationService for ExternalAuthentication {
fn get_pre_authentication_request_data(
payment_method_data: Option<&domain::PaymentMethodData>,
_service_details: Option<payments::CtpServiceDetails>,
amount: common_utils::types::MinorUnit,
currency: Option<common_enums::Currency>,
merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>,
billing_address: Option<&hyperswitch_domain_models::address::Address>,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<UasPreAuthenticationRequestData> {
let payment_method_data = payment_method_data
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("payment_method_data is missing")?;
let payment_details =
if let payment_method_data::PaymentMethodData::Card(card) = payment_method_data {
Some(PaymentDetails {
pan: card.card_number.clone(),
digital_card_id: None,
payment_data_type: payment_method_type,
encrypted_src_card_details: None,
card_expiry_month: card.card_exp_month.clone(),
card_expiry_year: card.card_exp_year.clone(),
cardholder_name: card.card_holder_name.clone(),
card_token_number: None,
account_type: payment_method_type,
card_cvc: Some(card.card_cvc.clone()),
})
} else {
None
};
let transaction_details = TransactionDetails {
amount: Some(amount),
currency,
device_channel: None,
message_category: None,
force_3ds_challenge: None,
psd2_sca_exemption_type: None,
};
Ok(UasPreAuthenticationRequestData {
service_details: None,
transaction_details: Some(transaction_details),
payment_details,
authentication_info: None,
merchant_details: merchant_details.cloned(),
billing_address: billing_address.cloned(),
acquirer_bin,
acquirer_merchant_id,
})
}
#[allow(clippy::too_many_arguments)]
async fn pre_authentication(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: Option<&common_utils::id_type::PaymentId>,
payment_method_data: Option<&domain::PaymentMethodData>,
payment_method_type: Option<common_enums::PaymentMethodType>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
authentication_id: &common_utils::id_type::AuthenticationId,
payment_method: common_enums::PaymentMethod,
amount: common_utils::types::MinorUnit,
currency: Option<common_enums::Currency>,
service_details: Option<payments::CtpServiceDetails>,
merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>,
billing_address: Option<&hyperswitch_domain_models::address::Address>,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
) -> RouterResult<UasPreAuthenticationRouterData> {
let pre_authentication_data = Self::get_pre_authentication_request_data(
payment_method_data,
service_details,
amount,
currency,
merchant_details,
billing_address,
acquirer_bin,
acquirer_merchant_id,
payment_method_type,
)?;
let pre_auth_router_data: UasPreAuthenticationRouterData =
utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
merchant_id.clone(),
None,
pre_authentication_data,
merchant_connector_account,
Some(authentication_id.to_owned()),
payment_id.cloned(),
)?;
Box::pin(utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
pre_auth_router_data,
))
.await
}
fn get_authentication_request_data(
browser_details: Option<BrowserInformation>,
amount: Option<common_utils::types::MinorUnit>,
currency: Option<common_enums::Currency>,
message_category: MessageCategory,
device_channel: payments::DeviceChannel,
authentication: hyperswitch_domain_models::authentication::Authentication,
return_url: Option<String>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
webhook_url: String,
force_3ds_challenge: Option<bool>,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
) -> RouterResult<UasAuthenticationRequestData> {
Ok(UasAuthenticationRequestData {
browser_details,
transaction_details: TransactionDetails {
amount,
currency,
device_channel: Some(device_channel),
message_category: Some(message_category),
force_3ds_challenge,
psd2_sca_exemption_type,
},
pre_authentication_data: PreAuthenticationData {
threeds_server_transaction_id: authentication.threeds_server_transaction_id.ok_or(
ApiErrorResponse::MissingRequiredField {
field_name: "authentication.threeds_server_transaction_id",
},
)?,
message_version: authentication.message_version.ok_or(
ApiErrorResponse::MissingRequiredField {
field_name: "authentication.message_version",
},
)?,
acquirer_bin: authentication.acquirer_bin,
acquirer_merchant_id: authentication.acquirer_merchant_id,
acquirer_country_code: authentication.acquirer_country_code,
connector_metadata: authentication.connector_metadata,
},
return_url,
sdk_information,
email,
threeds_method_comp_ind,
webhook_url,
})
}
#[allow(clippy::too_many_arguments)]
async fn authentication(
state: &SessionState,
business_profile: &domain::Profile,
payment_method: &common_enums::PaymentMethod,
browser_details: Option<BrowserInformation>,
amount: Option<common_utils::types::MinorUnit>,
currency: Option<common_enums::Currency>,
message_category: MessageCategory,
device_channel: payments::DeviceChannel,
authentication: hyperswitch_domain_models::authentication::Authentication,
return_url: Option<String>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
webhook_url: String,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
payment_id: Option<common_utils::id_type::PaymentId>,
force_3ds_challenge: Option<bool>,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
) -> RouterResult<UasAuthenticationRouterData> {
let authentication_data =
<Self as UnifiedAuthenticationService>::get_authentication_request_data(
browser_details,
amount,
currency,
message_category,
device_channel,
authentication.clone(),
return_url,
sdk_information,
threeds_method_comp_ind,
email,
webhook_url,
force_3ds_challenge,
psd2_sca_exemption_type,
)?;
let auth_router_data: UasAuthenticationRouterData = utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method.to_owned(),
business_profile.merchant_id.clone(),
None,
authentication_data,
merchant_connector_account,
Some(authentication.authentication_id.to_owned()),
payment_id,
)?;
Box::pin(utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
auth_router_data,
))
.await
}
fn get_post_authentication_request_data(
authentication: Option<hyperswitch_domain_models::authentication::Authentication>,
) -> RouterResult<UasPostAuthenticationRequestData> {
Ok(UasPostAuthenticationRequestData {
// authentication.threeds_server_transaction_id is mandatory for post-authentication in ExternalAuthentication
threeds_server_transaction_id: Some(
authentication
.and_then(|auth| auth.threeds_server_transaction_id)
.ok_or(ApiErrorResponse::MissingRequiredField {
field_name: "authentication.threeds_server_transaction_id",
})?,
),
})
}
async fn post_authentication(
state: &SessionState,
business_profile: &domain::Profile,
payment_id: Option<&common_utils::id_type::PaymentId>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
authentication_id: &common_utils::id_type::AuthenticationId,
payment_method: common_enums::PaymentMethod,
_merchant_id: &common_utils::id_type::MerchantId,
authentication: Option<&hyperswitch_domain_models::authentication::Authentication>,
) -> RouterResult<UasPostAuthenticationRouterData> {
let authentication_data =
<Self as UnifiedAuthenticationService>::get_post_authentication_request_data(
authentication.cloned(),
)?;
let auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
business_profile.merchant_id.clone(),
None,
authentication_data,
merchant_connector_account,
Some(authentication_id.clone()),
payment_id.cloned(),
)?;
utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
auth_router_data,
)
.await
}
}
#[allow(clippy::too_many_arguments)]
pub async fn create_new_authentication(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
authentication_connector: Option<String>,
profile_id: common_utils::id_type::ProfileId,
payment_id: Option<common_utils::id_type::PaymentId>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
authentication_id: &common_utils::id_type::AuthenticationId,
service_details: Option<payments::CtpServiceDetails>,
authentication_status: common_enums::AuthenticationStatus,
network_token: Option<payment_method_data::NetworkTokenData>,
organization_id: common_utils::id_type::OrganizationId,
force_3ds_challenge: Option<bool>,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
acquirer_bin: Option<String>,
acquirer_merchant_id: Option<String>,
acquirer_country_code: Option<String>,
amount: Option<common_utils::types::MinorUnit>,
currency: Option<common_enums::Currency>,
return_url: Option<String>,
profile_acquirer_id: Option<common_utils::id_type::ProfileAcquirerId>,
customer_details: Option<common_utils::encryption::Encryption>,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<hyperswitch_domain_models::authentication::Authentication> {
let service_details_value = service_details
.map(serde_json::to_value)
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to parse service details into json value while inserting to DB",
)?;
let authentication_client_secret = Some(common_utils::generate_id_with_default_len(&format!(
"{}_secret",
authentication_id.get_string_repr()
)));
let key_manager_state = (state).into();
let current_time = common_utils::date_time::now();
let new_authentication = hyperswitch_domain_models::authentication::Authentication {
authentication_id: authentication_id.clone(),
merchant_id,
authentication_connector,
connector_authentication_id: None,
authentication_data: None,
payment_method_id: "".to_string(),
authentication_type: None,
authentication_status,
authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused,
created_at: current_time,
modified_at: current_time,
error_message: None,
error_code: None,
connector_metadata: None,
maximum_supported_version: None,
threeds_server_transaction_id: None,
cavv: None,
authentication_flow_type: None,
message_version: None,
eci: network_token.and_then(|data| data.eci),
trans_status: None,
acquirer_bin,
acquirer_merchant_id,
three_ds_method_data: None,
three_ds_method_url: None,
acs_url: None,
challenge_request: None,
acs_reference_number: None,
acs_trans_id: None,
acs_signed_content: None,
profile_id,
payment_id,
merchant_connector_id,
ds_trans_id: None,
directory_server_id: None,
acquirer_country_code,
organization_id,
mcc: None,
amount,
currency,
billing_country: None,
shipping_country: None,
issuer_country: None,
earliest_supported_version: None,
latest_supported_version: None,
platform: None,
device_type: None,
device_brand: None,
device_os: None,
device_display: None,
browser_name: None,
browser_version: None,
issuer_id: None,
scheme_name: None,
exemption_requested: Some(psd2_sca_exemption_type.is_some()),
exemption_accepted: None,
service_details: service_details_value,
authentication_client_secret,
force_3ds_challenge,
psd2_sca_exemption_type,
return_url,
billing_address: None,
shipping_address: None,
browser_info: None,
email: None,
profile_acquirer_id,
challenge_code: None,
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
challenge_request_key: None,
customer_details,
merchant_country_code: None,
};
state
.store
.insert_authentication(&key_manager_state, merchant_key_store, new_authentication)
.await
.to_duplicate_response(ApiErrorResponse::GenericDuplicateError {
message: format!(
"Authentication with authentication_id {} already exists",
authentication_id.get_string_repr()
),
})
}
// Modular authentication
#[cfg(feature = "v1")]
pub async fn authentication_create_core(
state: SessionState,
platform: domain::Platform,
req: AuthenticationCreateRequest,
) -> RouterResponse<AuthenticationResponse> {
let db = &*state.store;
let merchant_account = platform.get_processor().get_account();
let merchant_id = merchant_account.get_id();
let key_manager_state = (&state).into();
let profile_id = core_utils::get_profile_id_from_business_details(
None,
None,
platform.get_processor(),
req.profile_id.as_ref(),
db,
true,
)
.await?;
let business_profile = db
.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id)
.await
.to_not_found_response(ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let organization_id = merchant_account.organization_id.clone();
let authentication_id = common_utils::id_type::AuthenticationId::generate_authentication_id(
consts::AUTHENTICATION_ID_PREFIX,
);
let force_3ds_challenge = Some(
req.force_3ds_challenge
.unwrap_or(business_profile.force_3ds_challenge),
);
// Priority logic: First check req.acquirer_details, then fallback to profile_acquirer_id lookup
let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) =
if let Some(acquirer_details) = &req.acquirer_details {
// Priority 1: Use acquirer_details from request if present
(
acquirer_details.acquirer_bin.clone(),
acquirer_details.acquirer_merchant_id.clone(),
acquirer_details.merchant_country_code.clone(),
)
} else {
// Priority 2: Fallback to profile_acquirer_id lookup
let acquirer_details = req.profile_acquirer_id.clone().and_then(|acquirer_id| {
business_profile
.acquirer_config_map
.and_then(|acquirer_config_map| {
acquirer_config_map.0.get(&acquirer_id).cloned()
})
});
acquirer_details
.as_ref()
.map(|details| {
(
Some(details.acquirer_bin.clone()),
Some(details.acquirer_assigned_merchant_id.clone()),
business_profile
.merchant_country_code
.map(|code| code.get_country_code().to_owned()),
)
})
.unwrap_or((None, None, None))
};
let customer_details = req
.customer_details
.clone()
.async_lift(|customer_details| async {
domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(Authentication),
domain::types::CryptoOperation::EncryptOptional(
customer_details
.map(|details| {
common_utils::ext_traits::Encode::encode_to_value(&details)
.map(masking::Secret::<serde_json::Value>::new)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable(
"Unable to encode customer details to serde_json::Value",
)
})
.transpose()?,
),
common_utils::types::keymanager::Identifier::Merchant(
platform.get_processor().get_key_store().merchant_id.clone(),
),
platform.get_processor().get_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")
})
.await?;
let new_authentication = create_new_authentication(
&state,
merchant_id.clone(),
req.authentication_connector
.map(|connector| connector.to_string()),
profile_id.clone(),
None,
None,
&authentication_id,
None,
common_enums::AuthenticationStatus::Started,
None,
organization_id,
force_3ds_challenge,
req.psd2_sca_exemption_type,
acquirer_bin,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/card_testing_guard.rs | crates/router/src/core/card_testing_guard.rs | pub mod utils;
use crate::core::errors;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/apple_pay_certificates_migration.rs | crates/router/src/core/apple_pay_certificates_migration.rs | use api_models::apple_pay_certificates_migration;
use common_utils::{errors::CustomResult, type_name, types::keymanager::Identifier};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use super::{
errors::{self, StorageErrorExt},
payments::helpers,
};
use crate::{
routes::SessionState,
services::{self, logger},
types::{domain::types as domain_types, storage},
};
#[cfg(feature = "v1")]
pub async fn apple_pay_certificates_migration(
state: SessionState,
req: &apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest,
) -> CustomResult<
services::ApplicationResponse<
apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse,
>,
errors::ApiErrorResponse,
> {
let db = state.store.as_ref();
let merchant_id_list = &req.merchant_ids;
let mut migration_successful_merchant_ids = vec![];
let mut migration_failed_merchant_ids = vec![];
for merchant_id in merchant_id_list {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_connector_accounts = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
merchant_id,
true,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let mut mca_to_update = vec![];
for connector_account in merchant_connector_accounts {
let connector_apple_pay_metadata =
helpers::get_applepay_metadata(connector_account.clone().metadata)
.map_err(|error| {
logger::error!(
"Apple pay metadata parsing failed for {:?} in certificates migrations api {:?}",
connector_account.clone().connector_name,
error
)
})
.ok();
if let Some(apple_pay_metadata) = connector_apple_pay_metadata {
let encrypted_apple_pay_metadata = domain_types::crypto_operation(
&(&state).into(),
type_name!(storage::MerchantConnectorAccount),
domain_types::CryptoOperation::Encrypt(Secret::new(
serde_json::to_value(apple_pay_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize apple pay metadata as JSON")?,
)),
Identifier::Merchant(merchant_id.clone()),
key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt connector apple pay metadata")?;
let updated_mca =
storage::MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {
connector_wallets_details: encrypted_apple_pay_metadata,
};
mca_to_update.push((connector_account, updated_mca.into()));
}
}
let merchant_connector_accounts_update = db
.update_multiple_merchant_connector_accounts(mca_to_update)
.await;
match merchant_connector_accounts_update {
Ok(_) => {
logger::debug!(
"Merchant connector accounts updated for merchant id {merchant_id:?}"
);
migration_successful_merchant_ids.push(merchant_id.clone());
}
Err(error) => {
logger::debug!(
"Merchant connector accounts update failed with error {error} for merchant id {merchant_id:?}");
migration_failed_merchant_ids.push(merchant_id.clone());
}
};
}
Ok(services::api::ApplicationResponse::Json(
apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse {
migration_successful: migration_successful_merchant_ids,
migration_failed: migration_failed_merchant_ids,
},
))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/webhooks.rs | crates/router/src/core/webhooks.rs | #[cfg(feature = "v1")]
pub mod incoming;
#[cfg(feature = "v2")]
mod incoming_v2;
#[cfg(feature = "v1")]
mod network_tokenization_incoming;
#[cfg(feature = "v1")]
mod outgoing;
#[cfg(feature = "v2")]
mod outgoing_v2;
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
pub mod recovery_incoming;
pub mod types;
pub mod utils;
#[cfg(feature = "olap")]
pub mod webhook_events;
#[cfg(feature = "v1")]
pub(crate) use self::{
incoming::{incoming_webhooks_wrapper, network_token_incoming_webhooks_wrapper},
outgoing::{
create_event_and_trigger_outgoing_webhook, get_outgoing_webhook_request,
trigger_webhook_and_raise_event,
},
};
#[cfg(feature = "v2")]
pub(crate) use self::{
incoming_v2::incoming_webhooks_wrapper, outgoing_v2::create_event_and_trigger_outgoing_webhook,
};
const MERCHANT_ID: &str = "merchant_id";
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/user_role.rs | crates/router/src/core/user_role.rs | use std::{
collections::{HashMap, HashSet},
sync::LazyLock,
};
use api_models::{
user as user_api,
user_role::{self as user_role_api, role as role_api},
};
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
organization::OrganizationBridge,
user_role::UserRoleUpdate,
};
use error_stack::{report, ResultExt};
use masking::Secret;
use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResponse},
db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},
routes::{app::ReqState, SessionState},
services::{
authentication as auth,
authorization::{
info,
permission_groups::{ParentGroupExt, PermissionGroupExt},
roles,
},
ApplicationResponse,
},
types::domain,
utils,
};
pub mod role;
use common_enums::{EntityType, ParentGroup, PermissionGroup};
use strum::IntoEnumIterator;
// TODO: To be deprecated
pub async fn get_authorization_info_with_groups(
_state: SessionState,
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
Ok(ApplicationResponse::Json(
user_role_api::AuthorizationInfoResponse(
info::get_group_authorization_info()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No visible groups found")?
.into_iter()
.map(user_role_api::AuthorizationInfo::Group)
.collect(),
),
))
}
pub async fn get_authorization_info_with_group_tag(
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
static GROUPS_WITH_PARENT_TAGS: LazyLock<Vec<user_role_api::ParentInfo>> =
LazyLock::new(|| {
PermissionGroup::iter()
.map(|group| (group.parent(), group))
.fold(
HashMap::new(),
|mut acc: HashMap<ParentGroup, Vec<PermissionGroup>>, (key, value)| {
acc.entry(key).or_default().push(value);
acc
},
)
.into_iter()
.filter_map(|(name, value)| {
Some(user_role_api::ParentInfo {
name: name.clone(),
description: info::get_parent_group_description(name)?,
groups: value,
})
})
.collect()
});
Ok(ApplicationResponse::Json(
user_role_api::AuthorizationInfoResponse(
GROUPS_WITH_PARENT_TAGS
.iter()
.cloned()
.map(user_role_api::AuthorizationInfo::GroupWithTag)
.collect(),
),
))
}
pub async fn get_parent_group_info(
state: SessionState,
user_from_token: auth::UserFromToken,
request: role_api::GetParentGroupsInfoQueryParams,
) -> UserResponse<Vec<role_api::ParentGroupDescription>> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.to_not_found_response(UserErrors::InvalidRoleId)?;
let entity_type = request
.entity_type
.unwrap_or_else(|| role_info.get_entity_type());
if role_info.get_entity_type() < entity_type {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"Invalid operation, requestor entity type = {} cannot access entity type = {}",
role_info.get_entity_type(),
entity_type
));
}
let parent_groups =
ParentGroup::get_descriptions_for_groups(entity_type, PermissionGroup::iter().collect())
.unwrap_or_default()
.into_iter()
.map(
|(parent_group, description)| role_api::ParentGroupDescription {
name: parent_group.clone(),
description,
scopes: PermissionGroup::iter()
.filter_map(|group| {
(group.parent() == parent_group).then_some(group.scope())
})
// TODO: Remove this hashset conversion when merchant access
// and organization access groups are removed
.collect::<HashSet<_>>()
.into_iter()
.collect(),
},
)
.collect::<Vec<_>>();
Ok(ApplicationResponse::Json(parent_groups))
}
pub async fn update_user_role(
state: SessionState,
user_from_token: auth::UserFromToken,
req: user_role_api::UpdateUserRoleRequest,
_req_state: ReqState,
) -> UserResponse<()> {
let role_info = roles::RoleInfo::from_role_id_in_lineage(
&state,
&req.role_id,
&user_from_token.merchant_id,
&user_from_token.org_id,
&user_from_token.profile_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.to_not_found_response(UserErrors::InvalidRoleId)?;
if !role_info.is_updatable() {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable(format!("User role cannot be updated to {}", req.role_id));
}
let user_to_be_updated =
utils::user::get_user_from_db_by_email(&state, domain::UserEmail::try_from(req.email)?)
.await
.to_not_found_response(UserErrors::InvalidRoleOperation)
.attach_printable("User not found in our records".to_string())?;
if user_from_token.user_id == user_to_be_updated.get_user_id() {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("User Changing their own role");
}
let updator_role = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
let mut is_updated = false;
let v2_user_role_to_be_updated = match state
.global_store
.find_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
&user_from_token.merchant_id,
&user_from_token.profile_id,
UserRoleVersion::V2,
)
.await
{
Ok(user_role) => Some(user_role),
Err(e) => {
if e.current_context().is_db_not_found() {
None
} else {
return Err(UserErrors::InternalServerError.into());
}
}
};
if let Some(user_role) = v2_user_role_to_be_updated {
let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_role.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
if !role_to_be_updated.is_updatable() {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"User role cannot be updated from {}",
role_to_be_updated.get_role_id()
));
}
if role_info.get_entity_type() != role_to_be_updated.get_entity_type() {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}",
role_to_be_updated.get_entity_type(),
role_info.get_entity_type(),
));
}
if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"Invalid operation, update requestor = {} cannot update target = {}",
updator_role.get_entity_type(),
role_to_be_updated.get_entity_type()
));
}
state
.global_store
.update_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
Some(&user_from_token.merchant_id),
Some(&user_from_token.profile_id),
UserRoleUpdate::UpdateRole {
role_id: req.role_id.clone(),
modified_by: user_from_token.user_id.clone(),
},
UserRoleVersion::V2,
)
.await
.change_context(UserErrors::InternalServerError)?;
is_updated = true;
}
let v1_user_role_to_be_updated = match state
.global_store
.find_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
&user_from_token.merchant_id,
&user_from_token.profile_id,
UserRoleVersion::V1,
)
.await
{
Ok(user_role) => Some(user_role),
Err(e) => {
if e.current_context().is_db_not_found() {
None
} else {
return Err(UserErrors::InternalServerError.into());
}
}
};
if let Some(user_role) = v1_user_role_to_be_updated {
let role_to_be_updated = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_role.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
if !role_to_be_updated.is_updatable() {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"User role cannot be updated from {}",
role_to_be_updated.get_role_id()
));
}
if role_info.get_entity_type() != role_to_be_updated.get_entity_type() {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"Upgrade and downgrade of roles is not allowed, user_entity_type = {} req_entity_type = {}",
role_to_be_updated.get_entity_type(),
role_info.get_entity_type(),
));
}
if updator_role.get_entity_type() < role_to_be_updated.get_entity_type() {
return Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
"Invalid operation, update requestor = {} cannot update target = {}",
updator_role.get_entity_type(),
role_to_be_updated.get_entity_type()
));
}
state
.global_store
.update_user_role_by_user_id_and_lineage(
user_to_be_updated.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
Some(&user_from_token.merchant_id),
Some(&user_from_token.profile_id),
UserRoleUpdate::UpdateRole {
role_id: req.role_id.clone(),
modified_by: user_from_token.user_id,
},
UserRoleVersion::V1,
)
.await
.change_context(UserErrors::InternalServerError)?;
is_updated = true;
}
if !is_updated {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("User with given email is not found in the organization")?;
}
auth::blacklist::insert_user_in_blacklist(&state, user_to_be_updated.get_user_id()).await?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn accept_invitations_v2(
state: SessionState,
user_from_token: auth::UserFromToken,
req: user_role_api::AcceptInvitationsV2Request,
) -> UserResponse<()> {
let lineages = futures::future::try_join_all(req.into_iter().map(|entity| {
utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite(
&state,
&user_from_token.user_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
entity.entity_id,
entity.entity_type,
)
}))
.await?
.into_iter()
.flatten()
.collect::<Vec<_>>();
let update_results = futures::future::join_all(lineages.iter().map(
|(org_id, merchant_id, profile_id)| async {
let (update_v1_result, update_v2_result) =
utils::user_role::update_v1_and_v2_user_roles_in_db(
&state,
user_from_token.user_id.as_str(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id,
merchant_id.as_ref(),
profile_id.as_ref(),
UserRoleUpdate::UpdateStatus {
status: UserStatus::Active,
modified_by: user_from_token.user_id.clone(),
},
)
.await;
if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
|| update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
{
Err(report!(UserErrors::InternalServerError))
} else {
Ok(())
}
},
))
.await;
if update_results.is_empty() || update_results.iter().all(Result::is_err) {
return Err(UserErrors::MerchantIdNotFound.into());
}
Ok(ApplicationResponse::StatusOk)
}
pub async fn accept_invitations_pre_auth(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
req: user_role_api::AcceptInvitationsPreAuthRequest,
) -> UserResponse<user_api::TokenResponse> {
let lineages = futures::future::try_join_all(req.into_iter().map(|entity| {
utils::user_role::get_lineage_for_user_id_and_entity_for_accepting_invite(
&state,
&user_token.user_id,
user_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
entity.entity_id,
entity.entity_type,
)
}))
.await?
.into_iter()
.flatten()
.collect::<Vec<_>>();
let update_results = futures::future::join_all(lineages.iter().map(
|(org_id, merchant_id, profile_id)| async {
let (update_v1_result, update_v2_result) =
utils::user_role::update_v1_and_v2_user_roles_in_db(
&state,
user_token.user_id.as_str(),
user_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id,
merchant_id.as_ref(),
profile_id.as_ref(),
UserRoleUpdate::UpdateStatus {
status: UserStatus::Active,
modified_by: user_token.user_id.clone(),
},
)
.await;
if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
|| update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
{
Err(report!(UserErrors::InternalServerError))
} else {
Ok(())
}
},
))
.await;
if update_results.is_empty() || update_results.iter().all(Result::is_err) {
return Err(UserErrors::MerchantIdNotFound.into());
}
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(user_token.user_id.as_str())
.await
.change_context(UserErrors::InternalServerError)?
.into();
let current_flow =
domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?;
let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
let token = next_flow.get_token(&state).await?;
let response = user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
};
auth::cookies::set_cookie_response(response, token)
}
pub async fn delete_user_role(
state: SessionState,
user_from_token: auth::UserFromToken,
request: user_role_api::DeleteUserRoleRequest,
_req_state: ReqState,
) -> UserResponse<()> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_email(&domain::UserEmail::from_pii_email(request.email)?)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::InvalidRoleOperation)
.attach_printable("User not found in our records")
} else {
e.change_context(UserErrors::InternalServerError)
}
})?
.into();
if user_from_db.get_user_id() == user_from_token.user_id {
return Err(report!(UserErrors::InvalidDeleteOperation))
.attach_printable("User deleting himself");
}
let deletion_requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
let mut user_role_deleted_flag = false;
// Find in V2
let user_role_v2 = match state
.global_store
.find_user_role_by_user_id_and_lineage(
user_from_db.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
&user_from_token.merchant_id,
&user_from_token.profile_id,
UserRoleVersion::V2,
)
.await
{
Ok(user_role) => Some(user_role),
Err(e) => {
if e.current_context().is_db_not_found() {
None
} else {
return Err(UserErrors::InternalServerError.into());
}
}
};
if let Some(role_to_be_deleted) = user_role_v2 {
let target_role_info = roles::RoleInfo::from_role_id_in_lineage(
&state,
&role_to_be_deleted.role_id,
&user_from_token.merchant_id,
&user_from_token.org_id,
&user_from_token.profile_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
if !target_role_info.is_deletable() {
return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!(
"Invalid operation, role_id = {} is not deletable",
role_to_be_deleted.role_id
));
}
if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() {
return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!(
"Invalid operation, deletion requestor = {} cannot delete target = {}",
deletion_requestor_role_info.get_entity_type(),
target_role_info.get_entity_type()
));
}
user_role_deleted_flag = true;
state
.global_store
.delete_user_role_by_user_id_and_lineage(
user_from_db.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
&user_from_token.merchant_id,
&user_from_token.profile_id,
UserRoleVersion::V2,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while deleting user role")?;
}
// Find in V1
let user_role_v1 = match state
.global_store
.find_user_role_by_user_id_and_lineage(
user_from_db.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
&user_from_token.merchant_id,
&user_from_token.profile_id,
UserRoleVersion::V1,
)
.await
{
Ok(user_role) => Some(user_role),
Err(e) => {
if e.current_context().is_db_not_found() {
None
} else {
return Err(UserErrors::InternalServerError.into());
}
}
};
if let Some(role_to_be_deleted) = user_role_v1 {
let target_role_info = roles::RoleInfo::from_role_id_in_lineage(
&state,
&role_to_be_deleted.role_id,
&user_from_token.merchant_id,
&user_from_token.org_id,
&user_from_token.profile_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
if !target_role_info.is_deletable() {
return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!(
"Invalid operation, role_id = {} is not deletable",
role_to_be_deleted.role_id
));
}
if deletion_requestor_role_info.get_entity_type() < target_role_info.get_entity_type() {
return Err(report!(UserErrors::InvalidDeleteOperation)).attach_printable(format!(
"Invalid operation, deletion requestor = {} cannot delete target = {}",
deletion_requestor_role_info.get_entity_type(),
target_role_info.get_entity_type()
));
}
user_role_deleted_flag = true;
state
.global_store
.delete_user_role_by_user_id_and_lineage(
user_from_db.get_user_id(),
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
&user_from_token.org_id,
&user_from_token.merchant_id,
&user_from_token.profile_id,
UserRoleVersion::V1,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while deleting user role")?;
}
if !user_role_deleted_flag {
return Err(report!(UserErrors::InvalidDeleteOperation))
.attach_printable("User is not associated with the merchant");
}
// Check if user has any more role associations
let remaining_roles = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_db.get_user_id(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?;
// If user has no more role associated with him then deleting user
if remaining_roles.is_empty() {
state
.global_store
.delete_user_by_user_id(user_from_db.get_user_id())
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while deleting user entry")?;
}
auth::blacklist::insert_user_in_blacklist(&state, user_from_db.get_user_id()).await?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn list_users_in_lineage(
state: SessionState,
user_from_token: auth::UserFromToken,
request: user_role_api::ListUsersInEntityRequest,
) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> {
let requestor_role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
let user_roles_set: HashSet<_> = match utils::user_role::get_min_entity(
requestor_role_info.get_entity_type(),
request.entity_type,
)? {
EntityType::Tenant => {
let mut org_users = utils::user_role::fetch_user_roles_by_payload(
&state,
ListUserRolesByOrgIdPayload {
user_id: None,
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: &user_from_token.org_id,
merchant_id: None,
profile_id: None,
version: None,
limit: None,
},
request.entity_type,
)
.await?;
// Fetch tenant user
let tenant_user = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: &user_from_token.user_id,
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?;
org_users.extend(tenant_user);
org_users
}
EntityType::Organization => {
utils::user_role::fetch_user_roles_by_payload(
&state,
ListUserRolesByOrgIdPayload {
user_id: None,
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: &user_from_token.org_id,
merchant_id: None,
profile_id: None,
version: None,
limit: None,
},
request.entity_type,
)
.await?
}
EntityType::Merchant => {
utils::user_role::fetch_user_roles_by_payload(
&state,
ListUserRolesByOrgIdPayload {
user_id: None,
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: &user_from_token.org_id,
merchant_id: Some(&user_from_token.merchant_id),
profile_id: None,
version: None,
limit: None,
},
request.entity_type,
)
.await?
}
EntityType::Profile => {
utils::user_role::fetch_user_roles_by_payload(
&state,
ListUserRolesByOrgIdPayload {
user_id: None,
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: &user_from_token.org_id,
merchant_id: Some(&user_from_token.merchant_id),
profile_id: Some(&user_from_token.profile_id),
version: None,
limit: None,
},
request.entity_type,
)
.await?
}
};
// This filtering is needed because for org level users in V1, merchant_id is present.
// Due to this, we get org level users in merchant level users list.
let user_roles_set = user_roles_set
.into_iter()
.filter_map(|user_role| {
let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?;
(entity_type <= requestor_role_info.get_entity_type()).then_some(user_role)
})
.collect::<HashSet<_>>();
let mut email_map = state
.global_store
.find_users_by_user_ids(
user_roles_set
.iter()
.map(|user_role| user_role.user_id.clone())
.collect(),
)
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.map(|user| (user.user_id.clone(), user.email))
.collect::<HashMap<_, _>>();
let role_info_map =
futures::future::try_join_all(user_roles_set.iter().map(|user_role| async {
roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_role.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.map(|role_info| {
(
user_role.role_id.clone(),
user_role_api::role::MinimalRoleInfo {
role_id: user_role.role_id.clone(),
role_name: role_info.get_role_name().to_string(),
},
)
})
}))
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.collect::<HashMap<_, _>>();
let user_role_map = user_roles_set
.into_iter()
.fold(HashMap::new(), |mut map, user_role| {
map.entry(user_role.user_id)
.or_insert(Vec::with_capacity(1))
.push(user_role.role_id);
map
});
Ok(ApplicationResponse::Json(
user_role_map
.into_iter()
.map(|(user_id, role_id_vec)| {
Ok::<_, error_stack::Report<UserErrors>>(user_role_api::ListUsersInEntityResponse {
email: email_map
.remove(&user_id)
.ok_or(UserErrors::InternalServerError)?,
roles: role_id_vec
.into_iter()
.map(|role_id| {
role_info_map
.get(&role_id)
.cloned()
.ok_or(UserErrors::InternalServerError)
})
.collect::<Result<Vec<_>, _>>()?,
})
})
.collect::<Result<Vec<_>, _>>()?,
))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/relay.rs | crates/router/src/core/relay.rs | use std::marker::PhantomData;
use api_models::relay as relay_api_models;
use async_trait::async_trait;
use common_enums::RelayStatus;
use common_utils::{
self, fp_utils,
id_type::{self, GenerateId},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::relay;
use super::errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt};
use crate::{
core::payments,
routes::SessionState,
services,
types::{
api::{self},
domain,
},
utils::OptionExt,
};
pub mod utils;
pub trait Validate {
type Error: error_stack::Context;
fn validate(&self) -> Result<(), Self::Error>;
}
impl Validate for relay_api_models::RelayRefundRequestData {
type Error = errors::ApiErrorResponse;
fn validate(&self) -> Result<(), Self::Error> {
fp_utils::when(self.amount.get_amount_as_i64() <= 0, || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Amount should be greater than 0".to_string(),
})
})?;
Ok(())
}
}
#[async_trait]
pub trait RelayInterface {
type Request: Validate;
fn validate_relay_request(req: &Self::Request) -> RouterResult<()> {
req.validate()
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid relay request".to_string(),
})
}
fn get_domain_models(
relay_request: RelayRequestInner<Self>,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> relay::Relay;
async fn process_relay(
state: &SessionState,
platform: domain::Platform,
connector_account: domain::MerchantConnectorAccount,
relay_record: &relay::Relay,
) -> RouterResult<relay::RelayUpdate>;
fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse>;
}
pub struct RelayRequestInner<T: RelayInterface + ?Sized> {
pub connector_resource_id: String,
pub connector_id: id_type::MerchantConnectorAccountId,
pub relay_type: PhantomData<T>,
pub data: T::Request,
}
impl RelayRequestInner<RelayRefund> {
pub fn from_relay_request(relay_request: relay_api_models::RelayRequest) -> RouterResult<Self> {
match relay_request.data {
Some(relay_api_models::RelayData::Refund(ref_data)) => Ok(Self {
connector_resource_id: relay_request.connector_resource_id,
connector_id: relay_request.connector_id,
relay_type: PhantomData,
data: ref_data,
}),
None => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Relay data is required for relay type refund".to_string(),
})?,
}
}
}
pub struct RelayRefund;
#[async_trait]
impl RelayInterface for RelayRefund {
type Request = relay_api_models::RelayRefundRequestData;
fn get_domain_models(
relay_request: RelayRequestInner<Self>,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> relay::Relay {
let relay_id = id_type::RelayId::generate();
let relay_refund: relay::RelayRefundData = relay_request.data.into();
relay::Relay {
id: relay_id.clone(),
connector_resource_id: relay_request.connector_resource_id.clone(),
connector_id: relay_request.connector_id.clone(),
profile_id: profile_id.clone(),
merchant_id: merchant_id.clone(),
relay_type: common_enums::RelayType::Refund,
request_data: Some(relay::RelayData::Refund(relay_refund)),
status: RelayStatus::Created,
connector_reference_id: None,
error_code: None,
error_message: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
response_data: None,
}
}
async fn process_relay(
state: &SessionState,
platform: domain::Platform,
connector_account: domain::MerchantConnectorAccount,
relay_record: &relay::Relay,
) -> RouterResult<relay::RelayUpdate> {
let connector_id = &relay_record.connector_id;
let merchant_id = platform.get_processor().get_account().get_id();
let connector_name = &connector_account.get_connector_name_as_string();
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(connector_id.clone()),
)?;
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::Execute,
hyperswitch_domain_models::router_request_types::RefundsData,
hyperswitch_domain_models::router_response_types::RefundsResponseData,
> = connector_data.connector.get_connector_integration();
let router_data = utils::construct_relay_refund_router_data(
state,
merchant_id,
&connector_account,
relay_record,
)
.await?;
let router_data_res = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_refund_failed_response()?;
let relay_update = relay::RelayUpdate::from(router_data_res.response);
Ok(relay_update)
}
fn generate_response(value: relay::Relay) -> RouterResult<api_models::relay::RelayResponse> {
let error = value
.error_code
.zip(value.error_message)
.map(
|(error_code, error_message)| api_models::relay::RelayError {
code: error_code,
message: error_message,
},
);
let data =
api_models::relay::RelayData::from(value.request_data.get_required_value("RelayData")?);
Ok(api_models::relay::RelayResponse {
id: value.id,
status: value.status,
error,
connector_resource_id: value.connector_resource_id,
connector_id: value.connector_id,
profile_id: value.profile_id,
relay_type: value.relay_type,
data: Some(data),
connector_reference_id: value.connector_reference_id,
})
}
}
pub async fn relay_flow_decider(
state: SessionState,
platform: domain::Platform,
profile_id_optional: Option<id_type::ProfileId>,
request: relay_api_models::RelayRequest,
) -> RouterResponse<relay_api_models::RelayResponse> {
let relay_flow_request = match request.relay_type {
common_enums::RelayType::Refund => {
RelayRequestInner::<RelayRefund>::from_relay_request(request)?
}
};
relay(state, platform, profile_id_optional, relay_flow_request).await
}
pub async fn relay<T: RelayInterface>(
state: SessionState,
platform: domain::Platform,
profile_id_optional: Option<id_type::ProfileId>,
req: RelayRequestInner<T>,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let merchant_id = platform.get_processor().get_account().get_id();
let connector_id = &req.connector_id;
let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
let profile = db
.find_business_profile_by_merchant_id_profile_id(
platform.get_processor().get_key_store(),
merchant_id,
&profile_id_from_auth_layer,
)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id_from_auth_layer.get_string_repr().to_owned(),
})?;
#[cfg(feature = "v1")]
let connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
merchant_id,
connector_id,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_string(),
})?;
#[cfg(feature = "v2")]
let connector_account = db
.find_merchant_connector_account_by_id(
connector_id,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_string(),
})?;
T::validate_relay_request(&req.data)?;
let relay_domain = T::get_domain_models(req, merchant_id, profile.get_id());
let relay_record = db
.insert_relay(platform.get_processor().get_key_store(), relay_domain)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert a relay record in db")?;
let relay_response =
T::process_relay(&state, platform.clone(), connector_account, &relay_record)
.await
.attach_printable("Failed to process relay")?;
let relay_update_record = db
.update_relay(
platform.get_processor().get_key_store(),
relay_record,
relay_response,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = T::generate_response(relay_update_record)
.attach_printable("Failed to generate relay response")?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
pub async fn relay_retrieve(
state: SessionState,
platform: domain::Platform,
profile_id_optional: Option<id_type::ProfileId>,
req: relay_api_models::RelayRetrieveRequest,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let merchant_id = platform.get_processor().get_account().get_id();
let relay_id = &req.id;
let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
db.find_business_profile_by_merchant_id_profile_id(
platform.get_processor().get_key_store(),
merchant_id,
&profile_id_from_auth_layer,
)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id_from_auth_layer.get_string_repr().to_owned(),
})?;
let relay_record_result = db
.find_relay_by_id(platform.get_processor().get_key_store(), relay_id)
.await;
let relay_record = match relay_record_result {
Err(error) => {
if error.current_context().is_db_not_found() {
Err(error).change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "relay not found".to_string(),
})?
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while fetch relay record")?
}
}
Ok(relay) => relay,
};
#[cfg(feature = "v1")]
let connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
merchant_id,
&relay_record.connector_id,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: relay_record.connector_id.get_string_repr().to_string(),
})?;
#[cfg(feature = "v2")]
let connector_account = db
.find_merchant_connector_account_by_id(
&relay_record.connector_id,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: relay_record.connector_id.get_string_repr().to_string(),
})?;
let relay_response = match relay_record.relay_type {
common_enums::RelayType::Refund => {
if should_call_connector_for_relay_refund_status(&relay_record, req.force_sync) {
let relay_response = sync_relay_refund_with_gateway(
&state,
&platform,
&relay_record,
connector_account,
)
.await?;
db.update_relay(
platform.get_processor().get_key_store(),
relay_record,
relay_response,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the relay record")?
} else {
relay_record
}
}
};
let response = relay_api_models::RelayResponse::from(relay_response);
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
fn should_call_connector_for_relay_refund_status(relay: &relay::Relay, force_sync: bool) -> bool {
// This allows refund sync at connector level if force_sync is enabled, or
// check if the refund is in terminal state
!matches!(relay.status, RelayStatus::Failure | RelayStatus::Success) && force_sync
}
pub async fn sync_relay_refund_with_gateway(
state: &SessionState,
platform: &domain::Platform,
relay_record: &relay::Relay,
connector_account: domain::MerchantConnectorAccount,
) -> RouterResult<relay::RelayUpdate> {
let connector_id = &relay_record.connector_id;
let merchant_id = platform.get_processor().get_account().get_id();
#[cfg(feature = "v1")]
let connector_name = &connector_account.connector_name;
#[cfg(feature = "v2")]
let connector_name = &connector_account.connector_name.to_string();
let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(connector_id.clone()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector")?;
let router_data = utils::construct_relay_refund_router_data(
state,
merchant_id,
&connector_account,
relay_record,
)
.await?;
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::RSync,
hyperswitch_domain_models::router_request_types::RefundsData,
hyperswitch_domain_models::router_response_types::RefundsResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_res = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_refund_failed_response()?;
let relay_response = relay::RelayUpdate::from(router_data_res.response);
Ok(relay_response)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/debit_routing.rs | crates/router/src/core/debit_routing.rs | use std::{collections::HashSet, fmt::Debug};
use api_models::{enums as api_enums, open_router};
use common_enums::enums;
use common_utils::{errors::CustomResult, ext_traits::ValueExt, id_type};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use super::{
payments::{OperationSessionGetters, OperationSessionSetters},
routing::TransactionData,
};
use crate::{
core::{
errors,
payments::{operations::BoxedOperation, routing},
},
logger,
routes::SessionState,
settings,
types::{
api::{self, ConnectorCallType},
domain,
},
utils::id_type::MerchantConnectorAccountId,
};
pub struct DebitRoutingResult {
pub debit_routing_connector_call_type: ConnectorCallType,
pub debit_routing_output: open_router::DebitRoutingOutput,
}
pub async fn perform_debit_routing<F, Req, D>(
operation: &BoxedOperation<'_, F, Req, D>,
state: &SessionState,
business_profile: &domain::Profile,
payment_data: &mut D,
connector: Option<ConnectorCallType>,
) -> (
Option<ConnectorCallType>,
Option<open_router::DebitRoutingOutput>,
)
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let mut debit_routing_output = None;
if should_execute_debit_routing(state, business_profile, operation, payment_data).await {
let debit_routing_config = state.conf.debit_routing_config.clone();
let debit_routing_supported_connectors = debit_routing_config.supported_connectors.clone();
// If the business profile does not have a country set, we cannot perform debit routing,
// because the merchant_business_country will be treated as the acquirer_country,
// which is used to determine whether a transaction is local or global in the open router.
// For now, since debit routing is only implemented for USD, we can safely assume the
// acquirer_country is US if not provided by the merchant.
let acquirer_country = business_profile
.merchant_business_country
.unwrap_or_default();
if let Some(call_connector_type) = connector.clone() {
debit_routing_output = match call_connector_type {
ConnectorCallType::PreDetermined(connector_data) => {
logger::info!("Performing debit routing for PreDetermined connector");
handle_pre_determined_connector(
state,
debit_routing_supported_connectors,
&connector_data,
payment_data,
acquirer_country,
)
.await
}
ConnectorCallType::Retryable(connector_data) => {
logger::info!("Performing debit routing for Retryable connector");
handle_retryable_connector(
state,
debit_routing_supported_connectors,
connector_data,
payment_data,
acquirer_country,
)
.await
}
ConnectorCallType::SessionMultiple(_) => {
logger::info!(
"SessionMultiple connector type is not supported for debit routing"
);
None
}
#[cfg(feature = "v2")]
ConnectorCallType::Skip => {
logger::info!("Skip connector type is not supported for debit routing");
None
}
};
}
}
if let Some(debit_routing_output) = debit_routing_output {
(
Some(debit_routing_output.debit_routing_connector_call_type),
Some(debit_routing_output.debit_routing_output),
)
} else {
// If debit_routing_output is None, return the static routing output (connector)
logger::info!("Debit routing is not performed, returning static routing output");
(connector, None)
}
}
async fn should_execute_debit_routing<F, Req, D>(
state: &SessionState,
business_profile: &domain::Profile,
operation: &BoxedOperation<'_, F, Req, D>,
payment_data: &D,
) -> bool
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
if business_profile.is_debit_routing_enabled && state.conf.open_router.dynamic_routing_enabled {
logger::info!("Debit routing is enabled for the profile");
let debit_routing_config = &state.conf.debit_routing_config;
if should_perform_debit_routing_for_the_flow(operation, payment_data, debit_routing_config)
{
let is_debit_routable_connector_present = check_for_debit_routing_connector_in_profile(
state,
business_profile.get_id(),
payment_data,
)
.await;
if is_debit_routable_connector_present {
logger::debug!("Debit routable connector is configured for the profile");
return true;
}
}
}
false
}
pub fn should_perform_debit_routing_for_the_flow<Op: Debug, F: Clone, D>(
operation: &Op,
payment_data: &D,
debit_routing_config: &settings::DebitRoutingConfig,
) -> bool
where
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
match format!("{operation:?}").as_str() {
"PaymentConfirm" => {
logger::info!("Checking if debit routing is required");
request_validation(payment_data, debit_routing_config)
}
_ => false,
}
}
fn request_validation<F: Clone, D>(
payment_data: &D,
debit_routing_config: &settings::DebitRoutingConfig,
) -> bool
where
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
let payment_intent = payment_data.get_payment_intent();
let payment_attempt = payment_data.get_payment_attempt();
let is_currency_supported = is_currency_supported(payment_intent, debit_routing_config);
let is_valid_payment_method = validate_payment_method_for_debit_routing(payment_data);
payment_intent.setup_future_usage != Some(enums::FutureUsage::OffSession)
&& payment_intent.amount.is_greater_than(0)
&& is_currency_supported
&& payment_attempt.authentication_type == Some(enums::AuthenticationType::NoThreeDs)
&& is_valid_payment_method
}
fn is_currency_supported(
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
debit_routing_config: &settings::DebitRoutingConfig,
) -> bool {
payment_intent
.currency
.map(|currency| {
debit_routing_config
.supported_currencies
.contains(¤cy)
})
.unwrap_or(false)
}
fn validate_payment_method_for_debit_routing<F: Clone, D>(payment_data: &D) -> bool
where
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
let payment_attempt = payment_data.get_payment_attempt();
match payment_attempt.payment_method {
Some(enums::PaymentMethod::Card) => {
payment_attempt.payment_method_type == Some(enums::PaymentMethodType::Debit)
}
Some(enums::PaymentMethod::Wallet) => {
payment_attempt.payment_method_type == Some(enums::PaymentMethodType::ApplePay)
&& payment_data
.get_payment_method_data()
.and_then(|data| data.get_wallet_data())
.and_then(|data| data.get_apple_pay_wallet_data())
.and_then(|data| data.get_payment_method_type())
== Some(enums::PaymentMethodType::Debit)
&& matches!(
payment_data.get_payment_method_token().cloned(),
Some(
hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(
_
)
)
)
}
_ => false,
}
}
pub async fn check_for_debit_routing_connector_in_profile<
F: Clone,
D: OperationSessionGetters<F>,
>(
state: &SessionState,
business_profile_id: &id_type::ProfileId,
payment_data: &D,
) -> bool {
logger::debug!("Checking for debit routing connector in profile");
let debit_routing_supported_connectors =
state.conf.debit_routing_config.supported_connectors.clone();
let transaction_data = super::routing::PaymentsDslInput::new(
payment_data.get_setup_mandate(),
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_payment_method_data(),
payment_data.get_address(),
payment_data.get_recurring_details(),
payment_data.get_currency(),
);
let fallback_config_optional = super::routing::helpers::get_merchant_default_config(
&*state.clone().store,
business_profile_id.get_string_repr(),
&enums::TransactionType::from(&TransactionData::Payment(transaction_data)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.map_err(|error| {
logger::warn!(?error, "Failed to fetch default connector for a profile");
})
.ok();
let is_debit_routable_connector_present = fallback_config_optional
.map(|fallback_config| {
fallback_config.iter().any(|fallback_config_connector| {
debit_routing_supported_connectors.contains(&api_enums::Connector::from(
fallback_config_connector.connector,
))
})
})
.unwrap_or(false);
is_debit_routable_connector_present
}
async fn handle_pre_determined_connector<F, D>(
state: &SessionState,
debit_routing_supported_connectors: HashSet<api_enums::Connector>,
connector_data: &api::ConnectorRoutingData,
payment_data: &mut D,
acquirer_country: enums::CountryAlpha2,
) -> Option<DebitRoutingResult>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let db = state.store.as_ref();
let merchant_id = payment_data.get_payment_attempt().merchant_id.clone();
let profile_id = payment_data.get_payment_attempt().profile_id.clone();
if debit_routing_supported_connectors.contains(&connector_data.connector_data.connector_name) {
logger::debug!("Chosen connector is supported for debit routing");
let debit_routing_output =
get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?;
logger::debug!(
"Sorted co-badged networks info: {:?}",
debit_routing_output.co_badged_card_networks_info
);
let key_store = db
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::MerchantAccountNotFound)
.map_err(|error| {
logger::error!(
"Failed to get merchant key store by merchant_id {:?}",
error
)
})
.ok()?;
let connector_routing_data = build_connector_routing_data(
state,
&profile_id,
&key_store,
vec![connector_data.clone()],
debit_routing_output
.co_badged_card_networks_info
.clone()
.get_card_networks(),
)
.await
.map_err(|error| {
logger::error!(
"Failed to build connector routing data for debit routing {:?}",
error
)
})
.ok()?;
if !connector_routing_data.is_empty() {
return Some(DebitRoutingResult {
debit_routing_connector_call_type: ConnectorCallType::Retryable(
connector_routing_data,
),
debit_routing_output,
});
}
}
None
}
pub async fn get_debit_routing_output<
F: Clone + Send,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
>(
state: &SessionState,
payment_data: &mut D,
acquirer_country: enums::CountryAlpha2,
) -> Option<open_router::DebitRoutingOutput> {
logger::debug!("Fetching sorted card networks");
let card_info = extract_card_info(payment_data);
let saved_co_badged_card_data = card_info.co_badged_card_data;
let saved_card_type = card_info.card_type;
let card_isin = card_info.card_isin;
match (
saved_co_badged_card_data
.clone()
.zip(saved_card_type.clone()),
card_isin.clone(),
) {
(None, None) => {
logger::debug!("Neither co-badged data nor ISIN found; skipping routing");
None
}
_ => {
let co_badged_card_data = saved_co_badged_card_data
.zip(saved_card_type)
.and_then(|(co_badged, card_type)| {
open_router::DebitRoutingRequestData::try_from((co_badged, card_type))
.map(Some)
.map_err(|error| {
logger::warn!("Failed to convert co-badged card data: {:?}", error);
})
.ok()
})
.flatten();
if co_badged_card_data.is_none() && card_isin.is_none() {
logger::debug!("Neither co-badged data nor ISIN found; skipping routing");
return None;
}
let co_badged_card_request = open_router::CoBadgedCardRequest {
merchant_category_code: enums::DecisionEngineMerchantCategoryCode::Mcc0001,
acquirer_country,
co_badged_card_data,
};
routing::perform_open_routing_for_debit_routing(
state,
co_badged_card_request,
card_isin,
payment_data,
)
.await
.map_err(|error| {
logger::warn!(?error, "Debit routing call to open router failed");
})
.ok()
}
}
}
#[derive(Debug, Clone)]
struct ExtractedCardInfo {
co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,
card_type: Option<String>,
card_isin: Option<Secret<String>>,
}
impl ExtractedCardInfo {
fn new(
co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,
card_type: Option<String>,
card_isin: Option<Secret<String>>,
) -> Self {
Self {
co_badged_card_data,
card_type,
card_isin,
}
}
fn empty() -> Self {
Self::new(None, None, None)
}
}
fn extract_card_info<F, D>(payment_data: &D) -> ExtractedCardInfo
where
D: OperationSessionGetters<F>,
{
extract_from_saved_payment_method(payment_data)
.unwrap_or_else(|| extract_from_payment_method_data(payment_data))
}
fn extract_from_saved_payment_method<F, D>(payment_data: &D) -> Option<ExtractedCardInfo>
where
D: OperationSessionGetters<F>,
{
let payment_methods_data = payment_data
.get_payment_method_info()?
.get_payment_methods_data()?;
if let hyperswitch_domain_models::payment_method_data::PaymentMethodsData::Card(card) =
payment_methods_data
{
return Some(extract_card_info_from_saved_card(&card));
}
None
}
fn extract_card_info_from_saved_card(
card: &hyperswitch_domain_models::payment_method_data::CardDetailsPaymentMethod,
) -> ExtractedCardInfo {
match (&card.co_badged_card_data, &card.card_isin) {
(Some(co_badged), _) => {
logger::debug!("Co-badged card data found in saved payment method");
ExtractedCardInfo::new(Some(co_badged.clone().into()), card.card_type.clone(), None)
}
(None, Some(card_isin)) => {
logger::debug!("No co-badged data; using saved card ISIN");
ExtractedCardInfo::new(None, None, Some(Secret::new(card_isin.clone())))
}
_ => ExtractedCardInfo::empty(),
}
}
fn extract_from_payment_method_data<F, D>(payment_data: &D) -> ExtractedCardInfo
where
D: OperationSessionGetters<F>,
{
match payment_data.get_payment_method_data() {
Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card)) => {
logger::debug!("Using card data from payment request");
ExtractedCardInfo::new(
None,
None,
Some(Secret::new(card.card_number.get_extended_card_bin())),
)
}
Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(
wallet_data,
)) => extract_from_wallet_data(wallet_data, payment_data),
_ => ExtractedCardInfo::empty(),
}
}
fn extract_from_wallet_data<F, D>(
wallet_data: &hyperswitch_domain_models::payment_method_data::WalletData,
payment_data: &D,
) -> ExtractedCardInfo
where
D: OperationSessionGetters<F>,
{
match wallet_data {
hyperswitch_domain_models::payment_method_data::WalletData::ApplePay(_) => {
logger::debug!("Using Apple Pay data from payment request");
let apple_pay_isin = extract_apple_pay_isin(payment_data);
ExtractedCardInfo::new(None, None, apple_pay_isin)
}
_ => ExtractedCardInfo::empty(),
}
}
fn extract_apple_pay_isin<F, D>(payment_data: &D) -> Option<Secret<String>>
where
D: OperationSessionGetters<F>,
{
payment_data.get_payment_method_token().and_then(|token| {
if let hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(
apple_pay_decrypt_data,
) = token
{
logger::debug!("Using Apple Pay decrypt data from payment method token");
Some(Secret::new(
apple_pay_decrypt_data
.application_primary_account_number
.peek()
.chars()
.take(8)
.collect::<String>(),
))
} else {
None
}
})
}
async fn handle_retryable_connector<F, D>(
state: &SessionState,
debit_routing_supported_connectors: HashSet<api_enums::Connector>,
connector_data_list: Vec<api::ConnectorRoutingData>,
payment_data: &mut D,
acquirer_country: enums::CountryAlpha2,
) -> Option<DebitRoutingResult>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let db = state.store.as_ref();
let profile_id = payment_data.get_payment_attempt().profile_id.clone();
let merchant_id = payment_data.get_payment_attempt().merchant_id.clone();
let is_any_debit_routing_connector_supported =
connector_data_list.iter().any(|connector_data| {
debit_routing_supported_connectors
.contains(&connector_data.connector_data.connector_name)
});
if is_any_debit_routing_connector_supported {
let debit_routing_output =
get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?;
let key_store = db
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::MerchantAccountNotFound)
.map_err(|error| {
logger::error!(
"Failed to get merchant key store by merchant_id {:?}",
error
)
})
.ok()?;
let connector_routing_data = build_connector_routing_data(
state,
&profile_id,
&key_store,
connector_data_list.clone(),
debit_routing_output
.co_badged_card_networks_info
.clone()
.get_card_networks(),
)
.await
.map_err(|error| {
logger::error!(
"Failed to build connector routing data for debit routing {:?}",
error
)
})
.ok()?;
if !connector_routing_data.is_empty() {
return Some(DebitRoutingResult {
debit_routing_connector_call_type: ConnectorCallType::Retryable(
connector_routing_data,
),
debit_routing_output,
});
};
}
None
}
async fn build_connector_routing_data(
state: &SessionState,
profile_id: &id_type::ProfileId,
key_store: &domain::MerchantKeyStore,
eligible_connector_data_list: Vec<api::ConnectorRoutingData>,
fee_sorted_debit_networks: Vec<common_enums::CardNetwork>,
) -> CustomResult<Vec<api::ConnectorRoutingData>, errors::ApiErrorResponse> {
let debit_routing_config = &state.conf.debit_routing_config;
let mcas_for_profile = fetch_merchant_connector_accounts(state, profile_id, key_store).await?;
let mut connector_routing_data = Vec::new();
let mut has_us_local_network = false;
for connector_data in eligible_connector_data_list {
if let Some(routing_data) = process_connector_for_networks(
&connector_data,
&mcas_for_profile,
&fee_sorted_debit_networks,
debit_routing_config,
&mut has_us_local_network,
)? {
connector_routing_data.extend(routing_data);
}
}
validate_us_local_network_requirement(has_us_local_network)?;
Ok(connector_routing_data)
}
/// Fetches merchant connector accounts for the given profile
async fn fetch_merchant_connector_accounts(
state: &SessionState,
profile_id: &id_type::ProfileId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::ApiErrorResponse> {
state
.store
.list_enabled_connector_accounts_by_profile_id(
profile_id,
key_store,
common_enums::ConnectorType::PaymentProcessor,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch merchant connector accounts")
}
/// Processes a single connector to find matching networks
fn process_connector_for_networks(
connector_data: &api::ConnectorRoutingData,
mcas_for_profile: &[domain::MerchantConnectorAccount],
fee_sorted_debit_networks: &[common_enums::CardNetwork],
debit_routing_config: &settings::DebitRoutingConfig,
has_us_local_network: &mut bool,
) -> CustomResult<Option<Vec<api::ConnectorRoutingData>>, errors::ApiErrorResponse> {
let Some(merchant_connector_id) = &connector_data.connector_data.merchant_connector_id else {
logger::warn!("Skipping connector with missing merchant_connector_id");
return Ok(None);
};
let Some(account) = find_merchant_connector_account(mcas_for_profile, merchant_connector_id)
else {
logger::warn!(
"No MCA found for merchant_connector_id: {:?}",
merchant_connector_id
);
return Ok(None);
};
let merchant_debit_networks = extract_debit_networks(&account)?;
let matching_networks = find_matching_networks(
&merchant_debit_networks,
fee_sorted_debit_networks,
connector_data,
debit_routing_config,
has_us_local_network,
);
Ok(Some(matching_networks))
}
/// Finds a merchant connector account by ID
fn find_merchant_connector_account(
mcas: &[domain::MerchantConnectorAccount],
merchant_connector_id: &MerchantConnectorAccountId,
) -> Option<domain::MerchantConnectorAccount> {
mcas.iter()
.find(|mca| mca.merchant_connector_id == *merchant_connector_id)
.cloned()
}
/// Finds networks that match between merchant and fee-sorted networks
fn find_matching_networks(
merchant_debit_networks: &HashSet<common_enums::CardNetwork>,
fee_sorted_debit_networks: &[common_enums::CardNetwork],
connector_routing_data: &api::ConnectorRoutingData,
debit_routing_config: &settings::DebitRoutingConfig,
has_us_local_network: &mut bool,
) -> Vec<api::ConnectorRoutingData> {
let is_routing_enabled = debit_routing_config
.supported_connectors
.contains(&connector_routing_data.connector_data.connector_name.clone());
fee_sorted_debit_networks
.iter()
.filter(|network| merchant_debit_networks.contains(network))
.filter(|network| is_routing_enabled || network.is_signature_network())
.map(|network| {
if network.is_us_local_network() {
*has_us_local_network = true;
}
api::ConnectorRoutingData {
connector_data: connector_routing_data.connector_data.clone(),
network: Some(network.clone()),
action_type: connector_routing_data.action_type.clone(),
}
})
.collect()
}
/// Validates that at least one US local network is present
fn validate_us_local_network_requirement(
has_us_local_network: bool,
) -> CustomResult<(), errors::ApiErrorResponse> {
if !has_us_local_network {
return Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("At least one US local network is required in routing");
}
Ok(())
}
fn extract_debit_networks(
account: &domain::MerchantConnectorAccount,
) -> CustomResult<HashSet<common_enums::CardNetwork>, errors::ApiErrorResponse> {
let mut networks = HashSet::new();
if let Some(values) = &account.payment_methods_enabled {
for val in values {
let payment_methods_enabled: api_models::admin::PaymentMethodsEnabled =
val.to_owned().parse_value("PaymentMethodsEnabled")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse enabled payment methods for a merchant connector account in debit routing flow")?;
if let Some(types) = payment_methods_enabled.payment_method_types {
for method_type in types {
if method_type.payment_method_type
== api_models::enums::PaymentMethodType::Debit
{
if let Some(card_networks) = method_type.card_networks {
networks.extend(card_networks);
}
}
}
}
}
}
Ok(networks)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/admin.rs | crates/router/src/core/admin.rs | use std::str::FromStr;
use api_models::{
admin::{self as admin_types},
enums as api_enums, routing as routing_types,
};
use common_enums::{MerchantAccountRequestType, MerchantAccountType, OrganizationType};
use common_utils::{
date_time,
ext_traits::{AsyncExt, Encode, OptionExt, ValueExt},
fp_utils, id_type, pii, type_name,
types::keymanager::{self as km_types, KeyManagerState, ToEncryptable},
};
#[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))]
use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge};
use diesel_models::{configs, payment_method};
use error_stack::{report, FutureExt, ResultExt};
use external_services::http_client::client;
use hyperswitch_domain_models::merchant_connector_account::{
FromRequestEncryptableMerchantConnectorAccount, UpdateEncryptableMerchantConnectorAccount,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use pm_auth::types as pm_auth_types;
use uuid::Uuid;
use super::routing::helpers::redact_cgraph_cache;
#[cfg(any(feature = "v1", feature = "v2"))]
use crate::types::transformers::ForeignFrom;
use crate::{
consts,
core::{
connector_validation::ConnectorAuthTypeAndMetadataValidation,
disputes,
encryption::transfer_encryption_key,
errors::{self, RouterResponse, RouterResult, StorageErrorExt},
payment_methods::{cards, transformers},
payments::helpers,
pm_auth::helpers::PaymentAuthConnectorDataExt,
routing, utils as core_utils,
},
db::{AccountsStorageInterface, StorageInterface},
logger,
routes::{metrics, SessionState},
services::{
self,
api::{self as service_api},
authentication, pm_auth as payment_initiation_service,
},
types::{
self,
api::{self, admin},
domain::{
self,
types::{self as domain_types, AsyncLift},
},
storage::{self, enums::MerchantStorageScheme},
transformers::{ForeignInto, ForeignTryFrom, ForeignTryInto},
},
utils,
};
#[inline]
pub fn create_merchant_publishable_key() -> String {
format!(
"pk_{}_{}",
router_env::env::prefix_for_env(),
Uuid::new_v4().simple()
)
}
pub async fn insert_merchant_configs(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
) -> RouterResult<()> {
db.insert_config(configs::ConfigNew {
key: merchant_id.get_requires_cvv_key(),
config: "true".to_string(),
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while setting requires_cvv config")?;
db.insert_config(configs::ConfigNew {
key: merchant_id.get_merchant_fingerprint_secret_key(),
config: utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs"),
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while inserting merchant fingerprint secret")?;
Ok(())
}
#[cfg(feature = "olap")]
fn add_publishable_key_to_decision_service(state: &SessionState, platform: &domain::Platform) {
let state = state.clone();
let publishable_key = platform
.get_processor()
.get_account()
.publishable_key
.clone();
let merchant_id = platform.get_processor().get_account().get_id().clone();
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::add_publishable_key(
&state,
publishable_key.into(),
merchant_id,
None,
)
.await
},
authentication::decision::ADD,
);
}
#[cfg(feature = "olap")]
pub async fn create_organization(
state: SessionState,
req: api::OrganizationCreateRequest,
) -> RouterResponse<api::OrganizationResponse> {
let db_organization = ForeignFrom::foreign_from(req);
state
.accounts_store
.insert_organization(db_organization)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "Organization with the given organization_name already exists".to_string(),
})
.attach_printable("Error when creating organization")
.map(ForeignFrom::foreign_from)
.map(service_api::ApplicationResponse::Json)
}
#[cfg(feature = "olap")]
pub async fn update_organization(
state: SessionState,
org_id: api::OrganizationId,
req: api::OrganizationUpdateRequest,
) -> RouterResponse<api::OrganizationResponse> {
let organization_update = diesel_models::organization::OrganizationUpdate::Update {
organization_name: req.organization_name,
organization_details: req.organization_details,
metadata: req.metadata,
platform_merchant_id: req.platform_merchant_id,
};
state
.accounts_store
.update_organization_by_org_id(&org_id.organization_id, organization_update)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "organization with the given id does not exist".to_string(),
})
.attach_printable(format!(
"Failed to update organization with organization_id: {:?}",
org_id.organization_id
))
.map(ForeignFrom::foreign_from)
.map(service_api::ApplicationResponse::Json)
}
#[cfg(feature = "olap")]
pub async fn get_organization(
state: SessionState,
org_id: api::OrganizationId,
) -> RouterResponse<api::OrganizationResponse> {
#[cfg(all(feature = "v1", feature = "olap"))]
{
CreateOrValidateOrganization::new(Some(org_id.organization_id))
.create_or_validate(state.accounts_store.as_ref())
.await
.map(ForeignFrom::foreign_from)
.map(service_api::ApplicationResponse::Json)
}
#[cfg(all(feature = "v2", feature = "olap"))]
{
CreateOrValidateOrganization::new(org_id.organization_id)
.create_or_validate(state.accounts_store.as_ref())
.await
.map(ForeignFrom::foreign_from)
.map(service_api::ApplicationResponse::Json)
}
}
#[cfg(feature = "olap")]
pub async fn create_merchant_account(
state: SessionState,
req: api::MerchantAccountCreate,
org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,
) -> RouterResponse<api::MerchantAccountResponse> {
#[cfg(feature = "keymanager_create")]
use common_utils::{keymanager, types::keymanager::EncryptionTransferRequest};
let db = state.store.as_ref();
let key = services::generate_aes256_key()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate aes 256 key")?;
let master_key = db.get_master_key();
let key_manager_state: &KeyManagerState = &(&state).into();
let merchant_id = req.get_merchant_reference_id();
let identifier = km_types::Identifier::Merchant(merchant_id.clone());
#[cfg(feature = "keymanager_create")]
{
use base64::Engine;
use crate::consts::BASE64_ENGINE;
if key_manager_state.enabled {
keymanager::transfer_key_to_key_manager(
key_manager_state,
EncryptionTransferRequest {
identifier: identifier.clone(),
key: masking::StrongSecret::new(BASE64_ENGINE.encode(key)),
},
)
.await
.change_context(errors::ApiErrorResponse::DuplicateMerchantAccount)
.attach_printable("Failed to insert key to KeyManager")?;
}
}
let key_store = domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
key: domain_types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantKeyStore),
domain_types::CryptoOperation::EncryptLocally(key.to_vec().into()),
identifier.clone(),
master_key,
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decrypt data from key store")?,
created_at: date_time::now(),
};
let domain_merchant_account = req
.create_domain_model_from_request(
&state,
key_store.clone(),
&merchant_id,
org_data_from_auth,
)
.await?;
db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into())
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
let merchant_account = db
.insert_merchant(domain_merchant_account, &key_store)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
add_publishable_key_to_decision_service(&state, &platform);
insert_merchant_configs(db, &merchant_id).await?;
Ok(service_api::ApplicationResponse::Json(
api::MerchantAccountResponse::foreign_try_from(merchant_account)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while generating response")?,
))
}
#[cfg(feature = "olap")]
#[async_trait::async_trait]
trait MerchantAccountCreateBridge {
async fn create_domain_model_from_request(
self,
state: &SessionState,
key: domain::MerchantKeyStore,
identifier: &id_type::MerchantId,
org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,
) -> RouterResult<domain::MerchantAccount>;
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[async_trait::async_trait]
impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
async fn create_domain_model_from_request(
self,
state: &SessionState,
key_store: domain::MerchantKeyStore,
identifier: &id_type::MerchantId,
org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,
) -> RouterResult<domain::MerchantAccount> {
let db = &*state.accounts_store;
let publishable_key = create_merchant_publishable_key();
let primary_business_details = self.get_primary_details_as_value().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "primary_business_details",
},
)?;
let webhook_details = self.webhook_details.clone().map(ForeignInto::foreign_into);
let pm_collect_link_config = self.get_pm_link_config_as_value().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "pm_collect_link_config",
},
)?;
let merchant_details = self.get_merchant_details_as_secret().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "merchant_details",
},
)?;
self.parse_routing_algorithm()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "routing_algorithm",
})
.attach_printable("Invalid routing algorithm given")?;
let metadata = self.get_metadata_as_secret().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "metadata",
},
)?;
// Get the enable payment response hash as a boolean, where the default value is true
let enable_payment_response_hash = self.get_enable_payment_response_hash();
let payment_response_hash_key = self.get_payment_response_hash_key();
let parent_merchant_id = get_parent_merchant(
state,
self.sub_merchants_enabled,
self.parent_merchant_id.as_ref(),
&key_store,
)
.await?;
let org_id = match (&self.organization_id, &org_data_from_auth) {
(Some(req_org_id), Some(auth)) => {
if req_org_id != &auth.organization_id {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Mismatched organization_id in request and authenticated context"
.to_string(),
}
.into());
}
Some(req_org_id.clone())
}
(None, Some(auth)) => Some(auth.organization_id.clone()),
(req_org_id, _) => req_org_id.clone(),
};
let organization = CreateOrValidateOrganization::new(org_id)
.create_or_validate(db)
.await?;
let merchant_account_type = match organization.get_organization_type() {
OrganizationType::Standard => {
match self.merchant_account_type.unwrap_or_default() {
// Allow only if explicitly Standard or not provided
MerchantAccountRequestType::Standard => MerchantAccountType::Standard,
MerchantAccountRequestType::Connected => {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message:
"Merchant account type must be Standard for a Standard Organization"
.to_string(),
}
.into());
}
}
}
OrganizationType::Platform => {
let accounts = state
.store
.list_merchant_accounts_by_organization_id(&organization.get_organization_id())
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let platform_account_exists = accounts
.iter()
.any(|account| account.merchant_account_type == MerchantAccountType::Platform);
if accounts.is_empty() || !platform_account_exists {
// First merchant in a Platform org must be Platform
MerchantAccountType::Platform
} else {
match self.merchant_account_type.unwrap_or_default() {
MerchantAccountRequestType::Standard => MerchantAccountType::Standard,
MerchantAccountRequestType::Connected => {
if state.conf.platform.allow_connected_merchants {
MerchantAccountType::Connected
} else {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Connected merchant accounts are not allowed"
.to_string(),
}
.into());
}
}
}
}
}
};
let key = key_store.key.clone().into_inner();
let key_manager_state = state.into();
let merchant_account = async {
Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>(
domain::MerchantAccountSetter {
merchant_id: identifier.clone(),
merchant_name: self
.merchant_name
.async_lift(|inner| async {
domain_types::crypto_operation(
&key_manager_state,
type_name!(domain::MerchantAccount),
domain_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: merchant_details
.async_lift(|inner| async {
domain_types::crypto_operation(
&key_manager_state,
type_name!(domain::MerchantAccount),
domain_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(key_store.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
return_url: self.return_url.map(|a| a.to_string()),
webhook_details,
routing_algorithm: Some(serde_json::json!({
"algorithm_id": null,
"timestamp": 0
})),
sub_merchants_enabled: self.sub_merchants_enabled,
parent_merchant_id,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post: self
.redirect_to_merchant_with_http_post
.unwrap_or_default(),
publishable_key,
locker_id: self.locker_id,
metadata,
storage_scheme: MerchantStorageScheme::PostgresOnly,
primary_business_details,
created_at: date_time::now(),
modified_at: date_time::now(),
intent_fulfillment_time: None,
frm_routing_algorithm: self.frm_routing_algorithm,
#[cfg(feature = "payouts")]
payout_routing_algorithm: self.payout_routing_algorithm,
#[cfg(not(feature = "payouts"))]
payout_routing_algorithm: None,
organization_id: organization.get_organization_id(),
is_recon_enabled: false,
default_profile: None,
recon_status: diesel_models::enums::ReconStatus::NotRequested,
payment_link_config: None,
pm_collect_link_config,
version: common_types::consts::API_VERSION,
is_platform_account: false,
product_type: self.product_type,
merchant_account_type,
},
)
}
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let mut domain_merchant_account = domain::MerchantAccount::from(merchant_account);
CreateProfile::new(self.primary_business_details.clone())
.create_profiles(state, &mut domain_merchant_account, &key_store)
.await?;
Ok(domain_merchant_account)
}
}
#[cfg(feature = "olap")]
enum CreateOrValidateOrganization {
/// Creates a new organization
#[cfg(feature = "v1")]
Create,
/// Validates if this organization exists in the records
Validate {
organization_id: id_type::OrganizationId,
},
}
#[cfg(feature = "olap")]
impl CreateOrValidateOrganization {
#[cfg(all(feature = "v1", feature = "olap"))]
/// Create an action to either create or validate the given organization_id
/// If organization_id is passed, then validate if this organization exists
/// If not passed, create a new organization
fn new(organization_id: Option<id_type::OrganizationId>) -> Self {
if let Some(organization_id) = organization_id {
Self::Validate { organization_id }
} else {
Self::Create
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
/// Create an action to validate the provided organization_id
fn new(organization_id: id_type::OrganizationId) -> Self {
Self::Validate { organization_id }
}
#[cfg(feature = "olap")]
/// Apply the action, whether to create the organization or validate the given organization_id
async fn create_or_validate(
&self,
db: &dyn AccountsStorageInterface,
) -> RouterResult<diesel_models::organization::Organization> {
match self {
#[cfg(feature = "v1")]
Self::Create => {
let new_organization = api_models::organization::OrganizationNew::new(
OrganizationType::Standard,
None,
);
let db_organization = ForeignFrom::foreign_from(new_organization);
db.insert_organization(db_organization)
.await
.to_duplicate_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error when creating organization")
}
Self::Validate { organization_id } => db
.find_organization_by_org_id(organization_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "organization with the given id does not exist".to_string(),
}),
}
}
}
#[cfg(all(feature = "v1", feature = "olap"))]
enum CreateProfile {
/// Create profiles from primary business details
/// If there is only one profile created, then set this profile as default
CreateFromPrimaryBusinessDetails {
primary_business_details: Vec<admin_types::PrimaryBusinessDetails>,
},
/// Create a default profile, set this as default profile
CreateDefaultProfile,
}
#[cfg(all(feature = "v1", feature = "olap"))]
impl CreateProfile {
/// Create a new profile action from the given information
/// If primary business details exist, then create profiles from them
/// If primary business details are empty, then create default profile
fn new(primary_business_details: Option<Vec<admin_types::PrimaryBusinessDetails>>) -> Self {
match primary_business_details {
Some(primary_business_details) if !primary_business_details.is_empty() => {
Self::CreateFromPrimaryBusinessDetails {
primary_business_details,
}
}
_ => Self::CreateDefaultProfile,
}
}
async fn create_profiles(
&self,
state: &SessionState,
merchant_account: &mut domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
match self {
Self::CreateFromPrimaryBusinessDetails {
primary_business_details,
} => {
let business_profiles = Self::create_profiles_for_each_business_details(
state,
merchant_account.clone(),
primary_business_details,
key_store,
)
.await?;
// Update the default business profile in merchant account
if business_profiles.len() == 1 {
merchant_account.default_profile = business_profiles
.first()
.map(|business_profile| business_profile.get_id().to_owned())
}
}
Self::CreateDefaultProfile => {
let business_profile = self
.create_default_business_profile(state, merchant_account.clone(), key_store)
.await?;
merchant_account.default_profile = Some(business_profile.get_id().to_owned());
}
}
Ok(())
}
/// Create default profile
async fn create_default_business_profile(
&self,
state: &SessionState,
merchant_account: domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<domain::Profile> {
let business_profile = create_and_insert_business_profile(
state,
api_models::admin::ProfileCreate::default(),
merchant_account.clone(),
key_store,
)
.await?;
Ok(business_profile)
}
/// Create profile for each primary_business_details,
/// If there is no default profile in merchant account and only one primary_business_detail
/// is available, then create a default profile.
async fn create_profiles_for_each_business_details(
state: &SessionState,
merchant_account: domain::MerchantAccount,
primary_business_details: &Vec<admin_types::PrimaryBusinessDetails>,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Vec<domain::Profile>> {
let mut business_profiles_vector = Vec::with_capacity(primary_business_details.len());
// This must ideally be run in a transaction,
// if there is an error in inserting some profile, because of unique constraints
// the whole query must be rolled back
for business_profile in primary_business_details {
let profile_name =
format!("{}_{}", business_profile.country, business_profile.business);
let profile_create_request = api_models::admin::ProfileCreate {
profile_name: Some(profile_name),
..Default::default()
};
create_and_insert_business_profile(
state,
profile_create_request,
merchant_account.clone(),
key_store,
)
.await
.map_err(|profile_insert_error| {
logger::warn!("Profile already exists {profile_insert_error:?}");
})
.map(|business_profile| business_profiles_vector.push(business_profile))
.ok();
}
Ok(business_profiles_vector)
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[async_trait::async_trait]
impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
async fn create_domain_model_from_request(
self,
state: &SessionState,
key_store: domain::MerchantKeyStore,
identifier: &id_type::MerchantId,
_org_data: Option<authentication::AuthenticationDataWithOrg>,
) -> RouterResult<domain::MerchantAccount> {
let publishable_key = create_merchant_publishable_key();
let db = &*state.accounts_store;
let metadata = self.get_metadata_as_secret().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "metadata",
},
)?;
let merchant_details = self.get_merchant_details_as_secret().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "merchant_details",
},
)?;
let organization = CreateOrValidateOrganization::new(self.organization_id.clone())
.create_or_validate(db)
.await?;
// V2 currently supports creation of Standard merchant accounts only, irrespective of organization type
let merchant_account_type = MerchantAccountType::Standard;
let key = key_store.key.into_inner();
let id = identifier.to_owned();
let key_manager_state = state.into();
let identifier = km_types::Identifier::Merchant(id.clone());
async {
Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>(
domain::MerchantAccount::from(domain::MerchantAccountSetter {
id,
merchant_name: Some(
domain_types::crypto_operation(
&key_manager_state,
type_name!(domain::MerchantAccount),
domain_types::CryptoOperation::Encrypt(
self.merchant_name
.map(|merchant_name| merchant_name.into_inner()),
),
identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_operation())?,
),
merchant_details: merchant_details
.async_lift(|inner| async {
domain_types::crypto_operation(
&key_manager_state,
type_name!(domain::MerchantAccount),
domain_types::CryptoOperation::EncryptOptional(inner),
identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
publishable_key,
metadata,
storage_scheme: MerchantStorageScheme::PostgresOnly,
created_at: date_time::now(),
modified_at: date_time::now(),
organization_id: organization.get_organization_id(),
recon_status: diesel_models::enums::ReconStatus::NotRequested,
is_platform_account: false,
version: common_types::consts::API_VERSION,
product_type: self.product_type,
merchant_account_type,
}),
)
}
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to encrypt merchant details")
}
}
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn list_merchant_account(
state: SessionState,
organization_id: api_models::organization::OrganizationId,
) -> RouterResponse<Vec<api::MerchantAccountResponse>> {
let merchant_accounts = state
.store
.list_merchant_accounts_by_organization_id(&organization_id.organization_id)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_accounts = merchant_accounts
.into_iter()
.map(|merchant_account| {
api::MerchantAccountResponse::foreign_try_from(merchant_account).change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "merchant_account",
},
)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(services::ApplicationResponse::Json(merchant_accounts))
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn list_merchant_account(
state: SessionState,
req: api_models::admin::MerchantAccountListRequest,
org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,
) -> RouterResponse<Vec<api::MerchantAccountResponse>> {
if let Some(auth) = org_data_from_auth {
if auth.organization_id != req.organization_id {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Organization ID in request and authentication do not match".to_string(),
}
.into());
}
}
let merchant_accounts = state
.store
.list_merchant_accounts_by_organization_id(&req.organization_id)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_accounts = merchant_accounts
.into_iter()
.map(|merchant_account| {
api::MerchantAccountResponse::foreign_try_from(merchant_account).change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "merchant_account",
},
)
})
.collect::<Result<Vec<_>, _>>()?;
Ok(services::ApplicationResponse::Json(merchant_accounts))
}
pub async fn get_merchant_account(
state: SessionState,
req: api::MerchantId,
_profile_id: Option<id_type::ProfileId>,
) -> RouterResponse<api::MerchantAccountResponse> {
let db = state.store.as_ref();
let key_store = db
.get_merchant_key_store_by_merchant_id(
&req.merchant_id,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/health_check.rs | crates/router/src/core/health_check.rs | #[cfg(feature = "olap")]
use analytics::health_check::HealthCheck;
#[cfg(feature = "dynamic_routing")]
use api_models::health_check::HealthCheckMap;
use api_models::health_check::HealthState;
use error_stack::ResultExt;
use router_env::logger;
use crate::{
consts,
core::errors::{self, CustomResult},
routes::app,
services::api as services,
};
#[async_trait::async_trait]
pub trait HealthCheckInterface {
async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError>;
async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError>;
async fn health_check_locker(
&self,
) -> CustomResult<HealthState, errors::HealthCheckLockerError>;
async fn health_check_outgoing(&self)
-> CustomResult<HealthState, errors::HealthCheckOutGoing>;
#[cfg(feature = "olap")]
async fn health_check_analytics(&self)
-> CustomResult<HealthState, errors::HealthCheckDBError>;
#[cfg(feature = "olap")]
async fn health_check_opensearch(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDBError>;
#[cfg(feature = "dynamic_routing")]
async fn health_check_grpc(
&self,
) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError>;
#[cfg(feature = "dynamic_routing")]
async fn health_check_decision_engine(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDecisionEngineError>;
async fn health_check_unified_connector_service(
&self,
) -> CustomResult<HealthState, errors::HealthCheckUnifiedConnectorServiceError>;
}
#[async_trait::async_trait]
impl HealthCheckInterface for app::SessionState {
async fn health_check_db(&self) -> CustomResult<HealthState, errors::HealthCheckDBError> {
let db = &*self.store;
db.health_check_db().await?;
Ok(HealthState::Running)
}
async fn health_check_redis(&self) -> CustomResult<HealthState, errors::HealthCheckRedisError> {
let db = &*self.store;
let redis_conn = db
.get_redis_conn()
.change_context(errors::HealthCheckRedisError::RedisConnectionError)?;
redis_conn
.serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30)
.await
.change_context(errors::HealthCheckRedisError::SetFailed)?;
logger::debug!("Redis set_key was successful");
redis_conn
.get_key::<()>(&"test_key".into())
.await
.change_context(errors::HealthCheckRedisError::GetFailed)?;
logger::debug!("Redis get_key was successful");
redis_conn
.delete_key(&"test_key".into())
.await
.change_context(errors::HealthCheckRedisError::DeleteFailed)?;
logger::debug!("Redis delete_key was successful");
Ok(HealthState::Running)
}
async fn health_check_locker(
&self,
) -> CustomResult<HealthState, errors::HealthCheckLockerError> {
let locker = &self.conf.locker;
if !locker.mock_locker {
let mut url = locker.host.to_owned();
url.push_str(consts::LOCKER_HEALTH_CALL_PATH);
let request = services::Request::new(services::Method::Get, &url);
services::call_connector_api(self, request, "health_check_for_locker")
.await
.change_context(errors::HealthCheckLockerError::FailedToCallLocker)?
.map_err(|_| {
error_stack::report!(errors::HealthCheckLockerError::FailedToCallLocker)
})?;
Ok(HealthState::Running)
} else {
Ok(HealthState::NotApplicable)
}
}
#[cfg(feature = "olap")]
async fn health_check_analytics(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDBError> {
let analytics = &self.pool;
match analytics {
analytics::AnalyticsProvider::Sqlx(client) => client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::SqlxAnalyticsError),
analytics::AnalyticsProvider::Clickhouse(client) => client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError),
analytics::AnalyticsProvider::CombinedCkh(sqlx_client, ckh_client) => {
sqlx_client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::SqlxAnalyticsError)?;
ckh_client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError)
}
analytics::AnalyticsProvider::CombinedSqlx(sqlx_client, ckh_client) => {
sqlx_client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::SqlxAnalyticsError)?;
ckh_client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::ClickhouseAnalyticsError)
}
}?;
Ok(HealthState::Running)
}
#[cfg(feature = "olap")]
async fn health_check_opensearch(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDBError> {
if let Some(client) = self.opensearch_client.as_ref() {
client
.deep_health_check()
.await
.change_context(errors::HealthCheckDBError::OpensearchError)?;
Ok(HealthState::Running)
} else {
Ok(HealthState::NotApplicable)
}
}
async fn health_check_outgoing(
&self,
) -> CustomResult<HealthState, errors::HealthCheckOutGoing> {
let request = services::Request::new(services::Method::Get, consts::OUTGOING_CALL_URL);
services::call_connector_api(self, request, "outgoing_health_check")
.await
.map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed {
message: err.to_string(),
})?
.map_err(|err| errors::HealthCheckOutGoing::OutGoingFailed {
message: format!(
"Got a non 200 status while making outgoing request. Error {:?}",
err.response
),
})?;
logger::debug!("Outgoing request successful");
Ok(HealthState::Running)
}
#[cfg(feature = "dynamic_routing")]
async fn health_check_grpc(
&self,
) -> CustomResult<HealthCheckMap, errors::HealthCheckGRPCServiceError> {
let health_client = &self.grpc_client.health_client;
let grpc_config = &self.conf.grpc_client;
let health_check_map = health_client
.perform_health_check(grpc_config)
.await
.change_context(errors::HealthCheckGRPCServiceError::FailedToCallService)?;
logger::debug!("Health check successful");
Ok(health_check_map)
}
#[cfg(feature = "dynamic_routing")]
async fn health_check_decision_engine(
&self,
) -> CustomResult<HealthState, errors::HealthCheckDecisionEngineError> {
if self.conf.open_router.dynamic_routing_enabled {
let url = format!("{}/{}", &self.conf.open_router.url, "health");
let request = services::Request::new(services::Method::Get, &url);
let _ = services::call_connector_api(self, request, "health_check_for_decision_engine")
.await
.change_context(
errors::HealthCheckDecisionEngineError::FailedToCallDecisionEngineService,
)?;
logger::debug!("Decision engine health check successful");
Ok(HealthState::Running)
} else {
logger::debug!("Decision engine health check not applicable");
Ok(HealthState::NotApplicable)
}
}
async fn health_check_unified_connector_service(
&self,
) -> CustomResult<HealthState, errors::HealthCheckUnifiedConnectorServiceError> {
if let Some(_ucs_client) = &self.grpc_client.unified_connector_service_client {
// For now, we'll just check if the client exists and is configured
// In the future, this could be enhanced to make an actual health check call
// to the unified connector service if it supports health check endpoints
logger::debug!("Unified Connector Service client is configured and available");
Ok(HealthState::Running)
} else {
logger::debug!("Unified Connector Service client not configured");
Ok(HealthState::NotApplicable)
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payouts.rs | crates/router/src/core/payouts.rs | #[cfg(feature = "olap")]
use strum::IntoEnumIterator;
pub mod access_token;
pub mod helpers;
#[cfg(feature = "payout_retry")]
pub mod retry;
pub mod transformers;
pub mod validator;
use std::{
collections::{HashMap, HashSet},
vec::IntoIter,
};
use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse};
#[cfg(feature = "olap")]
use api_models::{admin::MerchantConnectorInfo, payments as payment_enums};
#[cfg(feature = "payout_retry")]
use common_enums::PayoutRetryType;
use common_utils::{
consts,
ext_traits::{AsyncExt, ValueExt},
id_type::{self, GenerateId},
link_utils::{GenericLinkStatus, GenericLinkUiConfig, PayoutLinkData, PayoutLinkStatus},
types::{MinorUnit, UnifiedCode, UnifiedMessage},
};
use diesel_models::{
enums as storage_enums,
generic_link::{GenericLinkNew, PayoutLink},
CommonMandateReference, PayoutsMandateReference, PayoutsMandateReferenceRecord,
};
use error_stack::{report, ResultExt};
#[cfg(feature = "olap")]
use futures::future::join_all;
use hyperswitch_domain_models::{self as domain_models, payment_methods::PaymentMethod};
use masking::{PeekInterface, Secret};
#[cfg(feature = "payout_retry")]
use retry::GsmValidation;
use router_env::{instrument, logger, tracing, Env};
use scheduler::utils as pt_utils;
use time::Duration;
#[cfg(all(feature = "olap", feature = "payouts"))]
use crate::consts as payout_consts;
#[cfg(feature = "olap")]
use crate::types::domain::behaviour::Conversion;
#[cfg(feature = "olap")]
use crate::types::PayoutActionData;
use crate::{
core::{
errors::{
self, ConnectorErrorExt, CustomResult, RouterResponse, RouterResult, StorageErrorExt,
},
payments::{self, customers, helpers as payment_helpers},
utils as core_utils,
},
db::StorageInterface,
routes::SessionState,
services,
types::{
self,
api::{self, payments as payment_api_types, payouts},
domain,
storage::{self, PaymentRoutingInfo},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::{self, OptionExt},
};
// ********************************************** TYPES **********************************************
#[derive(Clone)]
pub struct PayoutData {
pub billing_address: Option<domain_models::address::Address>,
pub business_profile: domain::Profile,
pub customer_details: Option<domain::Customer>,
pub merchant_connector_account: Option<payment_helpers::MerchantConnectorAccountType>,
pub payouts: storage::Payouts,
pub payout_attempt: storage::PayoutAttempt,
pub payout_method_data: Option<payouts::PayoutMethodData>,
pub profile_id: id_type::ProfileId,
pub should_terminate: bool,
pub payout_link: Option<PayoutLink>,
pub current_locale: String,
pub payment_method: Option<PaymentMethod>,
pub connector_transfer_method_id: Option<String>,
pub browser_info: Option<domain_models::router_request_types::BrowserInformation>,
}
// ********************************************** CORE FLOWS **********************************************
pub fn get_next_connector(
connectors: &mut IntoIter<api::ConnectorRoutingData>,
) -> RouterResult<api::ConnectorRoutingData> {
connectors
.next()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector not found in connectors iterator")
}
#[cfg(all(feature = "payouts", feature = "v1"))]
pub async fn get_connector_choice(
state: &SessionState,
platform: &domain::Platform,
connector: Option<String>,
routing_algorithm: Option<serde_json::Value>,
payout_data: &mut PayoutData,
eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
) -> RouterResult<api::ConnectorCallType> {
let eligible_routable_connectors = eligible_connectors.map(|connectors| {
connectors
.into_iter()
.map(api::enums::RoutableConnectors::from)
.collect()
});
let connector_choice = helpers::get_default_payout_connector(state, routing_algorithm).await?;
match connector_choice {
api::ConnectorChoice::SessionMultiple(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector choice - SessionMultiple")?
}
api::ConnectorChoice::StraightThrough(straight_through) => {
let request_straight_through: api::routing::StraightThroughAlgorithm = straight_through
.clone()
.parse_value("StraightThroughAlgorithm")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid straight through routing rules format")?;
payout_data.payout_attempt.routing_info = Some(straight_through);
let mut routing_data = storage::RoutingData {
routed_through: connector,
merchant_connector_id: None,
algorithm: Some(request_straight_through.clone()),
routing_info: PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
},
};
helpers::decide_payout_connector(
state,
platform,
Some(request_straight_through),
&mut routing_data,
payout_data,
eligible_routable_connectors,
)
.await
}
api::ConnectorChoice::Decide => {
let mut routing_data = storage::RoutingData {
routed_through: connector,
merchant_connector_id: None,
algorithm: None,
routing_info: PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
},
};
helpers::decide_payout_connector(
state,
platform,
None,
&mut routing_data,
payout_data,
eligible_routable_connectors,
)
.await
}
}
}
#[instrument(skip_all)]
pub async fn make_connector_decision(
state: &SessionState,
platform: &domain::Platform,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
match connector_call_type {
api::ConnectorCallType::PreDetermined(routing_data) => {
Box::pin(call_connector_payout(
state,
platform,
&routing_data.connector_data,
payout_data,
))
.await?;
#[cfg(feature = "payout_retry")]
{
let config_bool = retry::config_should_call_gsm_payout(
&*state.store,
platform.get_processor().get_account().get_id(),
PayoutRetryType::SingleConnector,
)
.await;
if config_bool && payout_data.should_call_gsm() {
Box::pin(retry::do_gsm_single_connector_actions(
state,
routing_data.connector_data,
payout_data,
platform,
))
.await?;
}
}
Ok(())
}
api::ConnectorCallType::Retryable(routing_data) => {
let mut routing_data = routing_data.into_iter();
let connector_data = get_next_connector(&mut routing_data)?.connector_data;
Box::pin(call_connector_payout(
state,
platform,
&connector_data,
payout_data,
))
.await?;
#[cfg(feature = "payout_retry")]
{
let config_multiple_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
platform.get_processor().get_account().get_id(),
PayoutRetryType::MultiConnector,
)
.await;
if config_multiple_connector_bool && payout_data.should_call_gsm() {
Box::pin(retry::do_gsm_multiple_connector_actions(
state,
routing_data,
connector_data.clone(),
payout_data,
platform,
))
.await?;
}
let config_single_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
platform.get_processor().get_account().get_id(),
PayoutRetryType::SingleConnector,
)
.await;
if config_single_connector_bool && payout_data.should_call_gsm() {
Box::pin(retry::do_gsm_single_connector_actions(
state,
connector_data,
payout_data,
platform,
))
.await?;
}
}
Ok(())
}
_ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable({
"only PreDetermined and Retryable ConnectorCallTypes are supported".to_string()
})?,
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn payouts_core(
state: &SessionState,
platform: &domain::Platform,
payout_data: &mut PayoutData,
routing_algorithm: Option<serde_json::Value>,
eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt;
// Form connector data
let connector_call_type = get_connector_choice(
state,
platform,
payout_attempt.connector.clone(),
routing_algorithm,
payout_data,
eligible_connectors,
)
.await?;
// Call connector steps
Box::pin(make_connector_decision(
state,
platform,
connector_call_type,
payout_data,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn payouts_core(
state: &SessionState,
platform: &domain::Platform,
payout_data: &mut PayoutData,
routing_algorithm: Option<serde_json::Value>,
eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
) -> RouterResult<()> {
todo!()
}
#[instrument(skip_all)]
pub async fn payouts_create_core(
state: SessionState,
platform: domain::Platform,
req: payouts::PayoutCreateRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
// Validate create request
let (payout_id, payout_method_data, profile_id, customer, payment_method) =
validator::validate_create_request(&state, &platform, &req).await?;
// Create DB entries
let mut payout_data = payout_create_db_entries(
&state,
&platform,
&req,
&payout_id,
&profile_id,
payout_method_data.as_ref(),
&state.locale,
customer.as_ref(),
payment_method.clone(),
)
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let payout_type = payout_data.payouts.payout_type.to_owned();
// Persist payout method data in temp locker
if req.payout_method_data.is_some() {
let customer_id = payout_data
.payouts
.customer_id
.clone()
.get_required_value("customer_id when payout_method_data is provided")?;
payout_data.payout_method_data = helpers::make_payout_method_data(
&state,
req.payout_method_data.as_ref(),
payout_attempt.payout_token.as_deref(),
&customer_id,
&payout_attempt.merchant_id,
payout_type,
platform.get_processor().get_key_store(),
Some(&mut payout_data),
platform.get_processor().get_account().storage_scheme,
)
.await?;
}
if let Some(true) = payout_data.payouts.confirm {
payouts_core(
&state,
&platform,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
)
.await?
};
trigger_webhook_and_handle_response(&state, &platform, &payout_data).await
}
#[instrument(skip_all)]
pub async fn payouts_confirm_core(
state: SessionState,
platform: domain::Platform,
req: payouts::PayoutCreateRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
&state,
&platform,
None,
&payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())),
&state.locale,
))
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
helpers::validate_payout_status_against_not_allowed_statuses(
status,
&[
storage_enums::PayoutStatus::Cancelled,
storage_enums::PayoutStatus::Success,
storage_enums::PayoutStatus::Failed,
storage_enums::PayoutStatus::Pending,
storage_enums::PayoutStatus::Ineligible,
storage_enums::PayoutStatus::RequiresFulfillment,
storage_enums::PayoutStatus::RequiresVendorAccountCreation,
],
"confirm",
)?;
helpers::update_payouts_and_payout_attempt(&mut payout_data, &platform, &req, &state).await?;
let db = &*state.store;
payout_data.payout_link = payout_data
.payout_link
.clone()
.async_map(|pl| async move {
let payout_link_update = storage::PayoutLinkUpdate::StatusUpdate {
link_status: PayoutLinkStatus::Submitted,
};
db.update_payout_link(pl, payout_link_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout links in db")
})
.await
.transpose()?;
payouts_core(
&state,
&platform,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
)
.await?;
trigger_webhook_and_handle_response(&state, &platform, &payout_data).await
}
pub async fn payouts_update_core(
state: SessionState,
platform: domain::Platform,
req: payouts::PayoutCreateRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let payout_id = req.payout_id.clone().get_required_value("payout_id")?;
let mut payout_data = Box::pin(make_payout_data(
&state,
&platform,
None,
&payouts::PayoutRequest::PayoutCreateRequest(Box::new(req.to_owned())),
&state.locale,
))
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
// Verify update feasibility
if helpers::is_payout_terminal_state(status) || helpers::is_payout_initiated(status) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Payout {} cannot be updated for status {status}",
payout_id.get_string_repr()
),
}));
}
helpers::update_payouts_and_payout_attempt(&mut payout_data, &platform, &req, &state).await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
if (req.connector.is_none(), payout_attempt.connector.is_some()) != (true, true) {
// if the connector is not updated but was provided during payout create
payout_data.payout_attempt.connector = None;
payout_data.payout_attempt.routing_info = None;
};
// Update payout method data in temp locker
if req.payout_method_data.is_some() {
let customer_id = payout_data
.payouts
.customer_id
.clone()
.get_required_value("customer_id when payout_method_data is provided")?;
payout_data.payout_method_data = helpers::make_payout_method_data(
&state,
req.payout_method_data.as_ref(),
payout_attempt.payout_token.as_deref(),
&customer_id,
&payout_attempt.merchant_id,
payout_data.payouts.payout_type,
platform.get_processor().get_key_store(),
Some(&mut payout_data),
platform.get_processor().get_account().storage_scheme,
)
.await?;
}
if let Some(true) = payout_data.payouts.confirm {
payouts_core(
&state,
&platform,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
)
.await?;
}
trigger_webhook_and_handle_response(&state, &platform, &payout_data).await
}
#[cfg(all(feature = "payouts", feature = "v1"))]
#[instrument(skip_all)]
pub async fn payouts_retrieve_core(
state: SessionState,
platform: domain::Platform,
profile_id: Option<id_type::ProfileId>,
req: payouts::PayoutRetrieveRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
&state,
&platform,
profile_id,
&payouts::PayoutRequest::PayoutRetrieveRequest(req.to_owned()),
&state.locale,
))
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
if matches!(req.force_sync, Some(true)) && helpers::should_call_retrieve(status) {
// Form connector data
let connector_call_type = get_connector_choice(
&state,
&platform,
payout_attempt.connector.clone(),
None,
&mut payout_data,
None,
)
.await?;
Box::pin(complete_payout_retrieve(
&state,
&platform,
connector_call_type,
&mut payout_data,
))
.await?;
}
Ok(services::ApplicationResponse::Json(
response_handler(&state, &platform, &payout_data).await?,
))
}
#[instrument(skip_all)]
pub async fn payouts_cancel_core(
state: SessionState,
platform: domain::Platform,
req: payouts::PayoutActionRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
&state,
&platform,
None,
&payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),
&state.locale,
))
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
// Verify if cancellation can be triggered
if helpers::is_payout_terminal_state(status) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Payout {:?} cannot be cancelled for status {}",
payout_attempt.payout_id, status
),
}));
// Make local cancellation
} else if helpers::is_eligible_for_local_payout_cancellation(status) {
let status = storage_enums::PayoutStatus::Cancelled;
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_attempt.connector_payout_id.to_owned(),
status,
error_message: Some("Cancelled by user".to_string()),
error_code: None,
is_eligible: None,
unified_code: None,
unified_message: None,
payout_connector_metadata: None,
};
payout_data.payout_attempt = state
.store
.update_payout_attempt(
&payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = state
.store
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
// Trigger connector's cancellation
} else {
// Form connector data
let connector_data = match &payout_attempt.connector {
Some(connector) => api::ConnectorData::get_payout_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
payout_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?,
_ => Err(errors::ApplicationError::InvalidConfigurationValueError(
"Connector not found in payout_attempt - should not reach here".to_string(),
))
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector",
})
.attach_printable("Connector not found for payout cancellation")?,
};
Box::pin(cancel_payout(
&state,
&platform,
&connector_data,
&mut payout_data,
))
.await
.attach_printable("Payout cancellation failed for given Payout request")?;
}
Ok(services::ApplicationResponse::Json(
response_handler(&state, &platform, &payout_data).await?,
))
}
#[instrument(skip_all)]
pub async fn payouts_fulfill_core(
state: SessionState,
platform: domain::Platform,
req: payouts::PayoutActionRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
&state,
&platform,
None,
&payouts::PayoutRequest::PayoutActionRequest(req.to_owned()),
&state.locale,
))
.await?;
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
// Verify if fulfillment can be triggered
if helpers::is_payout_terminal_state(status)
|| status != api_enums::PayoutStatus::RequiresFulfillment
{
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Payout {:?} cannot be fulfilled for status {}",
payout_attempt.payout_id, status
),
}));
}
// Form connector data
let connector_data = match &payout_attempt.connector {
Some(connector) => api::ConnectorData::get_payout_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
payout_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?,
_ => Err(errors::ApplicationError::InvalidConfigurationValueError(
"Connector not found in payout_attempt - should not reach here.".to_string(),
))
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector",
})
.attach_printable("Connector not found for payout fulfillment")?,
};
helpers::fetch_payout_method_data(&state, &mut payout_data, &connector_data, &platform).await?;
Box::pin(fulfill_payout(
&state,
&platform,
&connector_data,
&mut payout_data,
))
.await
.attach_printable("Payout fulfillment failed for given Payout request")?;
trigger_webhook_and_handle_response(&state, &platform, &payout_data).await
}
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn payouts_list_core(
_state: SessionState,
_platform: domain::Platform,
_profile_id_list: Option<Vec<id_type::ProfileId>>,
_constraints: payouts::PayoutListConstraints,
) -> RouterResponse<payouts::PayoutListResponse> {
todo!()
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn payouts_list_core(
state: SessionState,
platform: domain::Platform,
profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: payouts::PayoutListConstraints,
) -> RouterResponse<payouts::PayoutListResponse> {
validator::validate_payout_list_request(&constraints)?;
let merchant_id = platform.get_processor().get_account().get_id();
let db = state.store.as_ref();
let payouts = helpers::filter_by_constraints(
db,
&constraints,
merchant_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts);
let mut pi_pa_tuple_vec = PayoutActionData::new();
for payout in payouts {
match db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
&utils::get_payout_attempt_id(
payout.payout_id.get_string_repr(),
payout.attempt_count,
),
storage_enums::MerchantStorageScheme::PostgresOnly,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
{
Ok(payout_attempt) => {
let domain_customer = match payout.customer_id.clone() {
#[cfg(feature = "v1")]
Some(customer_id) => db
.find_customer_by_customer_id_merchant_id(
&customer_id,
merchant_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.map_err(|err| {
let err_msg = format!(
"failed while fetching customer for customer_id - {customer_id:?}",
);
logger::warn!(?err, err_msg);
})
.ok(),
_ => None,
};
let payout_id_as_payment_id_type =
id_type::PaymentId::wrap(payout.payout_id.get_string_repr().to_string())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "payout_id contains invalid data".to_string(),
})
.attach_printable("Error converting payout_id to PaymentId type")?;
let payment_addr = payment_helpers::create_or_find_address_for_payment_by_request(
&state,
None,
payout.address_id.as_deref(),
merchant_id,
payout.customer_id.as_ref(),
platform.get_processor().get_key_store(),
&payout_id_as_payment_id_type,
platform.get_processor().get_account().storage_scheme,
)
.await
.transpose()
.and_then(|addr| {
addr.map_err(|err| {
let err_msg = format!(
"billing_address missing for address_id : {:?}",
payout.address_id
);
logger::warn!(?err, err_msg);
})
.ok()
.as_ref()
.map(domain_models::address::Address::from)
.map(payment_enums::Address::from)
});
pi_pa_tuple_vec.push((
payout.to_owned(),
payout_attempt.to_owned(),
domain_customer,
payment_addr,
));
}
Err(err) => {
let err_msg = format!(
"failed while fetching payout_attempt for payout_id - {:?}",
payout.payout_id
);
logger::warn!(?err, err_msg);
}
}
}
let data: Vec<api::PayoutCreateResponse> = pi_pa_tuple_vec
.into_iter()
.map(ForeignFrom::foreign_from)
.collect();
Ok(services::ApplicationResponse::Json(
api::PayoutListResponse {
size: data.len(),
data,
total_count: None,
},
))
}
#[cfg(feature = "olap")]
pub async fn payouts_filtered_list_core(
state: SessionState,
platform: domain::Platform,
profile_id_list: Option<Vec<id_type::ProfileId>>,
filters: payouts::PayoutListFilterConstraints,
) -> RouterResponse<payouts::PayoutListResponse> {
let limit = &filters.limit;
validator::validate_payout_list_request_for_joins(*limit)?;
let db = state.store.as_ref();
let constraints = filters.clone().into();
let list: Vec<(
storage::Payouts,
storage::PayoutAttempt,
Option<diesel_models::Customer>,
Option<diesel_models::Address>,
)> = db
.filter_payouts_and_attempts(
platform.get_processor().get_account().get_id(),
&constraints,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let list = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, list);
let data: Vec<api::PayoutCreateResponse> =
join_all(list.into_iter().map(|(p, pa, customer, address)| async {
let customer: Option<domain::Customer> = customer
.async_and_then(|cust| async {
domain::Customer::convert_back(
&(&state).into(),
cust,
&(platform.get_processor().get_key_store().clone()).key,
platform
.get_processor()
.get_key_store()
.merchant_id
.clone()
.into(),
)
.await
.map_err(|err| {
let msg = format!("failed to convert customer for id: {:?}", p.customer_id);
logger::warn!(?err, msg);
})
.ok()
})
.await;
let payout_addr: Option<payment_enums::Address> = address
.async_and_then(|addr| async {
domain::Address::convert_back(
&(&state).into(),
addr,
&(platform.get_processor().get_key_store().clone()).key,
platform
.get_processor()
.get_key_store()
.merchant_id
.clone()
.into(),
)
.await
.map(ForeignFrom::foreign_from)
.map_err(|err| {
let msg = format!("failed to convert address for id: {:?}", p.address_id);
logger::warn!(?err, msg);
})
.ok()
})
.await;
Some((p, pa, customer, payout_addr))
}))
.await
.into_iter()
.flatten()
.map(ForeignFrom::foreign_from)
.collect();
let active_payout_ids = db
.filter_active_payout_ids_by_constraints(
platform.get_processor().get_account().get_id(),
&constraints,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to filter active payout ids based on the constraints")?;
let total_count = db
.get_total_count_of_filtered_payouts(
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/utils.rs | crates/router/src/core/utils.rs | 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::{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_data_v2::flow_common_types::VaultConnectorFlowData,
router_request_types,
types::{OrderDetailsWithAmount, 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";
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,
_platform: &domain::Platform,
_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,
platform: &domain::Platform,
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 webhook_url = helpers::create_webhook_url(
&state.base_url,
&platform.get_processor().get_account().get_id().to_owned(),
merchant_connector_account
.get_mca_id()
.get_required_value("merchant_connector_id")?
.get_string_repr(),
);
let connector_transfer_method_id =
payout_helpers::should_create_connector_transfer_method(&*payout_data, connector_data)?;
let browser_info = payout_data.browser_info.to_owned();
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: platform.get_processor().get_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: get_payout_connector_customer_id(
connector_data,
connector_customer_id.clone(),
&customer_details.to_owned().map(|c| c.customer_id),
&payout_data.payment_method,
&payout_data.payout_attempt,
)?,
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(),
payment_method_type: None,
connector_auth_type,
description: payout_data.payouts.description.clone(),
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,
webhook_url: Some(webhook_url),
browser_info,
payout_connector_metadata: payout_attempt.payout_connector_metadata.to_owned(),
additional_payout_method_data: payout_attempt.additional_payout_method_data.to_owned(),
},
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,
payout_id: Some(payouts.payout_id.get_string_repr().to_string()),
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,
authorized_amount: 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,
platform: &domain::Platform,
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(),
platform.get_processor().get_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
.connector_metadata
.as_ref()
.and_then(|cm| cm.braintree.clone());
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: platform.get_processor().get_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,
payment_method_type: Some(payment_attempt.payment_method_subtype),
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,
payout_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,
authorized_amount: 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,
platform: &domain::Platform,
money: (MinorUnit, enums::Currency),
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
refund: &'a diesel_refund::Refund,
split_refunds: Option<router_request_types::SplitRefundsRequest>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> RouterResult<types::RefundsRouterData<F>> {
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 = payment_attempt
.payment_method
.get_required_value("payment_method")
.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(),
platform.get_processor().get_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: platform.get_processor().get_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: payment_attempt.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,
payout_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,
authorized_amount: 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 {
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 =
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/conditional_config.rs | crates/router/src/core/conditional_config.rs | #[cfg(feature = "v2")]
use api_models::conditional_configs::DecisionManagerRequest;
use api_models::conditional_configs::{
DecisionManager, DecisionManagerRecord, DecisionManagerResponse,
};
use common_utils::ext_traits::StringExt;
#[cfg(feature = "v2")]
use common_utils::types::keymanager::KeyManagerState;
use error_stack::ResultExt;
use crate::{
core::errors::{self, RouterResponse},
routes::SessionState,
services::api as service_api,
types::domain,
};
#[cfg(feature = "v2")]
pub async fn upsert_conditional_config(
state: SessionState,
key_store: domain::MerchantKeyStore,
request: DecisionManagerRequest,
profile: domain::Profile,
) -> RouterResponse<common_types::payments::DecisionManagerRecord> {
use common_utils::ext_traits::OptionExt;
let key_manager_state: &KeyManagerState = &(&state).into();
let db = &*state.store;
let name = request.name;
let program = request.program;
let timestamp = common_utils::date_time::now_unix_timestamp();
euclid::frontend::ast::lowering::lower_program(program.clone())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid Request Data".to_string(),
})
.attach_printable("The Request has an Invalid Comparison")?;
let decision_manager_record = common_types::payments::DecisionManagerRecord {
name,
program,
created_at: timestamp,
};
let business_profile_update = domain::ProfileUpdate::DecisionManagerRecordUpdate {
three_ds_decision_manager_config: decision_manager_record,
};
let updated_profile = db
.update_profile_by_profile_id(&key_store, profile, business_profile_update)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update decision manager record in business profile")?;
Ok(service_api::ApplicationResponse::Json(
updated_profile
.three_ds_decision_manager_config
.clone()
.get_required_value("three_ds_decision_manager_config")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to get updated decision manager record in business profile",
)?,
))
}
#[cfg(feature = "v1")]
pub async fn upsert_conditional_config(
state: SessionState,
platform: domain::Platform,
request: DecisionManager,
) -> RouterResponse<DecisionManagerRecord> {
use common_utils::ext_traits::{Encode, OptionExt, ValueExt};
use diesel_models::configs;
use storage_impl::redis::cache;
use super::routing::helpers::update_merchant_active_algorithm_ref;
let db = state.store.as_ref();
let (name, prog) = match request {
DecisionManager::DecisionManagerv0(ccr) => {
let name = ccr.name;
let prog = ccr
.algorithm
.get_required_value("algorithm")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "algorithm",
})
.attach_printable("Algorithm for config not given")?;
(name, prog)
}
DecisionManager::DecisionManagerv1(dmr) => {
let name = dmr.name;
let prog = dmr
.program
.get_required_value("program")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "program",
})
.attach_printable("Program for config not given")?;
(name, prog)
}
};
let timestamp = common_utils::date_time::now_unix_timestamp();
let mut algo_id: api_models::routing::RoutingAlgorithmRef = platform
.get_processor()
.get_account()
.routing_algorithm
.clone()
.map(|val| val.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
let key = platform
.get_processor()
.get_account()
.get_id()
.get_payment_config_routing_id();
let read_config_key = db.find_config_by_key(&key).await;
euclid::frontend::ast::lowering::lower_program(prog.clone())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid Request Data".to_string(),
})
.attach_printable("The Request has an Invalid Comparison")?;
match read_config_key {
Ok(config) => {
let previous_record: DecisionManagerRecord = config
.config
.parse_struct("DecisionManagerRecord")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The Payment Config Key Not Found")?;
let new_algo = DecisionManagerRecord {
name: previous_record.name,
program: prog,
modified_at: timestamp,
created_at: previous_record.created_at,
};
let serialize_updated_str = new_algo
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize config to string")?;
let updated_config = configs::ConfigUpdate::Update {
config: Some(serialize_updated_str),
};
db.update_config_by_key(&key, updated_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error serializing the config")?;
algo_id.update_conditional_config_id(key.clone());
let config_key = cache::CacheKind::DecisionManager(key.into());
update_merchant_active_algorithm_ref(
&state,
platform.get_processor().get_key_store(),
config_key,
algo_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
Ok(service_api::ApplicationResponse::Json(new_algo))
}
Err(e) if e.current_context().is_db_not_found() => {
let new_rec = DecisionManagerRecord {
name: name
.get_required_value("name")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "name",
})
.attach_printable("name of the config not found")?,
program: prog,
modified_at: timestamp,
created_at: timestamp,
};
let serialized_str = new_rec
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error serializing the config")?;
let new_config = configs::ConfigNew {
key: key.clone(),
config: serialized_str,
};
db.insert_config(new_config)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching the config")?;
algo_id.update_conditional_config_id(key.clone());
let config_key = cache::CacheKind::DecisionManager(key.into());
update_merchant_active_algorithm_ref(
&state,
platform.get_processor().get_key_store(),
config_key,
algo_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
Ok(service_api::ApplicationResponse::Json(new_rec))
}
Err(e) => Err(e)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching payment config"),
}
}
#[cfg(feature = "v2")]
pub async fn delete_conditional_config(
_state: SessionState,
_platform: domain::Platform,
) -> RouterResponse<()> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn delete_conditional_config(
state: SessionState,
platform: domain::Platform,
) -> RouterResponse<()> {
use common_utils::ext_traits::ValueExt;
use storage_impl::redis::cache;
use super::routing::helpers::update_merchant_active_algorithm_ref;
let db = state.store.as_ref();
let key = platform
.get_processor()
.get_account()
.get_id()
.get_payment_config_routing_id();
let mut algo_id: api_models::routing::RoutingAlgorithmRef = platform
.get_processor()
.get_account()
.routing_algorithm
.clone()
.map(|value| value.parse_value("routing algorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the conditional_config algorithm")?
.unwrap_or_default();
algo_id.config_algo_id = None;
let config_key = cache::CacheKind::DecisionManager(key.clone().into());
update_merchant_active_algorithm_ref(
&state,
platform.get_processor().get_key_store(),
config_key,
algo_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update deleted algorithm ref")?;
db.delete_config_by_key(&key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete routing config from DB")?;
Ok(service_api::ApplicationResponse::StatusOk)
}
#[cfg(feature = "v1")]
pub async fn retrieve_conditional_config(
state: SessionState,
platform: domain::Platform,
) -> RouterResponse<DecisionManagerResponse> {
let db = state.store.as_ref();
let algorithm_id = platform
.get_processor()
.get_account()
.get_id()
.get_payment_config_routing_id();
let algo_config = db
.find_config_by_key(&algorithm_id)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("The conditional config was not found in the DB")?;
let record: DecisionManagerRecord = algo_config
.config
.parse_struct("ConditionalConfigRecord")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The Conditional Config Record was not found")?;
let response = DecisionManagerRecord {
name: record.name,
program: record.program,
created_at: record.created_at,
modified_at: record.modified_at,
};
Ok(service_api::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn retrieve_conditional_config(
state: SessionState,
key_store: domain::MerchantKeyStore,
profile: domain::Profile,
) -> RouterResponse<common_types::payments::DecisionManagerResponse> {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &(&state).into();
let profile_id = profile.get_id();
let record = profile
.three_ds_decision_manager_config
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The Conditional Config Record was not found")?;
let response = common_types::payments::DecisionManagerRecord {
name: record.name,
program: record.program,
created_at: record.created_at,
};
Ok(service_api::ApplicationResponse::Json(response))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/verify_connector.rs | crates/router/src/core/verify_connector.rs | use api_models::{enums::Connector, verify_connector::VerifyConnectorRequest};
use error_stack::ResultExt;
use crate::{
connector,
core::errors,
services,
types::{
api::{
self,
verify_connector::{self as types, VerifyConnector},
},
transformers::ForeignInto,
},
utils::verify_connector as utils,
SessionState,
};
pub async fn verify_connector_credentials(
state: SessionState,
req: VerifyConnectorRequest,
_profile_id: Option<common_utils::id_type::ProfileId>,
) -> errors::RouterResponse<()> {
let boxed_connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&req.connector_name.to_string(),
api::GetToken::Connector,
None,
)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?;
let card_details = utils::get_test_card_details(req.connector_name)?.ok_or(
errors::ApiErrorResponse::FlowNotSupported {
flow: "Verify credentials".to_string(),
connector: req.connector_name.to_string(),
},
)?;
match req.connector_name {
Connector::Stripe => {
connector::Stripe::verify(
&state,
types::VerifyConnectorData {
connector: boxed_connector.connector,
connector_auth: req.connector_account_details.foreign_into(),
card_details,
},
)
.await
}
Connector::Paypal => connector::Paypal::get_access_token(
&state,
types::VerifyConnectorData {
connector: boxed_connector.connector,
connector_auth: req.connector_account_details.foreign_into(),
card_details,
},
)
.await
.map(|_| services::ApplicationResponse::StatusOk),
_ => Err(errors::ApiErrorResponse::FlowNotSupported {
flow: "Verify credentials".to_string(),
connector: req.connector_name.to_string(),
}
.into()),
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/chat.rs | crates/router/src/core/chat.rs | use api_models::chat as chat_api;
use common_utils::{
consts,
crypto::{DecodeMessage, GcmAes256},
errors::CustomResult,
request::{Method, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use external_services::http_client;
use hyperswitch_domain_models::chat as chat_domain;
use masking::ExposeInterface;
use router_env::{
instrument, logger,
tracing::{self, Instrument},
};
use crate::{
db::errors::chat::ChatErrors,
routes::{app::SessionStateInfo, SessionState},
services::{authentication as auth, authorization::roles, ApplicationResponse},
utils,
};
#[instrument(skip_all, fields(?session_id))]
pub async fn get_data_from_hyperswitch_ai_workflow(
state: SessionState,
user_from_token: auth::UserFromToken,
req: chat_api::ChatRequest,
session_id: Option<&str>,
) -> CustomResult<ApplicationResponse<chat_api::ChatResponse>, ChatErrors> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
let url = format!(
"{}/webhook",
state.conf.chat.get_inner().hyperswitch_ai_host
);
let request_id = state
.get_request_id()
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let request_body = chat_domain::HyperswitchAiDataRequest {
query: chat_domain::GetDataMessage {
message: req.message.clone(),
},
org_id: user_from_token.org_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
profile_id: user_from_token.profile_id.clone(),
entity_type: role_info.get_entity_type(),
};
logger::info!("Request for AI service: {:?}", request_body);
let mut request_builder = RequestBuilder::new()
.method(Method::Post)
.url(&url)
.attach_default_headers()
.header(consts::X_REQUEST_ID, &request_id)
.set_body(RequestContent::Json(Box::new(request_body.clone())));
if let Some(session_id) = session_id {
request_builder = request_builder.header(consts::X_CHAT_SESSION_ID, session_id);
}
let request = request_builder.build();
let response = http_client::send_request(
&state.conf.proxy,
request,
Some(consts::REQUEST_TIME_OUT_FOR_AI_SERVICE),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when sending request to AI service")?
.json::<chat_api::ChatResponse>()
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when deserializing response from AI service")?;
let response_to_return = response.clone();
tokio::spawn(
async move {
let new_hyperswitch_ai_interaction = utils::chat::construct_hyperswitch_ai_interaction(
&state,
&user_from_token,
&req,
&response,
&request_id,
)
.await;
match new_hyperswitch_ai_interaction {
Ok(interaction) => {
let db = state.store.as_ref();
if let Err(e) = db.insert_hyperswitch_ai_interaction(interaction).await {
logger::error!("Failed to insert hyperswitch_ai_interaction: {:?}", e);
}
}
Err(e) => {
logger::error!("Failed to construct hyperswitch_ai_interaction: {:?}", e);
}
}
}
.in_current_span(),
);
Ok(ApplicationResponse::Json(response_to_return))
}
#[instrument(skip_all)]
pub async fn list_chat_conversations(
state: SessionState,
user_from_token: auth::UserFromToken,
req: chat_api::ChatListRequest,
) -> CustomResult<ApplicationResponse<chat_api::ChatListResponse>, ChatErrors> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to retrieve role information")?;
if !role_info.is_internal() {
return Err(error_stack::Report::new(ChatErrors::UnauthorizedAccess)
.attach_printable("Only internal roles are allowed for this operation"));
}
let db = state.store.as_ref();
let hyperswitch_ai_interactions = db
.list_hyperswitch_ai_interactions(
req.merchant_id,
req.limit.unwrap_or(consts::DEFAULT_LIST_LIMIT),
req.offset.unwrap_or(consts::DEFAULT_LIST_OFFSET),
)
.await
.change_context(ChatErrors::InternalServerError)
.attach_printable("Error when fetching hyperswitch_ai_interactions")?;
let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose();
let key = match hex::decode(&encryption_key) {
Ok(key) => key,
Err(e) => {
router_env::logger::error!("Failed to decode encryption key: {}", e);
encryption_key.as_bytes().to_vec()
}
};
let mut conversations = Vec::new();
for interaction in hyperswitch_ai_interactions {
let user_query_encrypted = interaction
.user_query
.ok_or(ChatErrors::InternalServerError)
.attach_printable("Missing user_query field in hyperswitch_ai_interaction")?;
let response_encrypted = interaction
.response
.ok_or(ChatErrors::InternalServerError)
.attach_printable("Missing response field in hyperswitch_ai_interaction")?;
let user_query_decrypted_bytes = GcmAes256
.decode_message(&key, user_query_encrypted.into_inner())
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to decrypt user query")?;
let response_decrypted_bytes = GcmAes256
.decode_message(&key, response_encrypted.into_inner())
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to decrypt response")?;
let user_query_decrypted = String::from_utf8(user_query_decrypted_bytes)
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to convert decrypted user query to string")?;
let response_decrypted = serde_json::from_slice(&response_decrypted_bytes)
.change_context(ChatErrors::InternalServerError)
.attach_printable("Failed to deserialize decrypted response")?;
conversations.push(chat_api::ChatConversation {
id: interaction.id,
session_id: interaction.session_id,
user_id: interaction.user_id,
merchant_id: interaction.merchant_id,
profile_id: interaction.profile_id,
org_id: interaction.org_id,
role_id: interaction.role_id,
user_query: user_query_decrypted.into(),
response: response_decrypted,
database_query: interaction.database_query,
interaction_status: interaction.interaction_status,
created_at: interaction.created_at,
});
}
return Ok(ApplicationResponse::Json(chat_api::ChatListResponse {
conversations,
}));
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/gsm.rs | crates/router/src/core/gsm.rs | use api_models::gsm as gsm_api_types;
use error_stack::ResultExt;
use router_env::{instrument, tracing};
use crate::{
core::errors::{self, RouterResponse, StorageErrorExt},
db::gsm::GsmInterface,
services,
types::transformers::{ForeignFrom, ForeignInto},
SessionState,
};
#[instrument(skip_all)]
pub async fn create_gsm_rule(
state: SessionState,
gsm_rule: gsm_api_types::GsmCreateRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
GsmInterface::add_gsm_rule(db, gsm_rule.foreign_into())
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "GSM with given key already exists in our records".to_string(),
})
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
#[instrument(skip_all)]
pub async fn retrieve_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmRetrieveRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmRetrieveRequest {
connector,
flow,
sub_flow,
code,
message,
} = gsm_request;
GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
#[instrument(skip_all)]
pub async fn update_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmUpdateRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
let connector = gsm_request.connector.clone();
let flow = gsm_request.flow.clone();
let code = gsm_request.code.clone();
let sub_flow = gsm_request.sub_flow.clone();
let message = gsm_request.message.clone();
let gsm_db_record =
GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})?;
let inferred_feature_info = <(
common_enums::GsmFeature,
common_types::domain::GsmFeatureData,
)>::foreign_from((&gsm_request, gsm_db_record));
let gsm_api_types::GsmUpdateRequest {
connector,
flow,
sub_flow,
code,
message,
decision,
status,
router_error,
step_up_possible,
unified_code,
unified_message,
error_category,
clear_pan_possible,
feature,
feature_data,
standardised_code,
description,
user_guidance_message,
} = gsm_request;
GsmInterface::update_gsm_rule(
db,
connector.to_string(),
flow,
sub_flow,
code,
message,
hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate {
decision,
status,
router_error: Some(router_error),
step_up_possible: feature_data
.as_ref()
.and_then(|feature_data| feature_data.get_retry_feature_data())
.map(|retry_feature_data| retry_feature_data.is_step_up_possible())
.or(step_up_possible),
unified_code,
unified_message,
error_category,
clear_pan_possible: feature_data
.as_ref()
.and_then(|feature_data| feature_data.get_retry_feature_data())
.map(|retry_feature_data| retry_feature_data.is_clear_pan_possible())
.or(clear_pan_possible),
feature_data: feature_data.or(Some(inferred_feature_info.1)),
feature: feature.or(Some(inferred_feature_info.0)),
standardised_code,
description,
user_guidance_message,
},
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while updating Gsm rule")
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
#[instrument(skip_all)]
pub async fn delete_gsm_rule(
state: SessionState,
gsm_request: gsm_api_types::GsmDeleteRequest,
) -> RouterResponse<gsm_api_types::GsmDeleteResponse> {
let db = state.store.as_ref();
let gsm_api_types::GsmDeleteRequest {
connector,
flow,
sub_flow,
code,
message,
} = gsm_request;
match GsmInterface::delete_gsm_rule(
db,
connector.to_string(),
flow.to_owned(),
sub_flow.to_owned(),
code.to_owned(),
message.to_owned(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "GSM with given key does not exist in our records".to_string(),
})
.attach_printable("Failed while Deleting Gsm rule")
{
Ok(is_deleted) => {
if is_deleted {
Ok(services::ApplicationResponse::Json(
gsm_api_types::GsmDeleteResponse {
gsm_rule_delete: true,
connector,
flow,
sub_flow,
code,
},
))
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while Deleting Gsm rule, got response as false")
}
}
Err(err) => Err(err),
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payment_methods.rs | crates/router/src/core/payment_methods.rs | pub mod access_token;
#[cfg(feature = "v1")]
pub mod batch_retrieve;
pub mod cards;
pub mod migration;
pub mod network_tokenization;
pub mod surcharge_decision_configs;
#[cfg(feature = "v1")]
pub mod tokenize;
pub mod transformers;
pub mod utils;
mod validator;
pub mod vault;
use std::borrow::Cow;
#[cfg(feature = "v1")]
use std::collections::HashSet;
#[cfg(feature = "v2")]
use std::str::FromStr;
#[cfg(feature = "v2")]
pub use api_models::enums as api_enums;
pub use api_models::enums::Connector;
use api_models::payment_methods;
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
#[cfg(feature = "v1")]
use common_utils::{consts::DEFAULT_LOCALE, ext_traits::OptionExt};
#[cfg(feature = "v2")]
use common_utils::{
crypto::{EncodeMessage, Encryptable, GcmAes256},
encryption::Encryption,
errors::CustomResult,
ext_traits::{AsyncExt, ValueExt},
fp_utils::when,
generate_id, types as util_types,
};
use common_utils::{ext_traits::Encode, id_type};
use diesel_models::{
enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData,
};
use error_stack::{report, ResultExt};
#[cfg(feature = "v2")]
use futures::TryStreamExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::behaviour::Conversion;
use hyperswitch_domain_models::{
payments::{payment_attempt::PaymentAttempt, PaymentIntent, VaultData},
router_data_v2::flow_common_types::VaultConnectorFlowData,
router_flow_types::ExternalVaultInsertFlow,
types::VaultRouterData,
};
use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion;
use masking::{PeekInterface, Secret};
use router_env::{instrument, tracing};
use time::Duration;
#[cfg(feature = "v2")]
use super::payments::tokenization;
use super::{
errors::{RouterResponse, StorageErrorExt},
pm_auth,
};
#[cfg(feature = "v2")]
use crate::{
configs::settings,
core::{payment_methods::transformers as pm_transforms, tokenization as tokenization_core},
headers,
routes::{self, payment_methods as pm_routes},
services::encryption,
types::{
api::PaymentMethodCreateExt,
domain::types as domain_types,
storage::{ephemeral_key, PaymentMethodListContext},
transformers::{ForeignFrom, ForeignTryFrom},
Tokenizable,
},
utils::ext_traits::OptionExt,
};
use crate::{
consts,
core::{
errors::{ProcessTrackerError, RouterResult},
payments::{self as payments_core, helpers as payment_helpers},
utils as core_utils,
},
db::errors::ConnectorErrorExt,
errors, logger,
routes::{app::StorageInterface, SessionState},
services,
types::{
self, api, domain, payment_methods as pm_types,
storage::{self, enums as storage_enums},
},
};
const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE";
const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS";
#[instrument(skip_all)]
pub async fn retrieve_payment_method_core(
pm_data: &Option<domain::PaymentMethodData>,
state: &SessionState,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<(Option<domain::PaymentMethodData>, Option<String>)> {
match pm_data {
pm_opt @ Some(pm @ domain::PaymentMethodData::Card(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::Card,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::BankDebit(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::BankDebit,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
pm @ Some(domain::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::RealTimePayment(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::MobilePayment(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::NetworkToken(_)) => Ok((pm.to_owned(), None)),
pm_opt @ Some(pm @ domain::PaymentMethodData::BankTransfer(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::BankTransfer,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::Wallet(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::Wallet,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::BankRedirect(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::BankRedirect,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
_ => Ok((None, None)),
}
}
pub async fn initiate_pm_collect_link(
state: SessionState,
platform: domain::Platform,
req: payment_methods::PaymentMethodCollectLinkRequest,
) -> RouterResponse<payment_methods::PaymentMethodCollectLinkResponse> {
// Validate request and initiate flow
let pm_collect_link_data =
validator::validate_request_and_initiate_payment_method_collect_link(
&state, &platform, &req,
)
.await?;
// Create DB entry
let pm_collect_link = create_pm_collect_db_entry(
&state,
&platform,
&pm_collect_link_data,
req.return_url.clone(),
)
.await?;
let customer_id = id_type::CustomerId::try_from(Cow::from(pm_collect_link.primary_reference))
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_id",
})?;
// Return response
let url = pm_collect_link.url.peek();
let response = payment_methods::PaymentMethodCollectLinkResponse {
pm_collect_link_id: pm_collect_link.link_id,
customer_id,
expiry: pm_collect_link.expiry,
link: url::Url::parse(url)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("Failed to parse the payment method collect link - {url}")
})?
.into(),
return_url: pm_collect_link.return_url,
ui_config: pm_collect_link.link_data.ui_config,
enabled_payment_methods: pm_collect_link.link_data.enabled_payment_methods,
};
Ok(services::ApplicationResponse::Json(response))
}
pub async fn create_pm_collect_db_entry(
state: &SessionState,
platform: &domain::Platform,
pm_collect_link_data: &PaymentMethodCollectLinkData,
return_url: Option<String>,
) -> RouterResult<PaymentMethodCollectLink> {
let db: &dyn StorageInterface = &*state.store;
let link_data = serde_json::to_value(pm_collect_link_data)
.map_err(|_| report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable("Failed to convert PaymentMethodCollectLinkData to Value")?;
let pm_collect_link = GenericLinkNew {
link_id: pm_collect_link_data.pm_collect_link_id.to_string(),
primary_reference: pm_collect_link_data
.customer_id
.get_string_repr()
.to_string(),
merchant_id: platform.get_processor().get_account().get_id().to_owned(),
link_type: common_enums::GenericLinkType::PaymentMethodCollect,
link_data,
url: pm_collect_link_data.link.clone(),
return_url,
expiry: common_utils::date_time::now()
+ Duration::seconds(pm_collect_link_data.session_expiry.into()),
..Default::default()
};
db.insert_pm_collect_link(pm_collect_link)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "payment method collect link already exists".to_string(),
})
}
#[cfg(feature = "v2")]
pub async fn render_pm_collect_link(
_state: SessionState,
_platform: domain::Platform,
_req: payment_methods::PaymentMethodCollectLinkRenderRequest,
) -> RouterResponse<services::GenericLinkFormData> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn render_pm_collect_link(
state: SessionState,
provider: domain::Provider,
req: payment_methods::PaymentMethodCollectLinkRenderRequest,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
// Fetch pm collect link
let pm_collect_link = db
.find_pm_collect_link_by_link_id(&req.pm_collect_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method collect link not found".to_string(),
})?;
// Check status and return form data accordingly
let has_expired = common_utils::date_time::now() > pm_collect_link.expiry;
let status = pm_collect_link.link_status;
let link_data = pm_collect_link.link_data;
let default_config = &state.conf.generic_link.payment_method_collect;
let default_ui_config = default_config.ui_config.clone();
let ui_config_data = common_utils::link_utils::GenericLinkUiConfigFormData {
merchant_name: link_data
.ui_config
.merchant_name
.unwrap_or(default_ui_config.merchant_name),
logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo),
theme: link_data
.ui_config
.theme
.clone()
.unwrap_or(default_ui_config.theme.clone()),
};
match status {
common_utils::link_utils::PaymentMethodCollectStatus::Initiated => {
// if expired, send back expired status page
if has_expired {
let expired_link_data = services::GenericExpiredLinkData {
title: "Payment collect link has expired".to_string(),
message: "This payment collect link has expired.".to_string(),
theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::ExpiredLink(expired_link_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
// else, send back form link
} else {
let customer_id = id_type::CustomerId::try_from(Cow::from(
pm_collect_link.primary_reference.clone(),
))
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_id",
})?;
// Fetch customer
let customer = db
.find_customer_by_customer_id_merchant_id(
&customer_id,
&req.merchant_id,
provider.get_key_store(),
provider.get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Customer [{}] not found for link_id - {}",
pm_collect_link.primary_reference, pm_collect_link.link_id
),
})
.attach_printable(format!(
"customer [{}] not found",
pm_collect_link.primary_reference
))?;
let js_data = payment_methods::PaymentMethodCollectLinkDetails {
publishable_key: Secret::new(provider.get_account().clone().publishable_key),
client_secret: link_data.client_secret.clone(),
pm_collect_link_id: pm_collect_link.link_id,
customer_id: customer.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link.return_url,
ui_config: ui_config_data,
enabled_payment_methods: link_data.enabled_payment_methods,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")?
);
let generic_form_data = services::GenericLinkFormData {
js_data: serialized_js_content,
css_data: serialized_css_content,
sdk_url: default_config.sdk_url.clone(),
html_meta_tags: String::new(),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollect(generic_form_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
// Send back status page
status => {
let js_data = payment_methods::PaymentMethodCollectLinkStatusDetails {
pm_collect_link_id: pm_collect_link.link_id,
customer_id: link_data.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to parse return URL for payment method collect's status link",
)?,
ui_config: ui_config_data,
status,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to serialize PaymentMethodCollectLinkStatusDetails"
)?
);
let generic_status_data = services::GenericLinkStatusData {
js_data: serialized_js_content,
css_data: serialized_css_content,
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
}
fn generate_task_id_for_payment_method_status_update_workflow(
key_id: &str,
runner: storage::ProcessTrackerRunner,
task: &str,
) -> String {
format!("{runner}_{task}_{key_id}")
}
#[cfg(feature = "v1")]
pub async fn add_payment_method_status_update_task(
db: &dyn StorageInterface,
payment_method: &domain::PaymentMethod,
prev_status: enums::PaymentMethodStatus,
curr_status: enums::PaymentMethodStatus,
merchant_id: &id_type::MerchantId,
application_source: common_enums::ApplicationSource,
) -> Result<(), ProcessTrackerError> {
let created_at = payment_method.created_at;
let schedule_time =
created_at.saturating_add(Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
let tracking_data = storage::PaymentMethodStatusTrackingData {
payment_method_id: payment_method.get_id().clone(),
prev_status,
curr_status,
merchant_id: merchant_id.to_owned(),
};
let runner = storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow;
let task = PAYMENT_METHOD_STATUS_UPDATE_TASK;
let tag = [PAYMENT_METHOD_STATUS_TAG];
let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow(
payment_method.get_id().as_str(),
runner,
task,
);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
application_source,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct PAYMENT_METHOD_STATUS_UPDATE process tracker task")?;
db
.insert_process(process_tracker_entry)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while inserting PAYMENT_METHOD_STATUS_UPDATE reminder to process_tracker for payment_method_id: {}",
payment_method.get_id().clone()
)
})?;
Ok(())
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_with_token(
_state: &SessionState,
_merchant_key_store: &domain::MerchantKeyStore,
_token_data: &storage::PaymentTokenData,
_payment_intent: &PaymentIntent,
_card_token_data: Option<&domain::CardToken>,
_customer: &Option<domain::Customer>,
_storage_scheme: common_enums::enums::MerchantStorageScheme,
_mandate_id: Option<api_models::payments::MandateIds>,
_payment_method_info: Option<domain::PaymentMethod>,
_business_profile: &domain::Profile,
) -> RouterResult<storage::PaymentMethodDataWithId> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_payment_method_with_token(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
card_token_data: Option<&domain::CardToken>,
customer: &Option<domain::Customer>,
storage_scheme: common_enums::enums::MerchantStorageScheme,
mandate_id: Option<api_models::payments::MandateIds>,
payment_method_info: Option<domain::PaymentMethod>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
vault_data: Option<&VaultData>,
) -> RouterResult<storage::PaymentMethodDataWithId> {
let token = match token_data {
storage::PaymentTokenData::TemporaryGeneric(generic_token) => {
payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
payment_attempt,
merchant_key_store,
card_token_data,
)
.await?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: None,
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::Temporary(generic_token) => {
payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
payment_attempt,
merchant_key_store,
card_token_data,
)
.await?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: None,
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::Permanent(card_token) => {
payment_helpers::retrieve_payment_method_data_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token),
payment_intent,
card_token_data,
merchant_key_store,
storage_scheme,
mandate_id,
payment_method_info
.get_required_value("PaymentMethod")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("PaymentMethod not found")?,
business_profile,
payment_attempt.connector.clone(),
should_retry_with_pan,
vault_data,
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: Some(
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token)
.to_string(),
),
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::PermanentCard(card_token) => {
payment_helpers::retrieve_payment_method_data_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token),
payment_intent,
card_token_data,
merchant_key_store,
storage_scheme,
mandate_id,
payment_method_info
.get_required_value("PaymentMethod")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("PaymentMethod not found")?,
business_profile,
payment_attempt.connector.clone(),
should_retry_with_pan,
vault_data,
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: Some(
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token)
.to_string(),
),
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::AuthBankDebit(auth_token) => {
pm_auth::retrieve_payment_method_from_auth_service(
state,
merchant_key_store,
auth_token,
payment_intent,
customer,
)
.await?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: None,
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::WalletToken(_) => storage::PaymentMethodDataWithId {
payment_method: None,
payment_method_data: None,
payment_method_id: None,
},
// TODO: Locker support for BankDebit will be added in a future PR, currently keeping
// these fields as None
storage::PaymentTokenData::BankDebit(_) => storage::PaymentMethodDataWithId {
payment_method: None,
payment_method_data: None,
payment_method_id: None,
},
};
Ok(token)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub(crate) fn get_payment_method_create_request(
payment_method_data: &api_models::payments::PaymentMethodData,
payment_method_type: storage_enums::PaymentMethod,
payment_method_subtype: storage_enums::PaymentMethodType,
customer_id: Option<id_type::GlobalCustomerId>,
billing_address: Option<&api_models::payments::Address>,
payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>,
storage_type: Option<common_enums::StorageType>,
) -> RouterResult<payment_methods::PaymentMethodCreate> {
match payment_method_data {
api_models::payments::PaymentMethodData::Card(card) => {
let card_detail = payment_methods::CardDetail {
card_number: card.card_number.clone(),
card_exp_month: card.card_exp_month.clone(),
card_exp_year: card.card_exp_year.clone(),
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
card_issuing_country: card
.card_issuing_country
.as_ref()
.map(|c| api_enums::CountryAlpha2::from_str(c))
.transpose()
.ok()
.flatten(),
card_network: card.card_network.clone(),
card_issuer: card.card_issuer.clone(),
card_type: card
.card_type
.as_ref()
.map(|c| payment_methods::CardType::from_str(c))
.transpose()
.ok()
.flatten(),
card_cvc: Some(card.card_cvc.clone()),
};
let payment_method_request = payment_methods::PaymentMethodCreate {
payment_method_type,
payment_method_subtype,
metadata: None,
customer_id,
payment_method_data: payment_methods::PaymentMethodCreateData::Card(card_detail),
billing: billing_address.map(ToOwned::to_owned),
psp_tokenization: payment_method_session
.and_then(|pm_session| pm_session.psp_tokenization.clone()),
network_tokenization: payment_method_session
.and_then(|pm_session| pm_session.network_tokenization.clone()),
storage_type,
};
Ok(payment_method_request)
}
_ => Err(report!(errors::ApiErrorResponse::UnprocessableEntity {
message: "only card payment methods are supported for tokenization".to_string()
})
.attach_printable("Payment method data is incorrect")),
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub(crate) async fn get_payment_method_create_request(
payment_method_data: Option<&domain::PaymentMethodData>,
payment_method: Option<storage_enums::PaymentMethod>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
customer_id: &Option<id_type::CustomerId>,
billing_name: Option<Secret<String>>,
payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>,
) -> RouterResult<payment_methods::PaymentMethodCreate> {
match payment_method_data {
Some(pm_data) => match payment_method {
Some(payment_method) => match pm_data {
domain::PaymentMethodData::Card(card) => {
let card_network = get_card_network_with_us_local_debit_network_override(
card.card_network.clone(),
card.co_badged_card_data.as_ref(),
);
let card_detail = payment_methods::CardDetail {
card_number: card.card_number.clone(),
card_exp_month: card.card_exp_month.clone(),
card_exp_year: card.card_exp_year.clone(),
card_holder_name: billing_name,
nick_name: card.nick_name.clone(),
card_issuing_country: card.card_issuing_country.clone(),
card_issuing_country_code: card.card_issuing_country_code.clone(),
card_network: card_network.clone(),
card_issuer: card.card_issuer.clone(),
card_type: card.card_type.clone(),
card_cvc: None, // DO NOT POPULATE CVC FOR ADDITIONAL PAYMENT METHOD DATA
};
let payment_method_request = payment_methods::PaymentMethodCreate {
payment_method: Some(payment_method),
payment_method_type,
payment_method_issuer: card.card_issuer.clone(),
payment_method_issuer_code: None,
#[cfg(feature = "payouts")]
bank_transfer: None,
#[cfg(feature = "payouts")]
wallet: None,
card: Some(card_detail),
metadata: None,
customer_id: customer_id.clone(),
card_network: card_network
.clone()
.as_ref()
.map(|card_network| card_network.to_string()),
client_secret: None,
payment_method_data: None,
//TODO: why are we using api model in router internally
billing: payment_method_billing_address.cloned().map(From::from),
connector_mandate_details: None,
network_transaction_id: None,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/currency.rs | crates/router/src/core/currency.rs | use analytics::errors::AnalyticsError;
use common_utils::errors::CustomResult;
use currency_conversion::types::ExchangeRates;
use error_stack::ResultExt;
use router_env::logger;
use crate::{
consts::DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS,
core::errors::ApiErrorResponse,
services::ApplicationResponse,
utils::currency::{self, convert_currency, get_forex_rates, ForexError as ForexCacheError},
SessionState,
};
pub async fn retrieve_forex(
state: SessionState,
) -> CustomResult<ApplicationResponse<currency::FxExchangeRatesCacheEntry>, ApiErrorResponse> {
let forex_api = state.conf.forex_api.get_inner();
Ok(ApplicationResponse::Json(
get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds)
.await
.change_context(ApiErrorResponse::GenericNotFoundError {
message: "Unable to fetch forex rates".to_string(),
})?,
))
}
pub async fn convert_forex(
state: SessionState,
amount: i64,
to_currency: String,
from_currency: String,
) -> CustomResult<
ApplicationResponse<api_models::currency::CurrencyConversionResponse>,
ApiErrorResponse,
> {
Ok(ApplicationResponse::Json(
Box::pin(convert_currency(
state.clone(),
amount,
to_currency,
from_currency,
))
.await
.change_context(ApiErrorResponse::InternalServerError)?,
))
}
pub async fn get_forex_exchange_rates(
state: SessionState,
) -> CustomResult<ExchangeRates, AnalyticsError> {
let forex_api = state.conf.forex_api.get_inner();
let mut attempt = 1;
logger::info!("Starting forex exchange rates fetch");
loop {
logger::info!("Attempting to fetch forex rates - Attempt {attempt} of {DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS}");
match get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds).await {
Ok(rates) => {
logger::info!("Successfully fetched forex rates");
return Ok((*rates.data).clone());
}
Err(error) => {
let is_retryable = matches!(
error.current_context(),
ForexCacheError::CouldNotAcquireLock
| ForexCacheError::EntryNotFound
| ForexCacheError::ForexDataUnavailable
| ForexCacheError::LocalReadError
| ForexCacheError::LocalWriteError
| ForexCacheError::RedisConnectionError
| ForexCacheError::RedisLockReleaseFailed
| ForexCacheError::RedisWriteError
| ForexCacheError::WriteLockNotAcquired
);
if !is_retryable {
return Err(error.change_context(AnalyticsError::ForexFetchFailed));
}
if attempt >= DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS {
logger::error!("Failed to fetch forex rates after {DEFAULT_ANALYTICS_FOREX_RETRY_ATTEMPTS} attempts");
return Err(error.change_context(AnalyticsError::ForexFetchFailed));
}
logger::warn!(
"Forex rates fetch failed with retryable error, retrying in {attempt} seconds"
);
tokio::time::sleep(std::time::Duration::from_secs(attempt * 2)).await;
attempt += 1;
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/authentication.rs | crates/router/src/core/authentication.rs | pub(crate) mod utils;
pub mod transformers;
pub mod types;
use api_models::payments;
use common_enums::Currency;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use hyperswitch_domain_models::authentication;
use masking::ExposeInterface;
use super::errors::StorageErrorExt;
use crate::{
core::{errors::ApiErrorResponse, payments as payments_core},
routes::SessionState,
types::{
self as core_types, api,
domain::{self},
},
utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata,
};
#[allow(clippy::too_many_arguments)]
pub async fn perform_authentication(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
payment_method_data: domain::PaymentMethodData,
payment_method: common_enums::PaymentMethod,
billing_address: hyperswitch_domain_models::address::Address,
shipping_address: Option<hyperswitch_domain_models::address::Address>,
browser_details: Option<core_types::BrowserInformation>,
merchant_connector_account: payments_core::helpers::MerchantConnectorAccountType,
amount: Option<common_utils::types::MinorUnit>,
currency: Option<Currency>,
message_category: api::authentication::MessageCategory,
device_channel: payments::DeviceChannel,
authentication_data: authentication::Authentication,
return_url: Option<String>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
webhook_url: String,
three_ds_requestor_url: String,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
payment_id: common_utils::id_type::PaymentId,
force_3ds_challenge: bool,
merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
) -> CustomResult<api::authentication::AuthenticationResponse, ApiErrorResponse> {
let router_data = transformers::construct_authentication_router_data(
state,
merchant_id,
authentication_connector.clone(),
payment_method_data,
payment_method,
billing_address.clone(),
shipping_address.clone(),
browser_details.clone(),
amount,
currency,
message_category,
device_channel,
merchant_connector_account,
authentication_data.clone(),
return_url,
sdk_information.clone(),
threeds_method_comp_ind,
email.clone(),
webhook_url,
three_ds_requestor_url,
psd2_sca_exemption_type,
payment_id,
force_3ds_challenge,
)?;
let response = Box::pin(utils::do_auth_connector_call(
state,
authentication_connector.clone(),
router_data,
))
.await?;
let authentication_info =
hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {
billing_address: Some(billing_address),
shipping_address,
browser_info: browser_details,
email,
device_details: sdk_information
.and_then(|sdk_information| sdk_information.device_details),
merchant_category_code: None,
merchant_country_code: None,
};
let authentication = Box::pin(utils::update_trackers(
state,
response.clone(),
authentication_data,
None,
merchant_key_store,
authentication_info,
))
.await?;
response
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: authentication_connector,
status_code: err.status_code,
reason: err.reason,
})?;
api::authentication::AuthenticationResponse::try_from(authentication)
}
pub async fn perform_post_authentication(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: domain::Profile,
authentication_id: common_utils::id_type::AuthenticationId,
payment_id: &common_utils::id_type::PaymentId,
) -> CustomResult<
hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,
ApiErrorResponse,
> {
let key_state = &state.into();
let (authentication_connector, three_ds_connector_account) =
utils::get_authentication_connector_data(state, key_store, &business_profile, None).await?;
let is_pull_mechanism_enabled =
check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
three_ds_connector_account
.get_metadata()
.map(|metadata| metadata.expose()),
);
let authentication = state
.store
.find_authentication_by_merchant_id_authentication_id(
&business_profile.merchant_id,
&authentication_id,
key_store,
key_state,
)
.await
.to_not_found_response(ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Error while fetching authentication record with authentication_id {}",
authentication_id.get_string_repr()
)
})?;
let authentication_update = if !authentication.authentication_status.is_terminal_status()
&& is_pull_mechanism_enabled
{
// trigger in case of authenticate flow
let router_data = transformers::construct_post_authentication_router_data(
state,
authentication_connector.to_string(),
business_profile,
three_ds_connector_account,
&authentication,
payment_id,
)?;
let router_data =
utils::do_auth_connector_call(state, authentication_connector.to_string(), router_data)
.await?;
let authentication_info =
hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {
billing_address: None,
shipping_address: None,
browser_info: None,
email: None,
device_details: None,
merchant_category_code: None,
merchant_country_code: None,
};
utils::update_trackers(
state,
router_data,
authentication,
None,
key_store,
authentication_info,
)
.await?
} else {
// trigger in case of webhook flow
authentication
};
// getting authentication value from temp locker before moving ahead with authrisation
let tokenized_data = crate::core::payment_methods::vault::get_tokenized_data(
state,
authentication_id.get_string_repr(),
false,
key_store.key.get_inner(),
)
.await
.inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err))
.attach_printable("cavv not present after authentication flow")
.ok();
let authentication_store =
hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: tokenized_data.map(|data| masking::Secret::new(data.value1)),
authentication: authentication_update,
};
Ok(authentication_store)
}
#[allow(clippy::too_many_arguments)]
pub async fn perform_pre_authentication(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
card: hyperswitch_domain_models::payment_method_data::Card,
token: String,
business_profile: &domain::Profile,
acquirer_details: Option<types::AcquirerDetails>,
payment_id: common_utils::id_type::PaymentId,
organization_id: common_utils::id_type::OrganizationId,
force_3ds_challenge: Option<bool>,
psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
billing_address: Option<hyperswitch_domain_models::address::Address>,
shipping_address: Option<hyperswitch_domain_models::address::Address>,
) -> CustomResult<
hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,
ApiErrorResponse,
> {
let (authentication_connector, three_ds_connector_account) =
utils::get_authentication_connector_data(state, key_store, business_profile, None).await?;
let authentication_connector_name = authentication_connector.to_string();
let authentication = utils::create_new_authentication(
state,
business_profile.merchant_id.clone(),
authentication_connector_name.clone(),
token,
business_profile.get_id().to_owned(),
payment_id.clone(),
three_ds_connector_account
.get_mca_id()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Error while finding mca_id from merchant_connector_account")?,
organization_id,
force_3ds_challenge,
psd2_sca_exemption_type,
key_store,
)
.await?;
let authentication = if authentication_connector.is_separate_version_call_required() {
let router_data: core_types::authentication::PreAuthNVersionCallRouterData =
transformers::construct_pre_authentication_router_data(
state,
authentication_connector_name.clone(),
card.clone(),
&three_ds_connector_account,
business_profile.merchant_id.clone(),
payment_id.clone(),
)?;
let router_data = utils::do_auth_connector_call(
state,
authentication_connector_name.clone(),
router_data,
)
.await?;
let authentication_info =
hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {
billing_address: billing_address.clone(),
shipping_address: shipping_address.clone(),
browser_info: None,
email: None,
device_details: None,
merchant_category_code: None,
merchant_country_code: None,
};
let updated_authentication = utils::update_trackers(
state,
router_data,
authentication,
acquirer_details.clone(),
key_store,
authentication_info,
)
.await?;
// from version call response, we will get to know the maximum supported 3ds version.
// If the version is not greater than or equal to 3DS 2.0, We should not do the successive pre authentication call.
if !updated_authentication.is_separate_authn_required() {
return Ok(hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore{
authentication: updated_authentication,
cavv: None, // since cavv wont be present in pre_authentication step
});
}
updated_authentication
} else {
authentication
};
let router_data: core_types::authentication::PreAuthNRouterData =
transformers::construct_pre_authentication_router_data(
state,
authentication_connector_name.clone(),
card,
&three_ds_connector_account,
business_profile.merchant_id.clone(),
payment_id,
)?;
let router_data =
utils::do_auth_connector_call(state, authentication_connector_name, router_data).await?;
let authentication_info =
hyperswitch_domain_models::router_request_types::authentication::AuthenticationInfo {
billing_address,
shipping_address,
browser_info: None,
email: None,
device_details: None,
merchant_category_code: None,
merchant_country_code: None,
};
let authentication_update = utils::update_trackers(
state,
router_data,
authentication,
acquirer_details,
key_store,
authentication_info,
)
.await?;
Ok(
hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
authentication: authentication_update,
cavv: None, // since cavv wont be present in pre_authentication step
},
)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/files.rs | crates/router/src/core/files.rs | pub mod helpers;
use api_models::files;
use error_stack::ResultExt;
use super::errors::{self, RouterResponse};
use crate::{
consts,
routes::SessionState,
services::ApplicationResponse,
types::{api, domain},
};
pub async fn files_create_core(
state: SessionState,
platform: domain::Platform,
create_file_request: api::CreateFileRequest,
) -> RouterResponse<files::CreateFileResponse> {
helpers::validate_file_upload(&state, platform.clone(), create_file_request.clone()).await?;
let file_id = common_utils::generate_id(consts::ID_LENGTH, "file");
let file_key = format!(
"{}/{}",
platform
.get_processor()
.get_account()
.get_id()
.get_string_repr(),
file_id
);
let file_new: diesel_models::FileMetadataNew = diesel_models::file::FileMetadataNew {
file_id: file_id.clone(),
merchant_id: platform.get_processor().get_account().get_id().clone(),
file_name: create_file_request.file_name.clone(),
file_size: create_file_request.file_size,
file_type: create_file_request.file_type.to_string(),
provider_file_id: None,
file_upload_provider: None,
available: false,
connector_label: None,
profile_id: None,
merchant_connector_id: None,
};
let file_metadata_object = state
.store
.insert_file_metadata(file_new)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert file_metadata")?;
let (provider_file_id, file_upload_provider, profile_id, merchant_connector_id) = Box::pin(
helpers::upload_and_get_provider_provider_file_id_profile_id(
&state,
&platform,
&create_file_request,
file_key.clone(),
),
)
.await?;
// Update file metadata
let update_file_metadata = diesel_models::file::FileMetadataUpdate::Update {
provider_file_id: Some(provider_file_id),
file_upload_provider: Some(file_upload_provider),
available: true,
profile_id,
merchant_connector_id,
};
state
.store
.as_ref()
.update_file_metadata(file_metadata_object, update_file_metadata)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("Unable to update file_metadata with file_id: {file_id}")
})?;
Ok(ApplicationResponse::Json(files::CreateFileResponse {
file_id,
}))
}
pub async fn files_delete_core(
state: SessionState,
platform: domain::Platform,
req: api::FileId,
) -> RouterResponse<serde_json::Value> {
helpers::delete_file_using_file_id(&state, req.file_id.clone(), &platform).await?;
state
.store
.as_ref()
.delete_file_metadata_by_merchant_id_file_id(
platform.get_processor().get_account().get_id(),
&req.file_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to delete file_metadata")?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn files_retrieve_core(
state: SessionState,
platform: domain::Platform,
req: api::FileRetrieveRequest,
) -> RouterResponse<serde_json::Value> {
let file_metadata_object = state
.store
.as_ref()
.find_file_metadata_by_merchant_id_file_id(
platform.get_processor().get_account().get_id(),
&req.file_id,
)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)
.attach_printable("Unable to retrieve file_metadata")?;
let file_info = helpers::retrieve_file_and_provider_file_id_from_file_id(
&state,
Some(req.file_id),
req.dispute_id,
&platform,
api::FileDataRequired::Required,
)
.await?;
let content_type = file_metadata_object
.file_type
.parse::<mime::Mime>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse file content type")?;
Ok(ApplicationResponse::FileData((
file_info
.file_data
.ok_or(errors::ApiErrorResponse::FileNotAvailable)
.attach_printable("File data not found")?,
content_type,
)))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/split_payments.rs | crates/router/src/core/split_payments.rs | use api_models::{
enums,
payments::{
self as payments_api, GetPaymentMethodType, PaymentMethodData,
SplitPaymentMethodDataRequest,
},
};
use common_enums::CallConnectorAction;
use common_utils::{
ext_traits::{OptionExt, ValueExt},
id_type,
types::MinorUnit,
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::payments::{
split_payments, HeaderPayload, PaymentConfirmData, PaymentIntent,
};
use masking::ExposeInterface;
use super::errors::StorageErrorExt;
use crate::{
core::{
errors::{self, RouterResponse},
payment_method_balance,
payments::{
operations::{self, Operation, PaymentIntentConfirm},
payments_operation_core,
transformers::GenerateResponse,
},
},
db::errors::RouterResult,
routes::{app::ReqState, SessionState},
types::{api, domain},
};
pub(crate) struct SplitPaymentResponseData {
pub primary_payment_response_data: PaymentConfirmData<api::Authorize>,
pub secondary_payment_response_data: Vec<PaymentConfirmData<api::Authorize>>,
}
impl SplitPaymentResponseData {
fn get_intent_status(&self) -> common_enums::IntentStatus {
let primary_status = common_enums::IntentStatus::from(
self.primary_payment_response_data.payment_attempt.status,
);
let secondary_status_vec: Vec<common_enums::IntentStatus> = self
.secondary_payment_response_data
.iter()
.map(|elem| common_enums::IntentStatus::from(elem.payment_attempt.status))
.collect();
// If all statuses are the same, return that status
let all_same = secondary_status_vec
.iter()
.all(|status| *status == primary_status);
if all_same {
primary_status
} else {
// Return the last secondary status if array is not empty, otherwise primary status
secondary_status_vec
.last()
.copied()
.unwrap_or(primary_status)
}
}
}
/// This function has been written to support multiple gift cards + at most one non-gift card
/// payment method.
async fn get_payment_method_amount_split(
state: &SessionState,
payment_id: &id_type::GlobalPaymentId,
request: &payments_api::PaymentsConfirmIntentRequest,
payment_intent: &PaymentIntent,
) -> RouterResult<split_payments::PaymentMethodAmountSplit> {
// This function is called inside split payments flow, so its mandatory to have split_payment_method_data
let split_payment_method_data = request
.split_payment_method_data
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("split_payment_method_data not found in split payments flow")?;
// The primary/secondary payment method distinction is decided on the backend. Its irrelevant whether a payment_method
// is received in the top level `payment_method_data` field or inside `split_payment_method_data`
// Add the outer payment_method_data to the PMs inside split_payment_method_data to create a combined Vec and then segregate.
let payment_method_data = SplitPaymentMethodDataRequest {
payment_method_data: request
.payment_method_data
.payment_method_data
.clone()
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_data",
})?,
payment_method_type: request.payment_method_type,
payment_method_subtype: request.payment_method_subtype,
};
let combined_pm_data: Vec<_> = split_payment_method_data
.into_iter()
.chain(std::iter::once(payment_method_data))
.collect();
let (gift_card_pm_data, non_gift_card_pm_data): (Vec<_>, Vec<_>) = combined_pm_data
.into_iter()
.partition(|pm_data| pm_data.payment_method_type.is_gift_card());
// Validate at most one non-gift-card payment method
if non_gift_card_pm_data.len() > 1 {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "At most one non-gift card payment method is allowed".to_string(),
})?
}
// It is possible that non-gift card payment method is not present, e.g. only 2 gift cards were provided
let non_gift_card_pm_data = non_gift_card_pm_data.into_iter().next();
let gift_card_data_vec = gift_card_pm_data
.iter()
.map(|elem| {
if let PaymentMethodData::GiftCard(gift_card_data) = elem.payment_method_data.clone() {
Ok(gift_card_data.as_ref().clone())
} else {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Only Gift Card supported for Split Payments".to_string(),
}))
}
})
.collect::<RouterResult<Vec<_>>>()?;
let balance_check_data_vec = gift_card_data_vec
.iter()
.cloned()
.map(api_models::payments::BalanceCheckPaymentMethodData::GiftCard)
.collect::<Vec<_>>();
let balances = payment_method_balance::fetch_payment_methods_balances_from_redis(
state,
payment_id,
&balance_check_data_vec,
)
.await?;
// TODO: Add surcharge calculation when it is added in v2
let total_amount = payment_intent.amount_details.calculate_net_amount();
let mut remaining_to_allocate = total_amount;
let pm_split_amt_tuple = gift_card_data_vec
.iter()
.filter_map(|gift_card_card| {
if remaining_to_allocate == MinorUnit::zero() {
return None; // Payment already fully covered
}
let pm_balance_key = domain::PaymentMethodBalanceKey {
payment_method_type: common_enums::PaymentMethod::GiftCard,
payment_method_subtype: gift_card_card.get_payment_method_type(),
payment_method_key: domain::GiftCardData::from(gift_card_card.clone())
.get_payment_method_key()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Unable to get unique key for payment method".to_string(),
})
.ok()?
.expose(),
};
let pm_balance = balances
.get(&pm_balance_key)
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment Method Balance not present in Redis")
.ok()?;
// Use minimum of available balance and remaining amount
let amount_to_use = pm_balance.balance.min(remaining_to_allocate);
remaining_to_allocate = remaining_to_allocate - amount_to_use;
Some(Ok(split_payments::PaymentMethodDetailsWithSplitAmount {
split_amount: amount_to_use,
payment_method_details: split_payments::PaymentMethodDetails {
payment_method_data: PaymentMethodData::GiftCard(Box::new(
gift_card_card.to_owned(),
)),
payment_method_type: common_enums::PaymentMethod::GiftCard,
payment_method_subtype: gift_card_card.get_payment_method_type(),
},
}))
})
.collect::<RouterResult<Vec<_>>>()?;
// If the gift card balances are not sufficient for payment, use the non-gift card payment method
// for the remaining amount
if remaining_to_allocate > MinorUnit::zero() {
let non_gift_card_pm =
non_gift_card_pm_data.ok_or(errors::ApiErrorResponse::InvalidRequestData {
message: "Requires additional payment method data".to_string(),
})?;
let non_gift_card_pm_data = split_payments::PaymentMethodDetails {
payment_method_data: non_gift_card_pm.payment_method_data,
payment_method_type: non_gift_card_pm.payment_method_type,
payment_method_subtype: non_gift_card_pm.payment_method_subtype,
};
Ok(split_payments::PaymentMethodAmountSplit {
balance_pm_split: pm_split_amt_tuple,
non_balance_pm_split: Some(split_payments::PaymentMethodDetailsWithSplitAmount {
split_amount: remaining_to_allocate,
payment_method_details: non_gift_card_pm_data,
}),
})
} else {
Ok(split_payments::PaymentMethodAmountSplit {
balance_pm_split: pm_split_amt_tuple,
non_balance_pm_split: None,
})
}
}
pub(crate) async fn split_payments_execute_core(
state: SessionState,
req_state: ReqState,
platform: domain::Platform,
profile: domain::Profile,
request: payments_api::PaymentsConfirmIntentRequest,
header_payload: HeaderPayload,
payment_id: id_type::GlobalPaymentId,
) -> RouterResponse<payments_api::PaymentsResponse> {
let db = &*state.store;
let payment_intent = db
.find_payment_intent_by_id(
&payment_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
if !payment_intent.supports_split_payments() {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Split Payments not enabled in Payment Intent".to_string(),
})?
}
let cell_id = state.conf.cell_information.id.clone();
let attempts_group_id = id_type::GlobalAttemptGroupId::generate(&cell_id);
// Change the active_attempt_id_type of PaymentIntent to `GroupID`. This indicates that the customer
// has attempted a split payment for this intent
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::AttemptGroupUpdate {
updated_by: platform
.get_processor()
.get_account()
.storage_scheme
.to_string(),
active_attempt_id_type: enums::ActiveAttemptIDType::GroupID,
active_attempts_group_id: attempts_group_id.clone(),
};
let payment_intent = db
.update_payment_intent(
payment_intent,
payment_intent_update,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let pm_amount_split =
get_payment_method_amount_split(&state, &payment_id, &request, &payment_intent).await?;
let (
primary_pm_response,
connector_http_status_code,
external_latency,
connector_response_data,
) = {
// If a non-balance Payment Method is present, we will execute that first, otherwise we will execute
// a balance Payment Method
let payment_method_amount_details = pm_amount_split
.non_balance_pm_split
.clone()
.or_else(|| pm_amount_split.balance_pm_split.first().cloned())
.get_required_value("payment method amount split")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("At least one payment method is required")?;
let operation = PaymentIntentConfirm;
let get_tracker_response: operations::GetTrackerResponse<
PaymentConfirmData<api::Authorize>,
> = operation
.to_get_tracker()?
.get_trackers_for_split_payments(
&state,
&payment_id,
&request,
&platform,
&profile,
&header_payload,
payment_method_amount_details,
&attempts_group_id,
)
.await?;
let (
payment_data,
_req,
_customer,
connector_http_status_code,
external_latency,
connector_response_data,
) = Box::pin(payments_operation_core(
&state,
req_state.clone(),
platform.clone(),
&profile,
operation,
request.clone(),
get_tracker_response,
CallConnectorAction::Trigger,
header_payload.clone(),
))
.await?;
// payments_operation_core marks the intent as succeeded when the attempt is succesful
// However, for split case, we can't mark the intent as succesful until all the attempts
// have succeeded, so reverting the state of Payment Intent
if payment_data.payment_intent.is_succeeded() {
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SplitPaymentStatusUpdate {
status: common_enums::IntentStatus::RequiresPaymentMethod,
updated_by: platform
.get_processor()
.get_account()
.storage_scheme
.to_string(),
};
let updated_payment_intent = db
.update_payment_intent(
payment_data.payment_intent.clone(),
payment_intent_update,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
}
(
payment_data,
connector_http_status_code,
external_latency,
connector_response_data,
)
};
let mut split_pm_response_data = SplitPaymentResponseData {
primary_payment_response_data: primary_pm_response,
secondary_payment_response_data: vec![],
};
// We have executed the primary payment method, now get a vector of the secondary payment methods
// If we had a non-balance payment method, it was executed first, so the remaining ones are the balance PMs
// otherwise the first balance payment method was executed, so remove it from the remaining PMs
let remaining_pm_amount_split = if pm_amount_split.non_balance_pm_split.is_some() {
pm_amount_split.balance_pm_split
} else {
pm_amount_split
.balance_pm_split
.iter()
.skip(1)
.cloned()
.collect()
};
for payment_method_amount_details in remaining_pm_amount_split {
let operation = PaymentIntentConfirm;
let get_tracker_response: operations::GetTrackerResponse<
PaymentConfirmData<api::Authorize>,
> = operation
.to_get_tracker()?
.get_trackers_for_split_payments(
&state,
&payment_id,
&request,
&platform,
&profile,
&header_payload,
payment_method_amount_details,
&attempts_group_id,
)
.await?;
let (
payment_data,
_req,
_customer,
_connector_http_status_code,
_external_latency,
_connector_response_data,
) = Box::pin(payments_operation_core(
&state,
req_state.clone(),
platform.clone(),
&profile,
operation,
request.clone(),
get_tracker_response,
CallConnectorAction::Trigger,
header_payload.clone(),
))
.await?;
// payments_operation_core marks the intent as succeeded when the attempt is succesful
// However, for split case, we can't mark the intent as succesful until all the attempts
// have succeeded, so reverting the state of Payment Intent
if payment_data.payment_intent.is_succeeded() {
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SplitPaymentStatusUpdate {
status: common_enums::IntentStatus::RequiresPaymentMethod,
updated_by: platform
.get_processor()
.get_account()
.storage_scheme
.to_string(),
};
let _updated_payment_intent = db
.update_payment_intent(
payment_data.payment_intent.clone(),
payment_intent_update,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
} else {
split_pm_response_data
.secondary_payment_response_data
.push(payment_data);
// Exit the loop if a payment failed
break;
}
split_pm_response_data
.secondary_payment_response_data
.push(payment_data);
}
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SplitPaymentStatusUpdate {
status: split_pm_response_data.get_intent_status(),
updated_by: platform
.get_processor()
.get_account()
.storage_scheme
.to_string(),
};
let _updated_payment_intent = db
.update_payment_intent(
payment_intent,
payment_intent_update,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
split_pm_response_data.generate_response(
&state,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&platform,
&profile,
Some(connector_response_data),
)
}
/// Construct the domain model from the ConfirmIntentRequest and PaymentIntent
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "v2")]
pub async fn create_domain_model_for_split_payment(
payment_intent: &PaymentIntent,
cell_id: id_type::CellId,
storage_scheme: enums::MerchantStorageScheme,
request: &api_models::payments::PaymentsConfirmIntentRequest,
encrypted_data: hyperswitch_domain_models::payments::payment_attempt::DecryptedPaymentAttempt,
split_amount: MinorUnit,
attempts_group_id: &id_type::GlobalAttemptGroupId,
payment_method_type: enums::PaymentMethod,
payment_method_subtype: enums::PaymentMethodType,
) -> common_utils::errors::CustomResult<domain::PaymentAttempt, errors::ApiErrorResponse> {
let id = id_type::GlobalAttemptId::generate(&cell_id);
let intent_amount_details = payment_intent.amount_details.clone();
let attempt_amount_details =
intent_amount_details.create_split_attempt_amount_details(request, split_amount);
let now = common_utils::date_time::now();
let payment_method_billing_address = encrypted_data
.payment_method_billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
let connector_token = Some(diesel_models::ConnectorTokenDetails {
connector_mandate_id: None,
connector_token_request_reference_id: Some(common_utils::generate_id_with_len(
hyperswitch_domain_models::consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)),
});
let authentication_type = payment_intent.authentication_type.unwrap_or_default();
Ok(domain::PaymentAttempt {
payment_id: payment_intent.id.clone(),
merchant_id: payment_intent.merchant_id.clone(),
attempts_group_id: Some(attempts_group_id.to_owned()),
amount_details: attempt_amount_details,
status: common_enums::AttemptStatus::Started,
// This will be decided by the routing algorithm and updated in update trackers
// right before calling the connector
connector: None,
authentication_type,
created_at: now,
modified_at: now,
last_synced: None,
cancellation_reason: None,
browser_info: request.browser_info.clone(),
payment_token: request.payment_token.clone(),
connector_metadata: None,
payment_experience: None,
payment_method_data: None,
routing_result: None,
preprocessing_step_id: None,
multiple_capture_count: None,
connector_response_reference_id: None,
updated_by: storage_scheme.to_string(),
redirection_data: None,
encoded_data: None,
merchant_connector_id: None,
external_three_ds_authentication_attempted: None,
authentication_connector: None,
authentication_id: None,
fingerprint_id: None,
charges: None,
client_source: None,
client_version: None,
customer_acceptance: request
.customer_acceptance
.clone()
.map(masking::Secret::new),
profile_id: payment_intent.profile_id.clone(),
organization_id: payment_intent.organization_id.clone(),
payment_method_type,
payment_method_id: request.payment_method_id.clone(),
connector_payment_id: None,
payment_method_subtype,
authentication_applied: None,
external_reference_id: None,
payment_method_billing_address,
error: None,
connector_token_details: connector_token,
id,
card_discovery: None,
feature_metadata: None,
processor_merchant_id: payment_intent.merchant_id.clone(),
created_by: None,
connector_request_reference_id: None,
network_transaction_id: None,
authorized_amount: None,
})
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/mandate.rs | crates/router/src/core/mandate.rs | pub mod helpers;
pub mod utils;
use api_models::payments;
use common_types::payments as common_payments_types;
use common_utils::{ext_traits::Encode, id_type};
use diesel_models::enums as storage_enums;
use error_stack::{report, ResultExt};
use futures::future;
use router_env::{instrument, logger, tracing};
use super::payments::helpers as payment_helper;
use crate::{
core::{
errors::{self, RouterResponse, StorageErrorExt},
payments::CallConnectorAction,
},
db::StorageInterface,
routes::{metrics, SessionState},
services,
types::{
self,
api::{
mandates::{self, MandateResponseExt},
ConnectorData, GetToken,
},
domain,
storage::{self, enums::MerchantStorageScheme},
transformers::ForeignFrom,
},
utils::OptionExt,
};
#[instrument(skip(state))]
pub async fn get_mandate(
state: SessionState,
platform: domain::Platform,
req: mandates::MandateId,
) -> RouterResponse<mandates::MandateResponse> {
let mandate = state
.store
.as_ref()
.find_mandate_by_merchant_id_mandate_id(
platform.get_processor().get_account().get_id(),
&req.mandate_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
Ok(services::ApplicationResponse::Json(
mandates::MandateResponse::from_db_mandate(
&state,
platform.get_processor().get_key_store().clone(),
mandate,
platform.get_processor().get_account(),
)
.await?,
))
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn revoke_mandate(
state: SessionState,
platform: domain::Platform,
req: mandates::MandateId,
) -> RouterResponse<mandates::MandateRevokedResponse> {
let db = state.store.as_ref();
let mandate = db
.find_mandate_by_merchant_id_mandate_id(
platform.get_processor().get_account().get_id(),
&req.mandate_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
match mandate.mandate_status {
common_enums::MandateStatus::Active
| common_enums::MandateStatus::Inactive
| common_enums::MandateStatus::Pending => {
let profile_id =
helpers::get_profile_id_for_mandate(&state, &platform, mandate.clone()).await?;
let merchant_connector_account = payment_helper::get_merchant_connector_account(
&state,
platform.get_processor().get_account().get_id(),
None,
platform.get_processor().get_key_store(),
&profile_id,
&mandate.connector.clone(),
mandate.merchant_connector_id.as_ref(),
)
.await?;
let connector_data = ConnectorData::get_connector_by_name(
&state.conf.connectors,
&mandate.connector,
GetToken::Connector,
mandate.merchant_connector_id.clone(),
)?;
let connector_integration: services::BoxedMandateRevokeConnectorIntegrationInterface<
types::api::MandateRevoke,
types::MandateRevokeRequestData,
types::MandateRevokeResponseData,
> = connector_data.connector.get_connector_integration();
let router_data = utils::construct_mandate_revoke_router_data(
&state,
merchant_connector_account,
&platform,
mandate.clone(),
)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match response.response {
Ok(_) => {
let update_mandate = db
.update_mandate_by_merchant_id_mandate_id(
platform.get_processor().get_account().get_id(),
&req.mandate_id,
storage::MandateUpdate::StatusUpdate {
mandate_status: storage::enums::MandateStatus::Revoked,
},
mandate,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
Ok(services::ApplicationResponse::Json(
mandates::MandateRevokedResponse {
mandate_id: update_mandate.mandate_id,
status: update_mandate.mandate_status,
error_code: None,
error_message: None,
},
))
}
Err(err) => Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: mandate.connector,
status_code: err.status_code,
reason: err.reason,
}
.into()),
}
}
common_enums::MandateStatus::Revoked => {
Err(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Mandate has already been revoked".to_string(),
}
.into())
}
}
}
#[instrument(skip(db))]
pub async fn update_connector_mandate_id(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
mandate_ids_opt: Option<String>,
payment_method_id: Option<String>,
resp: Result<types::PaymentsResponseData, types::ErrorResponse>,
storage_scheme: MerchantStorageScheme,
) -> RouterResponse<mandates::MandateResponse> {
let mandate_details = Option::foreign_from(resp);
let connector_mandate_id = mandate_details
.clone()
.map(|md| {
md.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(masking::Secret::new)
})
.transpose()?;
//Ignore updation if the payment_attempt mandate_id or connector_mandate_id is not present
if let Some((mandate_id, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, &mandate_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::MandateNotFound)?;
let update_mandate_details = match payment_method_id {
Some(pmd_id) => storage::MandateUpdate::ConnectorMandateIdUpdate {
connector_mandate_id: mandate_details
.and_then(|mandate_reference| mandate_reference.connector_mandate_id),
connector_mandate_ids: Some(connector_id),
payment_method_id: pmd_id,
original_payment_id: None,
},
None => storage::MandateUpdate::ConnectorReferenceUpdate {
connector_mandate_ids: Some(connector_id),
},
};
// only update the connector_mandate_id if existing is none
if mandate.connector_mandate_id.is_none() {
db.update_mandate_by_merchant_id_mandate_id(
merchant_id,
&mandate_id,
update_mandate_details,
mandate,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::MandateUpdateFailed)?;
}
}
Ok(services::ApplicationResponse::StatusOk)
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn get_customer_mandates(
state: SessionState,
platform: domain::Platform,
customer_id: id_type::CustomerId,
) -> RouterResponse<Vec<mandates::MandateResponse>> {
let mandates = state
.store
.find_mandate_by_merchant_id_customer_id(
platform.get_processor().get_account().get_id(),
&customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while finding mandate: merchant_id: {:?}, customer_id: {:?}",
platform.get_processor().get_account().get_id(),
customer_id,
)
})?;
if mandates.is_empty() {
Err(report!(errors::ApiErrorResponse::MandateNotFound).attach_printable("No Mandate found"))
} else {
let mut response_vec = Vec::with_capacity(mandates.len());
for mandate in mandates {
response_vec.push(
mandates::MandateResponse::from_db_mandate(
&state,
platform.get_processor().get_key_store().clone(),
mandate,
platform.get_processor().get_account(),
)
.await?,
);
}
Ok(services::ApplicationResponse::Json(response_vec))
}
}
fn get_insensitive_payment_method_data_if_exists<F, FData>(
router_data: &types::RouterData<F, FData, types::PaymentsResponseData>,
) -> Option<domain::PaymentMethodData>
where
FData: MandateBehaviour,
{
match &router_data.request.get_payment_method_data() {
domain::PaymentMethodData::Card(_) => None,
_ => Some(router_data.request.get_payment_method_data()),
}
}
pub async fn mandate_procedure<F, FData>(
state: &SessionState,
resp: &types::RouterData<F, FData, types::PaymentsResponseData>,
customer_id: &Option<id_type::CustomerId>,
pm_id: Option<String>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
storage_scheme: MerchantStorageScheme,
payment_id: &id_type::PaymentId,
) -> errors::RouterResult<Option<String>>
where
FData: MandateBehaviour,
{
let Ok(ref response) = resp.response else {
return Ok(None);
};
match resp.request.get_mandate_id() {
Some(mandate_id) => {
let Some(ref mandate_id) = mandate_id.mandate_id else {
return Ok(None);
};
let orig_mandate = state
.store
.find_mandate_by_merchant_id_mandate_id(
&resp.merchant_id,
mandate_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
let mandate = match orig_mandate.mandate_type {
storage_enums::MandateType::SingleUse => state
.store
.update_mandate_by_merchant_id_mandate_id(
&resp.merchant_id,
mandate_id,
storage::MandateUpdate::StatusUpdate {
mandate_status: storage_enums::MandateStatus::Revoked,
},
orig_mandate,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::MandateUpdateFailed),
storage_enums::MandateType::MultiUse => state
.store
.update_mandate_by_merchant_id_mandate_id(
&resp.merchant_id,
mandate_id,
storage::MandateUpdate::CaptureAmountUpdate {
amount_captured: Some(
orig_mandate.amount_captured.unwrap_or(0)
+ resp.request.get_amount(),
),
},
orig_mandate,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::MandateUpdateFailed),
}?;
metrics::SUBSEQUENT_MANDATE_PAYMENT.add(
1,
router_env::metric_attributes!(("connector", mandate.connector)),
);
Ok(Some(mandate_id.clone()))
}
None => {
let Some(_mandate_details) = resp.request.get_setup_mandate_details() else {
return Ok(None);
};
let (mandate_reference, network_txn_id) = match &response {
types::PaymentsResponseData::TransactionResponse {
mandate_reference,
network_txn_id,
..
} => (mandate_reference.clone(), network_txn_id.clone()),
_ => (Box::new(None), None),
};
let mandate_ids = (*mandate_reference)
.as_ref()
.map(|md| {
md.encode_to_value()
.change_context(errors::ApiErrorResponse::MandateSerializationFailed)
.map(masking::Secret::new)
})
.transpose()?;
let Some(new_mandate_data) = payment_helper::generate_mandate(
resp.merchant_id.clone(),
payment_id.to_owned(),
resp.connector.clone(),
resp.request.get_setup_mandate_details().cloned(),
customer_id,
pm_id.get_required_value("payment_method_id")?,
mandate_ids,
network_txn_id,
get_insensitive_payment_method_data_if_exists(resp),
*mandate_reference,
merchant_connector_id,
)?
else {
return Ok(None);
};
let connector = new_mandate_data.connector.clone();
logger::debug!("{:?}", new_mandate_data);
let res_mandate_id = new_mandate_data.mandate_id.clone();
state
.store
.insert_mandate(new_mandate_data, storage_scheme)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMandate)?;
metrics::MANDATE_COUNT.add(1, router_env::metric_attributes!(("connector", connector)));
Ok(Some(res_mandate_id))
}
}
}
#[instrument(skip(state))]
pub async fn retrieve_mandates_list(
state: SessionState,
platform: domain::Platform,
constraints: api_models::mandates::MandateListConstraints,
) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> {
let mandates = state
.store
.as_ref()
.find_mandates_by_merchant_id(platform.get_processor().get_account().get_id(), constraints)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to retrieve mandates")?;
let mandates_list = future::try_join_all(mandates.into_iter().map(|mandate| {
mandates::MandateResponse::from_db_mandate(
&state,
platform.get_processor().get_key_store().clone(),
mandate,
platform.get_processor().get_account(),
)
}))
.await?;
Ok(services::ApplicationResponse::Json(mandates_list))
}
impl ForeignFrom<Result<types::PaymentsResponseData, types::ErrorResponse>>
for Option<types::MandateReference>
{
fn foreign_from(resp: Result<types::PaymentsResponseData, types::ErrorResponse>) -> Self {
match resp {
Ok(types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
}) => *mandate_reference,
_ => None,
}
}
}
pub trait MandateBehaviour {
fn get_amount(&self) -> i64;
fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage>;
fn get_mandate_id(&self) -> Option<&payments::MandateIds>;
fn set_mandate_id(&mut self, new_mandate_id: Option<payments::MandateIds>);
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData;
fn get_setup_mandate_details(
&self,
) -> Option<&hyperswitch_domain_models::mandates::MandateData>;
fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance>;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/metrics.rs | crates/router/src/core/metrics.rs | use router_env::{counter_metric, global_meter};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(INCOMING_DISPUTE_WEBHOOK_METRIC, GLOBAL_METER); // No. of incoming dispute webhooks
counter_metric!(
INCOMING_DISPUTE_WEBHOOK_SIGNATURE_FAILURE_METRIC,
GLOBAL_METER
); // No. of incoming dispute webhooks for which signature verification failed
counter_metric!(
INCOMING_DISPUTE_WEBHOOK_VALIDATION_FAILURE_METRIC,
GLOBAL_METER
); // No. of incoming dispute webhooks for which validation failed
counter_metric!(INCOMING_DISPUTE_WEBHOOK_NEW_RECORD_METRIC, GLOBAL_METER); // No. of incoming dispute webhooks for which new record is created in our db
counter_metric!(INCOMING_DISPUTE_WEBHOOK_UPDATE_RECORD_METRIC, GLOBAL_METER); // No. of incoming dispute webhooks for which we have updated the details to existing record
counter_metric!(
INCOMING_DISPUTE_WEBHOOK_MERCHANT_NOTIFIED_METRIC,
GLOBAL_METER
); // No. of incoming dispute webhooks which are notified to merchant
counter_metric!(
ACCEPT_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC,
GLOBAL_METER
); //No. of status validation failures while accepting a dispute
counter_metric!(
EVIDENCE_SUBMISSION_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC,
GLOBAL_METER
); //No. of status validation failures while submitting evidence for a dispute
//No. of status validation failures while attaching evidence for a dispute
counter_metric!(
ATTACH_EVIDENCE_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC,
GLOBAL_METER
);
counter_metric!(THREE_DS_EXEMPTION_INCOMING_REQUESTS, GLOBAL_METER); // No. of incoming requests for Three DS Exemption engine in payments flow
counter_metric!(THREE_DS_EXEMPTION_ALGORITHM_FOUND, GLOBAL_METER); // No. of requests for which Three DS Exemption algorithm is found in business profile
counter_metric!(THREE_DS_EXEMPTION_DECISION_COMPUTED, GLOBAL_METER); // No. of requests for which Three DS Exemption decision is computed
counter_metric!(INCOMING_PAYOUT_WEBHOOK_METRIC, GLOBAL_METER); // No. of incoming payout webhooks
counter_metric!(
INCOMING_PAYOUT_WEBHOOK_SIGNATURE_FAILURE_METRIC,
GLOBAL_METER
); // No. of incoming payout webhooks for which signature verification failed
counter_metric!(WEBHOOK_INCOMING_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_INCOMING_FILTERED_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_SOURCE_VERIFIED_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_OUTGOING_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_OUTGOING_RECEIVED_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT, GLOBAL_METER);
counter_metric!(WEBHOOK_PAYMENT_NOT_FOUND, GLOBAL_METER);
counter_metric!(
WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT,
GLOBAL_METER
);
counter_metric!(WEBHOOK_FLOW_FAILED_BUT_ACKNOWLEDGED, GLOBAL_METER);
counter_metric!(ROUTING_CREATE_REQUEST_RECEIVED, GLOBAL_METER);
counter_metric!(ROUTING_CREATE_SUCCESS_RESPONSE, GLOBAL_METER);
counter_metric!(ROUTING_MERCHANT_DICTIONARY_RETRIEVE, GLOBAL_METER);
counter_metric!(
ROUTING_MERCHANT_DICTIONARY_RETRIEVE_SUCCESS_RESPONSE,
GLOBAL_METER
);
counter_metric!(ROUTING_LINK_CONFIG, GLOBAL_METER);
counter_metric!(ROUTING_LINK_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER);
counter_metric!(ROUTING_RETRIEVE_CONFIG, GLOBAL_METER);
counter_metric!(ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER);
counter_metric!(ROUTING_RETRIEVE_DEFAULT_CONFIG, GLOBAL_METER);
counter_metric!(
ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE,
GLOBAL_METER
);
counter_metric!(ROUTING_RETRIEVE_LINK_CONFIG, GLOBAL_METER);
counter_metric!(ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER);
counter_metric!(ROUTING_UNLINK_CONFIG, GLOBAL_METER);
counter_metric!(ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER);
counter_metric!(ROUTING_UPDATE_CONFIG, GLOBAL_METER);
counter_metric!(ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE, GLOBAL_METER);
counter_metric!(ROUTING_UPDATE_CONFIG_FOR_PROFILE, GLOBAL_METER);
counter_metric!(
ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE,
GLOBAL_METER
);
counter_metric!(ROUTING_RETRIEVE_CONFIG_FOR_PROFILE, GLOBAL_METER);
counter_metric!(
ROUTING_RETRIEVE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE,
GLOBAL_METER
);
counter_metric!(DYNAMIC_SUCCESS_BASED_ROUTING, GLOBAL_METER);
counter_metric!(DYNAMIC_CONTRACT_BASED_ROUTING, GLOBAL_METER);
#[cfg(feature = "partial-auth")]
counter_metric!(PARTIAL_AUTH_FAILURE, GLOBAL_METER);
counter_metric!(API_KEY_REQUEST_INITIATED, GLOBAL_METER);
counter_metric!(API_KEY_REQUEST_COMPLETED, GLOBAL_METER);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/recon.rs | crates/router/src/core/recon.rs | use api_models::recon as recon_api;
#[cfg(feature = "email")]
use common_utils::{ext_traits::AsyncExt, types::user::ThemeLineage};
use error_stack::ResultExt;
#[cfg(feature = "email")]
use masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "email")]
use crate::{
consts, services::email::types as email_types, types::domain, utils::user::theme as theme_utils,
};
use crate::{
core::errors::{self, RouterResponse, UserErrors, UserResponse},
services::{api as service_api, authentication},
types::{
api::{self as api_types, enums},
storage,
transformers::ForeignTryFrom,
},
utils::user as user_utils,
SessionState,
};
#[allow(unused_variables)]
pub async fn send_recon_request(
state: SessionState,
auth_data: authentication::AuthenticationDataWithUser,
) -> RouterResponse<recon_api::ReconStatusResponse> {
#[cfg(not(feature = "email"))]
return Ok(service_api::ApplicationResponse::Json(
recon_api::ReconStatusResponse {
recon_status: enums::ReconStatus::NotRequested,
},
));
#[cfg(feature = "email")]
{
let user_in_db = &auth_data.user;
let merchant_id = auth_data.merchant_account.get_id().clone();
let theme = theme_utils::get_most_specific_theme_using_lineage(
&state.clone(),
ThemeLineage::Merchant {
tenant_id: state.tenant.tenant_id.clone(),
org_id: auth_data.merchant_account.get_org_id().clone(),
merchant_id: merchant_id.clone(),
},
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to fetch theme for merchant_id = {merchant_id:?}",
))?;
let user_email = user_in_db.email.clone();
let email_contents = email_types::ProFeatureRequest {
feature_name: consts::RECON_FEATURE_TAG.to_string(),
merchant_id: merchant_id.clone(),
user_name: domain::UserName::new(user_in_db.name.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to form username")?,
user_email: domain::UserEmail::from_pii_email(user_email.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert recipient's email to UserEmail")?,
recipient_email: domain::UserEmail::from_pii_email(
state.conf.email.recon_recipient_email.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert recipient's email to UserEmail")?,
subject: format!(
"{} {}",
consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST,
user_email.expose().peek()
),
theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
theme_config: theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
};
state
.email_client
.compose_and_send_email(
user_utils::get_base_url(&state),
Box::new(email_contents),
state.conf.proxy.https_url.as_ref(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to compose and send email for ProFeatureRequest [Recon]")
.async_and_then(|_| async {
let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate {
recon_status: enums::ReconStatus::Requested,
};
let db = &*state.store;
let response = db
.update_merchant(
auth_data.merchant_account,
updated_merchant_account,
&auth_data.key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("Failed while updating merchant's recon status: {merchant_id:?}")
})?;
Ok(service_api::ApplicationResponse::Json(
recon_api::ReconStatusResponse {
recon_status: response.recon_status,
},
))
})
.await
}
}
pub async fn generate_recon_token(
state: SessionState,
user_with_role: authentication::UserFromTokenWithRoleInfo,
) -> RouterResponse<recon_api::ReconTokenResponse> {
let user = user_with_role.user;
let token = authentication::ReconToken::new_token(
user.user_id.clone(),
user.merchant_id.clone(),
&state.conf,
user.org_id.clone(),
user.profile_id.clone(),
user.tenant_id,
user_with_role.role_info,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed to create recon token for params [user_id, org_id, mid, pid] [{}, {:?}, {:?}, {:?}]",
user.user_id, user.org_id, user.merchant_id, user.profile_id,
)
})?;
Ok(service_api::ApplicationResponse::Json(
recon_api::ReconTokenResponse {
token: token.into(),
},
))
}
pub async fn recon_merchant_account_update(
state: SessionState,
processor: domain::Processor,
req: recon_api::ReconUpdateMerchantRequest,
) -> RouterResponse<api_types::MerchantAccountResponse> {
let db = &*state.store;
let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate {
recon_status: req.recon_status,
};
let merchant_id = processor.get_account().get_id().clone();
let updated_merchant_account = db
.update_merchant(
processor.get_account().clone(),
updated_merchant_account,
processor.get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("Failed while updating merchant's recon status: {merchant_id:?}")
})?;
#[cfg(feature = "email")]
{
let user_email = &req.user_email.clone();
let theme = theme_utils::get_most_specific_theme_using_lineage(
&state.clone(),
ThemeLineage::Merchant {
tenant_id: state.tenant.tenant_id.clone(),
org_id: processor.get_account().get_org_id().clone(),
merchant_id: merchant_id.clone(),
},
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to fetch theme for merchant_id = {merchant_id:?}",
))?;
let email_contents = email_types::ReconActivation {
recipient_email: domain::UserEmail::from_pii_email(user_email.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to convert recipient's email to UserEmail from pii::Email",
)?,
user_name: domain::UserName::new(Secret::new("HyperSwitch User".to_string()))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to form username")?,
subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST,
theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
theme_config: theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
};
if req.recon_status == enums::ReconStatus::Active {
let _ = state
.email_client
.compose_and_send_email(
user_utils::get_base_url(&state),
Box::new(email_contents),
state.conf.proxy.https_url.as_ref(),
)
.await
.inspect_err(|err| {
router_env::logger::error!(
"Failed to compose and send email notifying them of recon activation: {}",
err
)
})
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to compose and send email for ReconActivation");
}
}
Ok(service_api::ApplicationResponse::Json(
api_types::MerchantAccountResponse::foreign_try_from(updated_merchant_account)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "merchant_account",
})?,
))
}
pub async fn verify_recon_token(
state: SessionState,
user_with_role: authentication::UserFromTokenWithRoleInfo,
) -> UserResponse<recon_api::VerifyTokenResponse> {
let user = user_with_role.user;
let user_in_db = user
.get_user_from_db(&state)
.await
.attach_printable_lazy(|| {
format!(
"Failed to fetch the user from DB for user_id - {}",
user.user_id
)
})?;
let acl = user_with_role.role_info.get_recon_acl();
let optional_acl_str = serde_json::to_string(&acl)
.inspect_err(|err| router_env::logger::error!("Failed to serialize acl to string: {}", err))
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to serialize acl to string. Using empty ACL")
.ok();
Ok(service_api::ApplicationResponse::Json(
recon_api::VerifyTokenResponse {
merchant_id: user.merchant_id.to_owned(),
user_email: user_in_db.0.email,
acl: optional_acl_str,
},
))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/locker_migration.rs | crates/router/src/core/locker_migration.rs | use ::payment_methods::controller::PaymentMethodsController;
use api_models::locker_migration::MigrateCardResponse;
use common_utils::{errors::CustomResult, id_type};
#[cfg(feature = "v1")]
use diesel_models::enums as storage_enums;
#[cfg(feature = "v1")]
use error_stack::FutureExt;
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use futures::TryFutureExt;
#[cfg(feature = "v1")]
use super::{errors::StorageErrorExt, payment_methods::cards};
use crate::{errors, routes::SessionState, services, types::domain};
#[cfg(feature = "v1")]
use crate::{services::logger, types::api};
#[cfg(feature = "v2")]
pub async fn rust_locker_migration(
_state: SessionState,
_merchant_id: &id_type::MerchantId,
) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn rust_locker_migration(
state: SessionState,
merchant_id: &id_type::MerchantId,
) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> {
use crate::db::customers::CustomerListConstraints;
let db = state.store.as_ref();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
// Handle cases where the number of customers is greater than the limit
let constraints = CustomerListConstraints {
limit: u16::MAX,
offset: None,
customer_id: None,
time_range: None,
};
let domain_customers = db
.list_customers_by_merchant_id(merchant_id, &key_store, constraints)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let mut customers_moved = 0;
let mut cards_moved = 0;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
for customer in domain_customers {
let result = db
.find_payment_method_by_customer_id_merchant_id_list(
&key_store,
&customer.customer_id,
merchant_id,
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|pm| {
call_to_locker(&state, pm, &customer.customer_id, merchant_id, &platform)
})
.await?;
customers_moved += 1;
cards_moved += result;
}
Ok(services::api::ApplicationResponse::Json(
MigrateCardResponse {
status_code: "200".to_string(),
status_message: "Card migration completed".to_string(),
customers_moved,
cards_moved,
},
))
}
#[cfg(feature = "v1")]
pub async fn call_to_locker(
state: &SessionState,
payment_methods: Vec<domain::PaymentMethod>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
platform: &domain::Platform,
) -> CustomResult<usize, errors::ApiErrorResponse> {
let mut cards_moved = 0;
for pm in payment_methods.into_iter().filter(|pm| {
matches!(
pm.get_payment_method_type(),
Some(storage_enums::PaymentMethod::Card)
)
}) {
let card = cards::get_card_from_locker(
state,
customer_id,
merchant_id,
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await;
let card = match card {
Ok(card) => card.get_card(),
Err(err) => {
logger::error!("Failed to fetch card from Basilisk HS locker : {:?}", err);
continue;
}
};
let card_details = api::CardDetail {
card_number: card.card_number,
card_exp_month: card.card_exp_month,
card_exp_year: card.card_exp_year,
card_holder_name: card.name_on_card,
nick_name: card.nick_name.map(masking::Secret::new),
card_cvc: None,
card_issuing_country: None,
card_issuing_country_code: None,
card_network: None,
card_issuer: None,
card_type: None,
};
let pm_create = api::PaymentMethodCreate {
payment_method: pm.get_payment_method_type(),
payment_method_type: pm.get_payment_method_subtype(),
payment_method_issuer: pm.payment_method_issuer,
payment_method_issuer_code: pm.payment_method_issuer_code,
card: Some(card_details.clone()),
#[cfg(feature = "payouts")]
wallet: None,
#[cfg(feature = "payouts")]
bank_transfer: None,
metadata: pm.metadata,
customer_id: Some(pm.customer_id),
card_network: card.card_brand,
client_secret: None,
payment_method_data: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
};
let add_card_result = cards::PmCards{
state,
provider: platform.get_provider(),
}.add_card_hs(
pm_create,
&card_details,
customer_id,
Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Card migration failed for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ",
pm.payment_method_id
));
let (_add_card_rs_resp, _is_duplicate) = match add_card_result {
Ok(output) => output,
Err(err) => {
logger::error!("Failed to add card to Rust locker : {:?}", err);
continue;
}
};
cards_moved += 1;
logger::info!(
"Card migrated for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ",
pm.payment_method_id
);
}
Ok(cards_moved)
}
#[cfg(feature = "v2")]
pub async fn call_to_locker(
_state: &SessionState,
_payment_methods: Vec<domain::PaymentMethod>,
_customer_id: &id_type::CustomerId,
_merchant_id: &id_type::MerchantId,
_platform: &domain::Platform,
) -> CustomResult<usize, errors::ApiErrorResponse> {
todo!()
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/cache.rs | crates/router/src/core/cache.rs | use common_utils::errors::CustomResult;
use error_stack::{report, ResultExt};
use storage_impl::redis::cache::{redact_from_redis_and_publish, CacheKind};
use super::errors;
use crate::{routes::SessionState, services};
pub async fn invalidate(
state: SessionState,
key: &str,
) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ApiErrorResponse> {
let store = state.store.as_ref();
let result = redact_from_redis_and_publish(
store.get_cache_store().as_ref(),
[CacheKind::All(key.into())],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
// If the message was published to atleast one channel
// then return status Ok
if result > 0 {
Ok(services::api::ApplicationResponse::StatusOk)
} else {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate cache"))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/configs.rs | crates/router/src/core/configs.rs | use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use external_services::superposition::ConfigContext;
use crate::{
core::errors::{self, utils::StorageErrorExt, RouterResponse},
routes::SessionState,
services::ApplicationResponse,
types::{api, transformers::ForeignInto},
};
pub async fn set_config(state: SessionState, config: api::Config) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
.insert_config(diesel_models::configs::ConfigNew {
key: config.key,
config: config.value,
})
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateConfig)
.attach_printable("Unknown error, while setting config key")?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
pub async fn read_config(state: SessionState, key: &str) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
.find_config_by_key(key)
.await
.to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
pub async fn update_config(
state: SessionState,
config_update: &api::ConfigUpdate,
) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
.update_config_by_key(&config_update.key, config_update.foreign_into())
.await
.to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
pub async fn config_delete(state: SessionState, key: String) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
.delete_config_by_key(&key)
.await
.to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
/// Get a boolean configuration value with superposition and database fallback
pub async fn get_config_bool(
state: &SessionState,
superposition_key: &str,
db_key: &str,
context: Option<ConfigContext>,
default_value: bool,
) -> CustomResult<bool, errors::StorageError> {
// Try superposition first if available
let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
match superposition_client
.get_bool_value(superposition_key, context.as_ref())
.await
{
Ok(value) => Some(value),
Err(err) => {
router_env::logger::warn!(
"Failed to retrieve config from superposition, falling back to database: {:?}",
err
);
None
}
}
} else {
None
};
// Use superposition result or fall back to database
if let Some(value) = superposition_result {
Ok(value)
} else {
let config = state
.store
.find_config_by_key_unwrap_or(db_key, Some(default_value.to_string()))
.await?;
config
.config
.parse::<bool>()
.change_context(errors::StorageError::DeserializationFailed)
}
}
/// Get a string configuration value with superposition and database fallback
pub async fn get_config_string(
state: &SessionState,
superposition_key: &str,
db_key: &str,
context: Option<ConfigContext>,
default_value: String,
) -> CustomResult<String, errors::StorageError> {
// Try superposition first if available
let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
match superposition_client
.get_string_value(superposition_key, context.as_ref())
.await
{
Ok(value) => Some(value),
Err(err) => {
router_env::logger::warn!(
"Failed to retrieve config from superposition, falling back to database: {:?}",
err
);
None
}
}
} else {
None
};
// Use superposition result or fall back to database
if let Some(value) = superposition_result {
Ok(value)
} else {
let config = state
.store
.find_config_by_key_unwrap_or(db_key, Some(default_value))
.await?;
Ok(config.config)
}
}
/// Get an integer configuration value with superposition and database fallback
pub async fn get_config_int(
state: &SessionState,
superposition_key: &str,
db_key: &str,
context: Option<ConfigContext>,
default_value: i64,
) -> CustomResult<i64, errors::StorageError> {
// Try superposition first if available
let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
match superposition_client
.get_int_value(superposition_key, context.as_ref())
.await
{
Ok(value) => Some(value),
Err(err) => {
router_env::logger::warn!(
"Failed to retrieve config from superposition, falling back to database: {:?}",
err
);
None
}
}
} else {
None
};
// Use superposition result or fall back to database
if let Some(value) = superposition_result {
Ok(value)
} else {
let config = state
.store
.find_config_by_key_unwrap_or(db_key, Some(default_value.to_string()))
.await?;
config
.config
.parse::<i64>()
.change_context(errors::StorageError::DeserializationFailed)
}
}
/// Get a float configuration value with superposition and database fallback
pub async fn get_config_float(
state: &SessionState,
superposition_key: &str,
db_key: &str,
context: Option<ConfigContext>,
default_value: f64,
) -> CustomResult<f64, errors::StorageError> {
// Try superposition first if available
let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
match superposition_client
.get_float_value(superposition_key, context.as_ref())
.await
{
Ok(value) => Some(value),
Err(err) => {
router_env::logger::warn!(
"Failed to retrieve config from superposition, falling back to database: {:?}",
err
);
None
}
}
} else {
None
};
// Use superposition result or fall back to database
if let Some(value) = superposition_result {
Ok(value)
} else {
let config = state
.store
.find_config_by_key_unwrap_or(db_key, Some(default_value.to_string()))
.await?;
config
.config
.parse::<f64>()
.change_context(errors::StorageError::DeserializationFailed)
}
}
/// Get an object configuration value with superposition and database fallback
pub async fn get_config_object<T>(
state: &SessionState,
superposition_key: &str,
db_key: &str,
context: Option<ConfigContext>,
default_value: T,
) -> CustomResult<T, errors::StorageError>
where
T: serde::de::DeserializeOwned + serde::Serialize,
{
// Try superposition first if available
let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
match superposition_client
.get_object_value(superposition_key, context.as_ref())
.await
{
Ok(json_value) => Some(
serde_json::from_value::<T>(json_value)
.change_context(errors::StorageError::DeserializationFailed),
),
Err(err) => {
router_env::logger::warn!(
"Failed to retrieve config from superposition, falling back to database: {:?}",
err
);
None
}
}
} else {
None
};
// Use superposition result or fall back to database
if let Some(superposition_result) = superposition_result {
superposition_result
} else {
let config = state
.store
.find_config_by_key_unwrap_or(
db_key,
Some(
serde_json::to_string(&default_value)
.change_context(errors::StorageError::SerializationFailed)?,
),
)
.await?;
serde_json::from_str::<T>(&config.config)
.change_context(errors::StorageError::DeserializationFailed)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/proxy.rs | crates/router/src/core/proxy.rs | use super::errors::{self, RouterResponse, RouterResult};
use crate::{logger, routes::SessionState, services, types::domain};
pub mod utils;
use api_models::proxy as proxy_api_models;
use common_utils::{
ext_traits::BytesExt,
request::{self, RequestBuilder},
};
use error_stack::ResultExt;
use hyperswitch_interfaces::types::Response;
use serde_json::Value;
pub async fn proxy_core(
state: SessionState,
platform: domain::Platform,
req: proxy_api_models::ProxyRequest,
) -> RouterResponse<proxy_api_models::ProxyResponse> {
let req_wrapper = utils::ProxyRequestWrapper(req.clone());
let proxy_record = req_wrapper
.get_proxy_record(
&state,
platform.get_provider().get_key_store(),
platform.get_provider().get_account().storage_scheme,
)
.await?;
let vault_data = proxy_record.get_vault_data(&state, platform).await?;
let processed_body =
interpolate_token_references_with_vault_data(req.request_body.clone(), &vault_data)?;
let res = execute_proxy_request(&state, &req_wrapper, processed_body).await?;
let proxy_response = proxy_api_models::ProxyResponse::try_from(ProxyResponseWrapper(res))?;
Ok(services::ApplicationResponse::Json(proxy_response))
}
fn interpolate_token_references_with_vault_data(
value: Value,
vault_data: &Value,
) -> RouterResult<Value> {
match value {
Value::Object(obj) => {
let new_obj = obj
.into_iter()
.map(|(key, val)| interpolate_token_references_with_vault_data(val, vault_data).map(|processed| (key, processed)))
.collect::<Result<serde_json::Map<_, _>, error_stack::Report<errors::ApiErrorResponse>>>()?;
Ok(Value::Object(new_obj))
}
Value::String(s) => utils::parse_token(&s)
.map(|(_, token_ref)| extract_field_from_vault_data(vault_data, &token_ref.field))
.unwrap_or(Ok(Value::String(s.clone()))),
_ => Ok(value),
}
}
fn find_field_recursively_in_vault_data(
obj: &serde_json::Map<String, Value>,
field_name: &str,
) -> Option<Value> {
obj.get(field_name).cloned().or_else(|| {
obj.values()
.filter_map(|val| {
if let Value::Object(inner_obj) = val {
find_field_recursively_in_vault_data(inner_obj, field_name)
} else {
None
}
})
.next()
})
}
fn extract_field_from_vault_data(vault_data: &Value, field_name: &str) -> RouterResult<Value> {
match vault_data {
Value::Object(obj) => find_field_recursively_in_vault_data(obj, field_name)
.ok_or_else(|| errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("Field '{field_name}' not found")),
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Vault data is not a valid JSON object"),
}
}
async fn execute_proxy_request(
state: &SessionState,
req_wrapper: &utils::ProxyRequestWrapper,
processed_body: Value,
) -> RouterResult<Response> {
let request = RequestBuilder::new()
.method(req_wrapper.get_method())
.attach_default_headers()
.headers(req_wrapper.get_headers())
.url(req_wrapper.get_destination_url())
.set_body(request::RequestContent::Json(Box::new(processed_body)))
.build();
let response = services::call_connector_api(state, request, "proxy")
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to call the destination");
response
.map(|inner| match inner {
Err(err_res) => {
logger::error!("Error while receiving response: {err_res:?}");
err_res
}
Ok(res) => res,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while receiving response")
}
struct ProxyResponseWrapper(Response);
impl TryFrom<ProxyResponseWrapper> for proxy_api_models::ProxyResponse {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(wrapper: ProxyResponseWrapper) -> Result<Self, Self::Error> {
let res = wrapper.0;
let response_body: Value = res
.response
.parse_struct("ProxyResponse")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse the response")?;
let status_code = res.status_code;
let response_headers = proxy_api_models::Headers::from_header_map(res.headers.as_ref());
Ok(Self {
response: response_body,
status_code,
response_headers,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments.rs | crates/router/src/core/payments.rs | pub mod access_token;
pub mod conditional_configs;
pub mod customers;
pub mod flows;
pub mod gateway;
pub mod helpers;
pub mod operations;
pub mod session_token;
#[cfg(feature = "retry")]
pub mod retry;
pub mod routing;
#[cfg(feature = "v2")]
pub mod session_operation;
pub mod tokenization;
pub mod transformers;
pub mod types;
#[cfg(feature = "v2")]
pub mod vault_session;
#[cfg(feature = "olap")]
use std::collections::HashMap;
use std::{
collections::HashSet, fmt::Debug, marker::PhantomData, ops::Deref, str::FromStr, time::Instant,
vec::IntoIter,
};
use external_services::grpc_client;
#[cfg(feature = "v2")]
pub mod payment_methods;
#[cfg(feature = "v2")]
use std::future;
#[cfg(feature = "olap")]
use api_models::admin::MerchantConnectorInfo;
#[cfg(feature = "v2")]
use api_models::payments::RevenueRecoveryGetIntentResponse;
use api_models::{
self, enums,
mandates::RecurringDetails,
payments::{self as payments_api},
};
pub use common_enums::enums::{CallConnectorAction, ExecutionMode, ExecutionPath, GatewaySystem};
use common_types::payments as common_payments_types;
use common_utils::{
ext_traits::{AsyncExt, StringExt},
id_type, pii,
types::{AmountConvertor, MinorUnit, Surcharge},
};
use diesel_models::{fraud_check::FraudCheck, refund as diesel_refund};
use error_stack::{report, ResultExt};
use events::EventInfo;
use futures::future::join_all;
use helpers::{decrypt_paze_token, ApplePayData};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::{
PaymentAttemptListData, PaymentCancelData, PaymentCaptureData, PaymentConfirmData,
PaymentIntentData, PaymentStatusData,
};
pub use hyperswitch_domain_models::{
mandates::MandateData,
payment_address::PaymentAddress,
payments::{self as domain_payments, HeaderPayload},
router_data::{PaymentMethodToken, RouterData},
router_request_types::CustomerDetails,
};
use hyperswitch_domain_models::{
payment_method_data::RecurringDetails as domain_recurring_details,
payments::{self, payment_intent::CustomerData, ClickToPayMetaData},
router_data::AccessToken,
};
use masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "v2")]
use operations::ValidateStatusForOperation;
use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
use router_types::transformers::ForeignFrom;
use rustc_hash::FxHashMap;
use scheduler::utils as pt_utils;
#[cfg(feature = "v2")]
pub use session_operation::payments_session_core;
#[cfg(feature = "olap")]
use strum::IntoEnumIterator;
#[cfg(feature = "v1")]
pub use self::operations::{
PaymentApprove, PaymentCancel, PaymentCancelPostCapture, PaymentCapture, PaymentConfirm,
PaymentCreate, PaymentExtendAuthorization, PaymentIncrementalAuthorization,
PaymentPostSessionTokens, PaymentReject, PaymentSession, PaymentSessionUpdate, PaymentStatus,
PaymentUpdate, PaymentUpdateMetadata,
};
use self::{
conditional_configs::perform_decision_management,
flows::{ConstructFlowSpecificData, Feature},
gateway::context as gateway_context,
operations::{BoxedOperation, Operation, PaymentResponse},
routing::{self as self_routing, SessionFlowRoutingInput},
};
use super::{
errors::StorageErrorExt,
payment_methods::surcharge_decision_configs,
routing::TransactionData,
unified_connector_service::{
extract_gateway_system_from_payment_intent, should_call_unified_connector_service,
},
};
#[cfg(feature = "v1")]
use crate::core::blocklist::utils as blocklist_utils;
#[cfg(feature = "v1")]
use crate::core::card_testing_guard::utils as card_testing_guard_utils;
#[cfg(feature = "v1")]
use crate::core::debit_routing;
#[cfg(feature = "frm")]
use crate::core::fraud_check as frm_core;
#[cfg(feature = "v2")]
use crate::core::payment_methods::vault;
#[cfg(feature = "v2")]
use crate::core::revenue_recovery::get_workflow_entries;
#[cfg(feature = "v2")]
use crate::core::revenue_recovery::map_to_recovery_payment_item;
#[cfg(feature = "v1")]
use crate::core::routing::helpers as routing_helpers;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use crate::types::api::convert_connector_data_to_routable_connectors;
use crate::{
configs::settings::{
ApplePayPreDecryptFlow, GooglePayPreDecryptFlow, PaymentFlow, PaymentMethodTypeTokenFilter,
},
consts,
core::{
errors::{self, CustomResult, RouterResponse, RouterResult},
payment_methods::{cards, network_tokenization},
payouts,
routing::{self as core_routing},
unified_authentication_service::types::{ClickToPay, UnifiedAuthenticationService},
utils as core_utils,
},
db::StorageInterface,
logger,
routes::{app::ReqState, metrics, payment_methods::ParentPaymentMethodToken, SessionState},
services::{self, api::Authenticate, ConnectorRedirectResponse},
types::{
self as router_types,
api::{self, ConnectorCallType, ConnectorCommon},
domain,
storage::{self, enums as storage_enums, payment_attempt::PaymentAttemptExt},
transformers::ForeignTryInto,
},
utils::{
self, add_apple_pay_flow_metrics, add_connector_http_status_code_metrics, Encode,
OptionExt, ValueExt,
},
workflows::payment_sync,
};
#[cfg(feature = "v1")]
use crate::{
core::{
authentication as authentication_core,
unified_connector_service::update_gateway_system_in_feature_metadata,
},
types::{api::authentication, BrowserInformation},
};
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn payments_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
platform: domain::Platform,
profile: &domain::Profile,
operation: Op,
req: Req,
get_tracker_response: operations::GetTrackerResponse<D>,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
) -> RouterResult<(
D,
Req,
Option<domain::Customer>,
Option<u16>,
Option<u128>,
common_types::domain::ConnectorResponseData,
)>
where
F: Send + Clone + Sync,
Req: Send + Sync + Authenticate,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
FData: Send + Sync + Clone,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
// Get the trackers related to track the state of the payment
let operations::GetTrackerResponse { mut payment_data } = get_tracker_response;
operation
.to_domain()?
.create_or_fetch_payment_method(state, &platform, profile, &mut payment_data)
.await?;
let (_operation, customer) = operation
.to_domain()?
.get_customer_details(
state,
&mut payment_data,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
operation
.to_domain()?
.run_decision_manager(state, &mut payment_data, profile)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to run decision manager")?;
let connector = operation
.to_domain()?
.perform_routing(&platform, profile, state, &mut payment_data)
.await?;
let mut connector_http_status_code = None;
let (payment_data, connector_response_data) = match connector {
ConnectorCallType::PreDetermined(connector_data) => {
let (mca_type_details, updated_customer, router_data, tokenization_action) =
call_connector_service_prerequisites(
state,
req_state.clone(),
&platform,
connector_data.connector_data.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
None,
header_payload.clone(),
None,
profile,
false,
false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType
req.should_return_raw_response(),
)
.await?;
let router_data = decide_unified_connector_service_call(
state,
req_state.clone(),
&platform,
connector_data.connector_data.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
None, // schedule_time is not used in PreDetermined ConnectorCallType
header_payload.clone(),
#[cfg(feature = "frm")]
None,
profile,
false,
false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType
req.should_return_raw_response(),
mca_type_details,
router_data,
updated_customer,
tokenization_action,
)
.await?;
let connector_response_data = common_types::domain::ConnectorResponseData {
raw_connector_response: router_data.raw_connector_response.clone(),
};
let payments_response_operation = Box::new(PaymentResponse);
connector_http_status_code = router_data.connector_http_status_code;
add_connector_http_status_code_metrics(connector_http_status_code);
payments_response_operation
.to_post_update_tracker()?
.save_pm_and_mandate(state, &router_data, &platform, &mut payment_data, profile)
.await?;
let payment_data = payments_response_operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await?;
(payment_data, connector_response_data)
}
ConnectorCallType::Retryable(connectors) => {
let mut connectors = connectors.clone().into_iter();
let connector_data = get_connector_data(&mut connectors)?;
let (mca_type_details, updated_customer, router_data, tokenization_action) =
call_connector_service_prerequisites(
state,
req_state.clone(),
&platform,
connector_data.connector_data.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
None,
header_payload.clone(),
None,
profile,
false,
false, //should_retry_with_pan is set to false in case of Retryable ConnectorCallType
req.should_return_raw_response(),
)
.await?;
let router_data = decide_unified_connector_service_call(
state,
req_state.clone(),
&platform,
connector_data.connector_data.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
None, // schedule_time is not used in Retryable ConnectorCallType
header_payload.clone(),
#[cfg(feature = "frm")]
None,
profile,
true,
false, //should_retry_with_pan is set to false in case of PreDetermined ConnectorCallType
req.should_return_raw_response(),
mca_type_details,
router_data,
updated_customer,
tokenization_action,
)
.await?;
let connector_response_data = common_types::domain::ConnectorResponseData {
raw_connector_response: router_data.raw_connector_response.clone(),
};
let payments_response_operation = Box::new(PaymentResponse);
connector_http_status_code = router_data.connector_http_status_code;
add_connector_http_status_code_metrics(connector_http_status_code);
payments_response_operation
.to_post_update_tracker()?
.save_pm_and_mandate(state, &router_data, &platform, &mut payment_data, profile)
.await?;
let payment_data = payments_response_operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await?;
(payment_data, connector_response_data)
}
ConnectorCallType::SessionMultiple(vec) => todo!(),
ConnectorCallType::Skip => (
payment_data,
common_types::domain::ConnectorResponseData {
raw_connector_response: None,
},
),
};
let payment_intent_status = payment_data.get_payment_intent().status;
// Delete the tokens after payment
payment_data
.get_payment_attempt()
.payment_token
.as_ref()
.zip(Some(payment_data.get_payment_attempt().payment_method_type))
.map(ParentPaymentMethodToken::return_key_for_token)
.async_map(|key_for_token| async move {
let _ = vault::delete_payment_token(state, &key_for_token, payment_intent_status)
.await
.inspect_err(|err| logger::error!("Failed to delete payment_token: {:?}", err));
})
.await;
Ok((
payment_data,
req,
customer,
connector_http_status_code,
None,
connector_response_data,
))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn internal_payments_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
platform: domain::Platform,
profile: &domain::Profile,
operation: Op,
req: Req,
get_tracker_response: operations::GetTrackerResponse<D>,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
) -> RouterResult<(
D,
Req,
Option<u16>,
Option<u128>,
common_types::domain::ConnectorResponseData,
)>
where
F: Send + Clone + Sync,
Req: Send + Sync + Authenticate,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
FData: Send + Sync + Clone + serde::Serialize,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
// Get the trackers related to track the state of the payment
let operations::GetTrackerResponse { mut payment_data } = get_tracker_response;
let connector_data = operation
.to_domain()?
.get_connector_from_request(state, &req, &mut payment_data)
.await?;
let merchant_connector_account = payment_data
.get_merchant_connector_details()
.map(domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails)
.ok_or_else(|| {
error_stack::report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector details not found in payment data")
})?;
operation
.to_domain()?
.populate_payment_data(
state,
&mut payment_data,
&platform,
profile,
&connector_data,
)
.await?;
let router_data = connector_service_decider(
state,
req_state.clone(),
&platform,
connector_data.clone(),
&operation,
&mut payment_data,
call_connector_action.clone(),
header_payload.clone(),
profile,
req.should_return_raw_response(),
merchant_connector_account,
)
.await?;
let connector_response_data = common_types::domain::ConnectorResponseData {
raw_connector_response: router_data.raw_connector_response.clone(),
};
let payments_response_operation = Box::new(PaymentResponse);
let connector_http_status_code = router_data.connector_http_status_code;
add_connector_http_status_code_metrics(connector_http_status_code);
let payment_data = payments_response_operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await?;
Ok((
payment_data,
req,
connector_http_status_code,
None,
connector_response_data,
))
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn payments_operation_core<'a, F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
platform: &domain::Platform,
profile_id_from_auth_layer: Option<id_type::ProfileId>,
operation: Op,
req: Req,
call_connector_action: CallConnectorAction,
shadow_ucs_call_connector_action: Option<CallConnectorAction>,
auth_flow: services::AuthFlow,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
header_payload: HeaderPayload,
) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync + Debug + 'static,
Req: Authenticate + Clone,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
FData: Send + Sync + Clone + router_types::Capturable + 'static + serde::Serialize,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
tracing::Span::current().record(
"merchant_id",
platform
.get_processor()
.get_account()
.get_id()
.get_string_repr(),
);
let (operation, validate_result) = operation
.to_validate_request()?
.validate_request(&req, platform.get_processor())?;
tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
// get profile from headers
let operations::GetTrackerResponse {
operation,
customer_details,
mut payment_data,
business_profile,
mandate_type,
} = operation
.to_get_tracker()?
.get_trackers(
state,
&validate_result.payment_id,
&req,
platform,
auth_flow,
&header_payload,
)
.await?;
operation
.to_get_tracker()?
.validate_request_with_state(state, &req, &mut payment_data, &business_profile)
.await?;
core_utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&payment_data.get_payment_intent().clone(),
)?;
operation
.to_domain()?
.populate_raw_customer_details(
state,
&mut payment_data,
customer_details.as_ref(),
platform.get_processor(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while populating raw customer details")?;
let (operation, customer) = operation
.to_domain()?
// get_customer_details
.get_or_create_customer_details(
state,
&mut payment_data,
customer_details,
platform.get_provider(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
let authentication_type =
call_decision_manager(state, platform, &business_profile, &payment_data).await?;
payment_data.set_authentication_type_in_attempt(authentication_type);
operation
.to_domain()?
.apply_three_ds_authentication_strategy(state, &mut payment_data, &business_profile)
.await;
let connector = get_connector_choice(
&operation,
state,
&req,
platform,
&business_profile,
&mut payment_data,
eligible_connectors,
mandate_type,
)
.await?;
let payment_method_token = get_decrypted_wallet_payment_method_token(
&operation,
state,
platform,
&mut payment_data,
connector.as_ref(),
)
.await?;
payment_method_token.map(|token| payment_data.set_payment_method_token(Some(token)));
let (connector, debit_routing_output) = debit_routing::perform_debit_routing(
&operation,
state,
&business_profile,
&mut payment_data,
connector,
)
.await;
let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data);
let locale = header_payload.locale.clone();
payment_data = tokenize_in_router_when_confirm_false_or_external_authentication(
state,
&operation,
&mut payment_data,
&validate_result,
platform.get_processor().get_key_store(),
&customer,
&business_profile,
)
.await?;
let mut connector_http_status_code = None;
let mut external_latency = None;
if let Some(connector_details) = connector {
// Fetch and check FRM configs
#[cfg(feature = "frm")]
let mut frm_info = None;
#[allow(unused_variables, unused_mut)]
let mut should_continue_transaction: bool = true;
#[cfg(feature = "frm")]
let mut should_continue_capture: bool = true;
#[cfg(feature = "frm")]
let frm_configs = if state.conf.frm.enabled {
Box::pin(frm_core::call_frm_before_connector_call(
&operation,
platform,
&mut payment_data,
state,
&mut frm_info,
&customer,
&mut should_continue_transaction,
&mut should_continue_capture,
))
.await?
} else {
None
};
#[cfg(feature = "frm")]
logger::debug!(
"frm_configs: {:?}\nshould_continue_transaction: {:?}\nshould_continue_capture: {:?}",
frm_configs,
should_continue_transaction,
should_continue_capture,
);
let is_eligible_for_uas = helpers::is_merchant_eligible_authentication_service(
platform.get_processor().get_account().get_id(),
state,
)
.await?;
if <Req as Authenticate>::is_external_three_ds_data_passed_by_merchant(&req) {
let maybe_connector_enum = match &connector_details {
ConnectorCallType::PreDetermined(connector_data) => {
Some(connector_data.connector_data.connector_name)
}
ConnectorCallType::Retryable(connector_list) => connector_list
.first()
.map(|c| c.connector_data.connector_name),
ConnectorCallType::SessionMultiple(_) => None,
};
if let Some(connector_enum) = maybe_connector_enum {
if connector_enum.is_separate_authentication_supported() {
logger::info!(
"Proceeding with external authentication data provided by the merchant for connector: {:?}",
connector_enum
);
}
}
} else if is_eligible_for_uas {
operation
.to_domain()?
.call_unified_authentication_service_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
platform.get_processor().get_key_store(),
mandate_type,
)
.await?;
} else {
logger::info!(
"skipping authentication service call since the merchant is not eligible."
);
operation
.to_domain()?
.call_external_three_ds_authentication_if_eligible(
state,
&mut payment_data,
&mut should_continue_transaction,
&connector_details,
&business_profile,
platform.get_processor().get_key_store(),
mandate_type,
)
.await?;
};
operation
.to_domain()?
.payments_dynamic_tax_calculation(
state,
&mut payment_data,
&connector_details,
&business_profile,
platform,
)
.await?;
if should_continue_transaction {
#[cfg(feature = "frm")]
match (
should_continue_capture,
payment_data.get_payment_attempt().capture_method,
) {
(
false,
Some(storage_enums::CaptureMethod::Automatic)
| Some(storage_enums::CaptureMethod::SequentialAutomatic),
)
| (false, Some(storage_enums::CaptureMethod::Scheduled)) => {
if let Some(info) = &mut frm_info {
if let Some(frm_data) = &mut info.frm_data {
frm_data.fraud_check.payment_capture_method =
payment_data.get_payment_attempt().capture_method;
}
}
payment_data
.set_capture_method_in_attempt(storage_enums::CaptureMethod::Manual);
logger::debug!("payment_id : {:?} capture method has been changed to manual, since it has configured Post FRM flow",payment_data.get_payment_attempt().payment_id);
}
_ => (),
};
payment_data = match connector_details {
ConnectorCallType::PreDetermined(ref connector) => {
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
let routable_connectors = convert_connector_data_to_routable_connectors(
std::slice::from_ref(connector),
)
.map_err(|e| logger::error!(routable_connector_error=?e))
.unwrap_or_default();
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector.connector_data.connector.id(),
platform.get_processor().get_account().get_id(),
0,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting process schedule time")?
} else {
None
};
let (merchant_connector_account, router_data, tokenization_action) =
call_connector_service_prerequisites(
state,
platform,
connector.connector_data.clone(),
&operation,
&mut payment_data,
&customer,
&validate_result,
&business_profile,
false,
None,
)
.await?;
let (router_data, mca) = decide_unified_connector_service_call(
state,
req_state.clone(),
platform,
connector.connector_data.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
shadow_ucs_call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload.clone(),
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
false,
<Req as Authenticate>::should_return_raw_response(&req),
merchant_connector_account,
router_data,
tokenization_action,
)
.await?;
let op_ref = &operation;
let should_trigger_post_processing_flows = is_operation_confirm(&operation);
let operation = Box::new(PaymentResponse);
connector_http_status_code = router_data.connector_http_status_code;
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
operation
.to_post_update_tracker()?
.save_pm_and_mandate(
state,
&router_data,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/external_service_auth.rs | crates/router/src/core/external_service_auth.rs | use api_models::external_service_auth as external_service_auth_api;
use common_utils::fp_utils;
use error_stack::ResultExt;
use masking::ExposeInterface;
use crate::{
core::errors::{self, RouterResponse},
services::{
api as service_api,
authentication::{self, ExternalServiceType, ExternalToken},
},
SessionState,
};
pub async fn generate_external_token(
state: SessionState,
user: authentication::UserFromToken,
external_service_type: ExternalServiceType,
) -> RouterResponse<external_service_auth_api::ExternalTokenResponse> {
let token = ExternalToken::new_token(
user.user_id.clone(),
user.merchant_id.clone(),
&state.conf,
external_service_type.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed to create external token for params [user_id, mid, external_service_type] [{}, {:?}, {:?}]",
user.user_id, user.merchant_id, external_service_type,
)
})?;
Ok(service_api::ApplicationResponse::Json(
external_service_auth_api::ExternalTokenResponse {
token: token.into(),
},
))
}
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)
}
pub async fn verify_external_token(
state: SessionState,
json_payload: external_service_auth_api::ExternalVerifyTokenRequest,
external_service_type: ExternalServiceType,
) -> RouterResponse<external_service_auth_api::ExternalVerifyTokenResponse> {
let token_from_payload = json_payload.token.expose();
let token = authentication::decode_jwt::<ExternalToken>(&token_from_payload, &state)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
fp_utils::when(
authentication::blacklist::check_user_in_blacklist(&state, &token.user_id, token.exp)
.await?,
|| Err(errors::ApiErrorResponse::InvalidJwtToken),
)?;
token.check_service_type(&external_service_type)?;
let user_in_db = state
.global_store
.find_user_by_id(&token.user_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("User not found in database")?;
let email = user_in_db.email.clone();
let name = user_in_db.name;
Ok(service_api::ApplicationResponse::Json(
external_service_auth_api::ExternalVerifyTokenResponse::Hypersense {
user_id: user_in_db.user_id,
merchant_id: token.merchant_id,
name,
email,
},
))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/api_locking.rs | crates/router/src/core/api_locking.rs | use std::fmt::Debug;
use actix_web::rt::time as actix_time;
use error_stack::{report, ResultExt};
use redis_interface::{self as redis, RedisKey};
use router_env::{instrument, logger, tracing};
use super::errors::{self, RouterResult};
use crate::routes::{app::SessionStateInfo, lock_utils};
pub const API_LOCK_PREFIX: &str = "API_LOCK";
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LockStatus {
// status when the lock is acquired by the caller
Acquired, // [#2129] pick up request_id from AppState and populate here
// status when the lock is acquired by some other caller
Busy,
}
#[derive(Clone, Debug)]
pub enum LockAction {
// Sleep until the lock is acquired
Hold { input: LockingInput },
// Sleep until all locks are acquired
HoldMultiple { inputs: Vec<LockingInput> },
// Queue it but return response as 2xx, could be used for webhooks
QueueWithOk,
// Return Error
Drop,
// Locking Not applicable
NotApplicable,
}
#[derive(Clone, Debug)]
pub struct LockingInput {
pub unique_locking_key: String,
pub api_identifier: lock_utils::ApiIdentifier,
pub override_lock_retries: Option<u32>,
}
impl LockingInput {
fn get_redis_locking_key(&self, merchant_id: &common_utils::id_type::MerchantId) -> String {
format!(
"{}_{}_{}_{}",
API_LOCK_PREFIX,
merchant_id.get_string_repr(),
self.api_identifier,
self.unique_locking_key
)
}
}
impl LockAction {
#[instrument(skip_all)]
pub async fn perform_locking_action<A>(
self,
state: &A,
merchant_id: common_utils::id_type::MerchantId,
) -> RouterResult<()>
where
A: SessionStateInfo,
{
match self {
Self::HoldMultiple { inputs } => {
let lock_retries = inputs
.iter()
.find_map(|input| input.override_lock_retries)
.unwrap_or(state.conf().lock_settings.lock_retries);
let request_id = state.get_request_id();
let redis_lock_expiry_seconds =
state.conf().lock_settings.redis_lock_expiry_seconds;
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_key_values = inputs
.iter()
.map(|input| input.get_redis_locking_key(&merchant_id))
.map(|key| (RedisKey::from(key.as_str()), request_id.clone()))
.collect::<Vec<_>>();
let delay_between_retries_in_milliseconds = state
.conf()
.lock_settings
.delay_between_retries_in_milliseconds;
for _retry in 0..lock_retries {
let results: Vec<redis::SetGetReply<_>> = redis_conn
.set_multiple_keys_if_not_exists_and_get_values(
&redis_key_values,
Some(i64::from(redis_lock_expiry_seconds)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let lock_acquired = results.iter().all(|res| {
// each redis value must match the request_id
// if even 1 does match, the lock is not acquired
*res.get_value() == request_id
});
if lock_acquired {
logger::info!("Lock acquired for locking inputs {:?}", inputs);
return Ok(());
} else {
actix_time::sleep(tokio::time::Duration::from_millis(u64::from(
delay_between_retries_in_milliseconds,
)))
.await;
}
}
Err(report!(errors::ApiErrorResponse::ResourceBusy))
}
Self::Hold { input } => {
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_locking_key = input.get_redis_locking_key(&merchant_id);
let delay_between_retries_in_milliseconds = state
.conf()
.lock_settings
.delay_between_retries_in_milliseconds;
let redis_lock_expiry_seconds =
state.conf().lock_settings.redis_lock_expiry_seconds;
let lock_retries = input
.override_lock_retries
.unwrap_or(state.conf().lock_settings.lock_retries);
for _retry in 0..lock_retries {
let redis_lock_result = redis_conn
.set_key_if_not_exists_with_expiry(
&redis_locking_key.as_str().into(),
state.get_request_id(),
Some(i64::from(redis_lock_expiry_seconds)),
)
.await;
match redis_lock_result {
Ok(redis::SetnxReply::KeySet) => {
logger::info!("Lock acquired for locking input {:?}", input);
tracing::Span::current()
.record("redis_lock_acquired", redis_locking_key);
return Ok(());
}
Ok(redis::SetnxReply::KeyNotSet) => {
logger::info!(
"Lock busy by other request when tried for locking input {:?}",
input
);
actix_time::sleep(tokio::time::Duration::from_millis(u64::from(
delay_between_retries_in_milliseconds,
)))
.await;
}
Err(err) => {
return Err(err)
.change_context(errors::ApiErrorResponse::InternalServerError)
}
}
}
Err(report!(errors::ApiErrorResponse::ResourceBusy))
}
Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()),
}
}
#[instrument(skip_all)]
pub async fn free_lock_action<A>(
self,
state: &A,
merchant_id: common_utils::id_type::MerchantId,
) -> RouterResult<()>
where
A: SessionStateInfo,
{
match self {
Self::HoldMultiple { inputs } => {
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_locking_keys = inputs
.iter()
.map(|input| RedisKey::from(input.get_redis_locking_key(&merchant_id).as_str()))
.collect::<Vec<_>>();
let request_id = state.get_request_id();
let values = redis_conn
.get_multiple_keys::<String>(&redis_locking_keys)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let invalid_request_id_list = values
.iter()
.filter(|redis_value| **redis_value != request_id)
.flatten()
.collect::<Vec<_>>();
if !invalid_request_id_list.is_empty() {
logger::error!(
"The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock.
Current request_id: {:?},
Redis request_ids : {:?}",
request_id,
invalid_request_id_list
);
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock")
} else {
Ok(())
}?;
let delete_result = redis_conn
.delete_multiple_keys(&redis_locking_keys)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let is_key_not_deleted = delete_result
.into_iter()
.any(|delete_reply| delete_reply.is_key_not_deleted());
if is_key_not_deleted {
Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Status release lock called but key is not found in redis",
)
} else {
logger::info!("Lock freed for locking inputs {:?}", inputs);
Ok(())
}
}
Self::Hold { input } => {
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let redis_locking_key = input.get_redis_locking_key(&merchant_id);
match redis_conn
.get_key::<Option<String>>(&redis_locking_key.as_str().into())
.await
{
Ok(val) => {
if val == state.get_request_id() {
match redis_conn
.delete_key(&redis_locking_key.as_str().into())
.await
{
Ok(redis::types::DelReply::KeyDeleted) => {
logger::info!("Lock freed for locking input {:?}", input);
tracing::Span::current()
.record("redis_lock_released", redis_locking_key);
Ok(())
}
Ok(redis::types::DelReply::KeyNotDeleted) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Status release lock called but key is not found in redis",
)
}
Err(error) => Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError),
}
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The request_id which acquired the lock is not equal to the request_id requesting for releasing the lock")
}
}
Err(error) => {
Err(error).change_context(errors::ApiErrorResponse::InternalServerError)
}
}
}
Self::QueueWithOk | Self::Drop | Self::NotApplicable => Ok(()),
}
}
}
pub trait GetLockingInput {
fn get_locking_input<F>(&self, flow: F) -> LockAction
where
F: router_env::types::FlowMetric,
lock_utils::ApiIdentifier: From<F>;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/tokenization.rs | crates/router/src/core/tokenization.rs | #[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use common_enums::enums;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use common_utils::{
crypto::{DecodeMessage, EncodeMessage, GcmAes256},
errors::CustomResult,
ext_traits::{BytesExt, Encode, StringExt},
fp_utils::when,
id_type,
};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use error_stack::ResultExt;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use router_env::{instrument, logger, tracing, Flow};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use serde::Serialize;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use crate::{
core::{
errors::{self, RouterResponse, RouterResult},
payment_methods::vault as pm_vault,
},
db::errors::StorageErrorExt,
routes::{app::StorageInterface, AppState, SessionState},
services::{self, api as api_service, authentication as auth},
types::{api, domain, payment_methods as pm_types},
};
#[instrument(skip_all)]
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub async fn create_vault_token_core(
state: SessionState,
provider: domain::Provider,
req: api_models::tokenization::GenericTokenizationRequest,
) -> RouterResponse<api_models::tokenization::GenericTokenizationResponse> {
// Generate a unique vault ID
let vault_id = domain::VaultId::generate(uuid::Uuid::now_v7().to_string());
let db = state.store.as_ref();
let customer_id = req.customer_id.clone();
// Create vault request
let payload = pm_types::AddVaultRequest {
entity_id: req.customer_id.to_owned(),
vault_id: vault_id.clone(),
data: req.token_request.clone(),
ttl: state.conf.locker.ttl_for_storage_in_secs,
}
.encode_to_vec()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode Request")?;
// Call the vault service
let resp = pm_vault::call_to_vault::<pm_types::AddVault>(&state, payload.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Call to vault failed")?;
// Parse the response
let stored_resp: pm_types::AddVaultResponse = resp
.parse_struct("AddVaultResponse")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse data into AddVaultResponse")?;
// Create new tokenization record
let tokenization_new = hyperswitch_domain_models::tokenization::Tokenization {
id: id_type::GlobalTokenId::generate(&state.conf.cell_information.id),
merchant_id: provider.get_account().get_id().clone(),
customer_id: customer_id.clone(),
locker_id: stored_resp.vault_id.get_string_repr().to_string(),
created_at: common_utils::date_time::now(),
updated_at: common_utils::date_time::now(),
flag: enums::TokenizationFlag::Enabled,
version: enums::ApiVersion::V2,
};
// Insert into database
let tokenization = db
.insert_tokenization(tokenization_new, provider.get_key_store())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert tokenization record")?;
// Convert to TokenizationResponse
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
api_models::tokenization::GenericTokenizationResponse {
id: tokenization.id,
created_at: tokenization.created_at,
flag: tokenization.flag,
},
))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_tokenized_data_core(
state: SessionState,
platform: domain::Platform,
token_id: &id_type::GlobalTokenId,
payload: api_models::tokenization::DeleteTokenDataRequest,
) -> RouterResponse<api_models::tokenization::DeleteTokenDataResponse> {
let db = &*state.store;
// Retrieve the tokenization record
let tokenization_record = db
.get_entity_id_vault_id_by_token_id(token_id, platform.get_processor().get_key_store())
.await
.to_not_found_response(errors::ApiErrorResponse::TokenizationRecordNotFound {
id: token_id.get_string_repr().to_string(),
})
.attach_printable("Failed to get tokenization record")?;
when(
tokenization_record.customer_id != payload.customer_id,
|| {
Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "Tokenization record does not belong to the customer".to_string(),
})
},
)?;
when(tokenization_record.is_disabled(), || {
Err(errors::ApiErrorResponse::GenericNotFoundError {
message: "Tokenization is already disabled for the id".to_string(),
})
})?;
//fetch locker id
let vault_id = domain::VaultId::generate(tokenization_record.locker_id.clone());
//delete card from vault
pm_vault::delete_payment_method_data_from_vault_internal(
&state,
&platform,
vault_id,
&tokenization_record.customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete payment method from vault")?;
//update the status with Disabled
let tokenization_update = hyperswitch_domain_models::tokenization::TokenizationUpdate::DeleteTokenizationRecordUpdate {
flag: Some(enums::TokenizationFlag::Disabled),
};
db.update_tokenization_record(
tokenization_record,
tokenization_update,
platform.get_processor().get_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update tokenization record")?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
api_models::tokenization::DeleteTokenDataResponse {
id: token_id.clone(),
},
))
}
#[instrument(skip_all)]
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub async fn get_token_vault_core(
state: SessionState,
merchant_account: &domain::MerchantAccount,
merchant_key_store: &domain::MerchantKeyStore,
query: id_type::GlobalTokenId,
) -> CustomResult<serde_json::Value, errors::ApiErrorResponse> {
let db = state.store.as_ref();
let tokenization_record = db
.get_entity_id_vault_id_by_token_id(&query, &(merchant_key_store.clone()))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get tokenization record")?;
if tokenization_record.flag == enums::TokenizationFlag::Disabled {
return Err(errors::ApiErrorResponse::GenericNotFoundError {
message: "Tokenization is disabled for the id".to_string(),
}
.into());
}
let vault_request = pm_types::VaultRetrieveRequest {
entity_id: tokenization_record.customer_id.clone(),
vault_id: hyperswitch_domain_models::payment_methods::VaultId::generate(
tokenization_record.locker_id.clone(),
),
};
let vault_data = pm_vault::retrieve_value_from_vault(&state, vault_request)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve vault data")?;
let data_json = vault_data
.get("data")
.cloned()
.unwrap_or(serde_json::Value::Null);
// Create the response
Ok(data_json)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/unified_connector_service.rs | crates/router/src/core/unified_connector_service.rs | use std::{str::FromStr, time::Instant};
use api_models::admin;
#[cfg(feature = "v2")]
use base64::Engine;
use common_enums::{
connector_enums::Connector, AttemptStatus, CallConnectorAction, ConnectorIntegrationType,
ExecutionMode, ExecutionPath, GatewaySystem, PaymentMethodType, UcsAvailability,
};
#[cfg(feature = "v2")]
use common_utils::consts::BASE64_ENGINE;
use common_utils::{
consts::{X_CONNECTOR_NAME, X_FLOW_NAME, X_SUB_FLOW_NAME},
errors::CustomResult,
ext_traits::ValueExt,
id_type,
request::{Method, RequestBuilder, RequestContent},
};
use diesel_models::types::FeatureMetadata;
use error_stack::ResultExt;
use external_services::{
grpc_client::{
unified_connector_service::{ConnectorAuthMetadata, UnifiedConnectorServiceError},
LineageIds,
},
http_client,
};
use hyperswitch_connectors::utils::CardData;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::merchant_connector_account::{
ExternalVaultConnectorMetadata, MerchantConnectorAccountTypeDetails,
};
use hyperswitch_domain_models::{
platform::Platform,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds,
router_request_types::RefundsData,
router_response_types::{PaymentsResponseData, RefundsResponseData},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
use unified_connector_service_cards::{CardNumber, NetworkToken};
use unified_connector_service_client::payments::{
self as payments_grpc, payment_method::PaymentMethod, CardDetails, ClassicReward,
CryptoCurrency, EVoucher, OpenBanking, PaymentServiceAuthorizeResponse,
};
#[cfg(feature = "v2")]
use crate::types::api::enums as api_enums;
use crate::{
consts,
core::{
errors::{self, RouterResult},
payments::{
helpers::{
is_ucs_enabled, should_execute_based_on_rollout, MerchantConnectorAccountType,
ProxyOverride,
},
OperationSessionGetters, OperationSessionSetters,
},
utils::get_flow_name,
},
events::connector_api_logs::ConnectorEvent,
headers::{CONTENT_TYPE, X_REQUEST_ID},
routes::SessionState,
types::{
transformers::{ForeignFrom, ForeignTryFrom},
UcsAuthorizeResponseData, UcsRepeatPaymentResponseData, UcsSetupMandateResponseData,
},
};
pub mod transformers;
pub async fn get_access_token_from_ucs_response(
session_state: &SessionState,
platform: &Platform,
connector_name: &str,
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
creds_identifier: Option<String>,
ucs_state: Option<&unified_connector_service_client::payments::ConnectorState>,
) -> Option<AccessToken> {
let ucs_access_token = ucs_state
.and_then(|state| state.access_token.as_ref())
.map(AccessToken::foreign_from)?;
let merchant_id = platform.get_processor().get_account().get_id();
let merchant_connector_id_or_connector_name = merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string())
.or(creds_identifier.map(|id| id.to_string()))
.unwrap_or(connector_name.to_string());
let key = common_utils::access_token::get_default_access_token_key(
merchant_id,
merchant_connector_id_or_connector_name,
);
if let Ok(Some(cached_token)) = session_state.store.get_access_token(key).await {
if cached_token.token.peek() == ucs_access_token.token.peek() {
return None;
}
}
Some(ucs_access_token)
}
pub async fn set_access_token_for_ucs(
state: &SessionState,
platform: &Platform,
connector_name: &str,
access_token: AccessToken,
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
creds_identifier: Option<String>,
) -> Result<(), errors::StorageError> {
let merchant_id = platform.get_processor().get_account().get_id();
let merchant_connector_id_or_connector_name = merchant_connector_id
.map(|mca_id| mca_id.get_string_repr().to_string())
.or(creds_identifier.map(|id| id.to_string()))
.unwrap_or(connector_name.to_string());
let key = common_utils::access_token::get_default_access_token_key(
merchant_id,
&merchant_connector_id_or_connector_name,
);
let modified_access_token = AccessToken {
expires: access_token
.expires
.saturating_sub(consts::REDUCE_ACCESS_TOKEN_EXPIRY_TIME.into()),
..access_token
};
logger::debug!(
access_token_expiry_after_modification = modified_access_token.expires,
merchant_id = ?merchant_id,
connector_name = connector_name,
merchant_connector_id_or_connector_name = merchant_connector_id_or_connector_name
);
if let Err(access_token_set_error) = state
.store
.set_access_token(key, modified_access_token)
.await
{
// If we are not able to set the access token in redis, the error should just be logged and proceed with the payment
// Payments should not fail, once the access token is successfully created
// The next request will create new access token, if required
logger::error!(access_token_set_error=?access_token_set_error, "Failed to store UCS access token");
}
Ok(())
}
// Re-export webhook transformer types for easier access
pub use transformers::{WebhookTransformData, WebhookTransformationStatus};
/// Type alias for return type used by unified connector service response handlers
type UnifiedConnectorServiceResult = CustomResult<
(
Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>,
u16,
),
UnifiedConnectorServiceError,
>;
/// Type alias for return type used by unified connector service refund response handlers
type UnifiedConnectorServiceRefundResult =
CustomResult<(Result<RefundsResponseData, ErrorResponse>, u16), UnifiedConnectorServiceError>;
/// Checks if the Unified Connector Service (UCS) is available for use
async fn check_ucs_availability(state: &SessionState) -> UcsAvailability {
let is_client_available = state.grpc_client.unified_connector_service_client.is_some();
let is_enabled = is_ucs_enabled(state, consts::UCS_ENABLED).await;
match (is_client_available, is_enabled) {
(true, true) => {
router_env::logger::debug!("UCS is available and enabled");
UcsAvailability::Enabled
}
_ => {
router_env::logger::debug!(
"UCS client is {} and UCS is {} in configuration",
if is_client_available {
"available"
} else {
"not available"
},
if is_enabled { "enabled" } else { "not enabled" }
);
UcsAvailability::Disabled
}
}
}
/// Determines the connector integration type based on UCS configuration or on both
async fn determine_connector_integration_type(
state: &SessionState,
connector: Connector,
) -> RouterResult<ConnectorIntegrationType> {
match state.conf.grpc_client.unified_connector_service.as_ref() {
Some(ucs_config) => {
let is_ucs_only = ucs_config.ucs_only_connectors.contains(&connector);
if is_ucs_only {
router_env::logger::debug!(
connector = ?connector,
ucs_only_list = is_ucs_only,
"Using UcsConnector"
);
Ok(ConnectorIntegrationType::UcsConnector)
} else {
router_env::logger::debug!(
connector = ?connector,
"Using DirectandUCSConnector - not in ucs_only_list"
);
Ok(ConnectorIntegrationType::DirectandUCSConnector)
}
}
None => {
router_env::logger::debug!(
connector = ?connector,
"UCS config not present, using DirectandUCSConnector"
);
Ok(ConnectorIntegrationType::DirectandUCSConnector)
}
}
}
pub async fn should_call_unified_connector_service<F: Clone, T, R>(
state: &SessionState,
platform: &Platform,
router_data: &RouterData<F, T, R>,
previous_gateway: Option<GatewaySystem>,
call_connector_action: CallConnectorAction,
shadow_ucs_call_connector_action: Option<CallConnectorAction>,
) -> RouterResult<(ExecutionPath, SessionState)>
where
R: Send + Sync + Clone,
{
// Extract context information
let merchant_id = platform
.get_processor()
.get_account()
.get_id()
.get_string_repr();
let connector_name = &router_data.connector;
let connector_enum = Connector::from_str(connector_name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| format!("Failed to parse connector name: {connector_name}"))?;
let flow_name = get_flow_name::<F>()?;
// Check UCS availability using idiomatic helper
let ucs_availability = check_ucs_availability(state).await;
let rollout_key = build_rollout_keys(
merchant_id,
connector_name,
&flow_name,
router_data.payment_method,
);
// Determine connector integration type
let connector_integration_type =
determine_connector_integration_type(state, connector_enum).await?;
// Check rollout key availability and shadow key presence (optimized to reduce DB calls)
let rollout_result = should_execute_based_on_rollout(state, &rollout_key).await?;
// Single decision point using pattern matching
let (gateway_system, mut execution_path) = if ucs_availability == UcsAvailability::Disabled {
match call_connector_action {
CallConnectorAction::UCSConsumeResponse(_)
| CallConnectorAction::UCSHandleResponse(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("CallConnectorAction UCSHandleResponse/UCSConsumeResponse received but UCS is disabled. These actions are only valid in UCS gateway")?
}
CallConnectorAction::Avoid
| CallConnectorAction::Trigger
| CallConnectorAction::HandleResponse(_)
| CallConnectorAction::StatusUpdate { .. } => {
router_env::logger::debug!("UCS is disabled, using Direct gateway");
(GatewaySystem::Direct, ExecutionPath::Direct)
}
}
} else {
match call_connector_action {
CallConnectorAction::UCSConsumeResponse(_)
| CallConnectorAction::UCSHandleResponse(_) => {
router_env::logger::info!("CallConnectorAction UCSHandleResponse/UCSConsumeResponse received, using UCS gateway");
(
GatewaySystem::UnifiedConnectorService,
ExecutionPath::UnifiedConnectorService,
)
}
CallConnectorAction::HandleResponse(_) => {
router_env::logger::info!(
"CallConnectorAction HandleResponse received, using Direct gateway"
);
if shadow_ucs_call_connector_action.is_some() {
(
GatewaySystem::Direct,
ExecutionPath::ShadowUnifiedConnectorService,
)
} else {
(GatewaySystem::Direct, ExecutionPath::Direct)
}
}
CallConnectorAction::Trigger
| CallConnectorAction::Avoid
| CallConnectorAction::StatusUpdate { .. } => {
// UCS is enabled, call decide function
decide_execution_path(
connector_integration_type,
previous_gateway,
rollout_result.execution_mode,
)?
}
}
};
// Handle proxy configuration for Shadow UCS flows
let session_state = match execution_path {
ExecutionPath::ShadowUnifiedConnectorService => {
// For shadow UCS, use rollout_result for proxy configuration since it takes priority
match &rollout_result.proxy_override {
Some(proxy_override) => {
router_env::logger::debug!(
proxy_override = ?proxy_override,
"Creating updated session state with proxy configuration for Shadow UCS"
);
create_updated_session_state_with_proxy(state.clone(), proxy_override)
}
None => {
router_env::logger::debug!(
"No proxy override available for Shadow UCS, Using the Original State and Sending Request Directly"
);
execution_path = ExecutionPath::Direct;
state.clone()
}
}
}
ExecutionPath::Direct | ExecutionPath::UnifiedConnectorService => {
// For Direct and UCS flows, use original state
state.clone()
}
};
router_env::logger::info!(
"Payment gateway decision: gateway={:?}, execution_path={:?} - merchant_id={}, connector={}, flow={}",
gateway_system,
execution_path,
merchant_id,
connector_name,
flow_name
);
Ok((execution_path, session_state))
}
/// Creates a new SessionState with proxy configuration updated from the override
fn create_updated_session_state_with_proxy(
state: SessionState,
proxy_override: &ProxyOverride,
) -> SessionState {
let mut updated_state = state;
// Create updated configuration with proxy overrides
let mut updated_conf = (*updated_state.conf).clone();
// Update proxy URLs with overrides, falling back to existing values
if let Some(ref http_url) = proxy_override.http_url {
updated_conf.proxy.http_url = Some(http_url.clone());
}
if let Some(ref https_url) = proxy_override.https_url {
updated_conf.proxy.https_url = Some(https_url.clone());
}
updated_state.conf = std::sync::Arc::new(updated_conf);
updated_state
}
fn decide_execution_path(
connector_type: ConnectorIntegrationType,
previous_gateway: Option<GatewaySystem>,
execution_mode: ExecutionMode,
) -> RouterResult<(GatewaySystem, ExecutionPath)> {
match connector_type {
// UCS-only connectors always use UCS
ConnectorIntegrationType::UcsConnector => Ok((
GatewaySystem::UnifiedConnectorService,
ExecutionPath::UnifiedConnectorService,
)),
ConnectorIntegrationType::DirectandUCSConnector => {
match (previous_gateway, execution_mode) {
(Some(GatewaySystem::Direct), ExecutionMode::NotApplicable) => {
// Previous gateway was Direct, continue using Direct
Ok((GatewaySystem::Direct, ExecutionPath::Direct))
}
(Some(GatewaySystem::Direct), ExecutionMode::Primary) => {
// Previous gateway was Direct, continue using Direct
Ok((GatewaySystem::Direct, ExecutionPath::Direct))
}
(Some(GatewaySystem::Direct), ExecutionMode::Shadow) => {
// Previous gateway was Direct, but now UCS is in shadow mode for comparison
Ok((
GatewaySystem::Direct,
ExecutionPath::ShadowUnifiedConnectorService,
))
}
(Some(GatewaySystem::UnifiedConnectorService), ExecutionMode::NotApplicable) => {
// Previous gateway was UCS, continue using Direct as the config key has notapplicable execution mode
Ok((GatewaySystem::Direct, ExecutionPath::Direct))
}
(Some(GatewaySystem::UnifiedConnectorService), ExecutionMode::Primary) => {
// previous gateway was UCS, and config key has execution mode primary - continue using UCS
Ok((
GatewaySystem::UnifiedConnectorService,
ExecutionPath::UnifiedConnectorService,
))
}
(Some(GatewaySystem::UnifiedConnectorService), ExecutionMode::Shadow) => {
// previous gateway was UCS, but now UCS is in shadow mode for comparison
Ok((
GatewaySystem::Direct,
ExecutionPath::ShadowUnifiedConnectorService,
))
}
(None, ExecutionMode::Primary) => {
// Fresh payment for a UCS-enabled connector - use UCS as primary
Ok((
GatewaySystem::UnifiedConnectorService,
ExecutionPath::UnifiedConnectorService,
))
}
(None, ExecutionMode::Shadow) => {
// Fresh payment for UCS-enabled connector with shadow mode - use shadow UCS
Ok((
GatewaySystem::Direct,
ExecutionPath::ShadowUnifiedConnectorService,
))
}
(None, ExecutionMode::NotApplicable) => {
// Fresh payment request for direct connector - use direct gateway
Ok((GatewaySystem::Direct, ExecutionPath::Direct))
}
}
}
}
}
/// Build rollout keys based on flow type - include payment method for payments, skip for refunds
fn build_rollout_keys(
merchant_id: &str,
connector_name: &str,
flow_name: &str,
payment_method: common_enums::PaymentMethod,
) -> String {
// Detect if this is a refund flow based on flow name
let is_refund_flow = matches!(flow_name, "Execute" | "RSync");
let rollout_key = if is_refund_flow {
// Refund flows: UCS_merchant_connector_flow (e.g., UCS_merchant123_stripe_Execute)
format!(
"{}_{}_{}_{}",
consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
merchant_id,
connector_name,
flow_name
)
} else {
// Payment flows: UCS_merchant_connector_paymentmethod_flow (e.g., UCS_merchant123_stripe_card_Authorize)
let payment_method_str = payment_method.to_string();
format!(
"{}_{}_{}_{}_{}",
consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
merchant_id,
connector_name,
payment_method_str,
flow_name
)
};
rollout_key
}
/// Extracts the gateway system from the payment intent's feature metadata
/// Returns None if metadata is missing, corrupted, or doesn't contain gateway_system
pub fn extract_gateway_system_from_payment_intent<F: Clone, D>(
payment_data: &D,
) -> Option<GatewaySystem>
where
D: OperationSessionGetters<F>,
{
#[cfg(feature = "v1")]
{
payment_data
.get_payment_intent()
.feature_metadata
.as_ref()
.and_then(|metadata| {
// Try to parse the JSON value as FeatureMetadata
// Log errors but don't fail the flow for corrupted metadata
match serde_json::from_value::<FeatureMetadata>(metadata.clone()) {
Ok(feature_metadata) => feature_metadata.gateway_system,
Err(err) => {
router_env::logger::warn!(
"Failed to parse feature_metadata for gateway_system extraction: {}",
err
);
None
}
}
})
}
#[cfg(feature = "v2")]
{
None // V2 does not use feature metadata for gateway system tracking
}
}
/// Updates the payment intent's feature metadata to track the gateway system being used
#[cfg(feature = "v1")]
pub fn update_gateway_system_in_feature_metadata<F: Clone, D>(
payment_data: &mut D,
gateway_system: GatewaySystem,
) -> RouterResult<()>
where
D: OperationSessionGetters<F> + OperationSessionSetters<F>,
{
let mut payment_intent = payment_data.get_payment_intent().clone();
let existing_metadata = payment_intent.feature_metadata.as_ref();
let mut feature_metadata = existing_metadata
.and_then(|metadata| serde_json::from_value::<FeatureMetadata>(metadata.clone()).ok())
.unwrap_or_default();
feature_metadata.gateway_system = Some(gateway_system);
let updated_metadata = serde_json::to_value(feature_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize feature metadata")?;
payment_intent.feature_metadata = Some(updated_metadata.clone());
payment_data.set_payment_intent(payment_intent);
Ok(())
}
pub async fn should_call_unified_connector_service_for_webhooks(
state: &SessionState,
platform: &Platform,
connector_name: &str,
) -> RouterResult<ExecutionPath> {
// Extract context information
let merchant_id = platform
.get_processor()
.get_account()
.get_id()
.get_string_repr();
let connector_enum = Connector::from_str(connector_name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| format!("Failed to parse connector name: {}", connector_name))?;
let flow_name = "Webhooks";
// Check UCS availability using idiomatic helper
let ucs_availability = check_ucs_availability(state).await;
// Build rollout keys - webhooks don't use payment method, so use a simplified key format
let rollout_key = format!(
"{}_{}_{}_{}",
consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
merchant_id,
connector_name,
flow_name
);
// Determine connector integration type
let connector_integration_type =
determine_connector_integration_type(state, connector_enum).await?;
// For webhooks, there is no previous gateway system to consider (webhooks are stateless)
let previous_gateway = None;
// Check both rollout keys to determine priority based on shadow percentage
let rollout_result = should_execute_based_on_rollout(state, &rollout_key).await?;
// Use the same decision logic as payments, with no call_connector_action to consider
let (gateway_system, execution_path) = if ucs_availability == UcsAvailability::Disabled {
router_env::logger::debug!("UCS is disabled for webhooks, using Direct gateway");
(GatewaySystem::Direct, ExecutionPath::Direct)
} else {
// UCS is enabled, use decide function with no previous gateway for webhooks
decide_execution_path(
connector_integration_type,
previous_gateway,
rollout_result.execution_mode,
)?
};
router_env::logger::info!(
"Webhook gateway decision: gateway={:?}, execution_path={:?} - merchant_id={}, connector={}, flow={}",
gateway_system,
execution_path,
merchant_id,
connector_name,
flow_name
);
Ok(execution_path)
}
pub fn build_unified_connector_service_payment_method(
payment_method_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData,
payment_method_type: Option<PaymentMethodType>,
) -> CustomResult<payments_grpc::PaymentMethod, UnifiedConnectorServiceError> {
match payment_method_data {
hyperswitch_domain_models::payment_method_data::PaymentMethodData::Card(card) => {
let card_exp_month = card
.get_card_expiry_month_2_digit()
.attach_printable("Failed to extract 2-digit expiry month from card")
.change_context(UnifiedConnectorServiceError::InvalidDataFormat {
field_name: "card_exp_month",
})?
.peek()
.to_string();
let card_network = card
.card_network
.clone()
.map(payments_grpc::CardNetwork::foreign_try_from)
.transpose()?;
let card_details = CardDetails {
card_number: Some(
CardNumber::from_str(&card.card_number.get_card_no()).change_context(
UnifiedConnectorServiceError::RequestEncodingFailedWithReason(
"Failed to parse card number".to_string(),
),
)?,
),
card_exp_month: Some(card_exp_month.into()),
card_exp_year: Some(card.card_exp_year.expose().into()),
card_cvc: Some(card.card_cvc.expose().into()),
card_holder_name: card.card_holder_name.map(|name| name.expose().into()),
card_issuer: card.card_issuer.clone(),
card_network: card_network.map(|card_network| card_network.into()),
card_type: card.card_type.clone(),
bank_code: card.bank_code.clone(),
nick_name: card.nick_name.map(|n| n.expose()),
card_issuing_country_alpha2: card.card_issuing_country.clone(),
};
Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::Card(card_details)),
})
}
hyperswitch_domain_models::payment_method_data::PaymentMethodData::Upi(upi_data) => {
let upi_type = match upi_data {
hyperswitch_domain_models::payment_method_data::UpiData::UpiCollect(
upi_collect_data,
) => {
let upi_details = payments_grpc::UpiCollect {
vpa_id: upi_collect_data.vpa_id.map(|vpa| vpa.expose().into()),
upi_source: None,
};
PaymentMethod::UpiCollect(upi_details)
}
hyperswitch_domain_models::payment_method_data::UpiData::UpiIntent(_) => {
let upi_details = payments_grpc::UpiIntent {
app_name: None,
upi_source: None,
};
PaymentMethod::UpiIntent(upi_details)
}
hyperswitch_domain_models::payment_method_data::UpiData::UpiQr(_) => {
let upi_details = payments_grpc::UpiQr {
upi_source: None,
};
PaymentMethod::UpiQr(upi_details)
}
};
Ok(payments_grpc::PaymentMethod {
payment_method: Some(upi_type),
})
}
hyperswitch_domain_models::payment_method_data::PaymentMethodData::BankRedirect(
bank_redirect_data,
) => match bank_redirect_data {
hyperswitch_domain_models::payment_method_data::BankRedirectData::OpenBankingUk {
issuer,
country,
} => {
let open_banking_uk = payments_grpc::OpenBankingUk {
issuer: issuer.map(|issuer| issuer.to_string()),
country: country.map(|country| country.to_string()),
};
Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::OpenBankingUk(open_banking_uk)),
})
}
hyperswitch_domain_models::payment_method_data::BankRedirectData::OpenBanking {} =>
Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::OpenBanking(OpenBanking {})),
}),
_ => Err(UnifiedConnectorServiceError::NotImplemented(format!(
"Unimplemented bank redirect type: {bank_redirect_data:?}"
))
.into()),
},
hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward => {
match payment_method_type {
Some(PaymentMethodType::ClassicReward) => Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::ClassicReward(ClassicReward {})),
}),
Some(PaymentMethodType::Evoucher) => Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::EVoucher(EVoucher {})),
}),
None | Some(_) => Err(UnifiedConnectorServiceError::NotImplemented(format!(
"Unimplemented payment method subtype: {payment_method_type:?}"
))
.into()),
}
}
hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(wallet_data) => {
match wallet_data {
hyperswitch_domain_models::payment_method_data::WalletData::Mifinity(
mifinity_data,
) => Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::Mifinity(payments_grpc::MifinityWallet {
date_of_birth: Some(mifinity_data.date_of_birth.peek().to_string().into()),
language_preference: mifinity_data.language_preference,
})),
}),
hyperswitch_domain_models::payment_method_data::WalletData::ApplePay(
apple_pay_wallet_data
) => Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::ApplePay(payments_grpc::AppleWallet {
payment_data: Some(payments_grpc::apple_wallet::PaymentData {
payment_data: Some(payments_grpc::apple_wallet::payment_data::PaymentData::foreign_try_from(&apple_pay_wallet_data.payment_data)?),
}),
payment_method: Some(payments_grpc::apple_wallet::PaymentMethod {
display_name: apple_pay_wallet_data.payment_method.display_name,
network: apple_pay_wallet_data.payment_method.network,
r#type: apple_pay_wallet_data.payment_method.pm_type,
}),
transaction_identifier: apple_pay_wallet_data.transaction_identifier,
})),
}),
hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(
google_pay_wallet_data,
) => Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::GooglePay(payments_grpc::GoogleWallet {
r#type: google_pay_wallet_data.pm_type,
description: google_pay_wallet_data.description,
info: Some(payments_grpc::google_wallet::PaymentMethodInfo {
card_network: google_pay_wallet_data.info.card_network,
card_details: google_pay_wallet_data.info.card_details,
assurance_details: google_pay_wallet_data.info.assurance_details.map(|details| {
payments_grpc::google_wallet::payment_method_info::AssuranceDetails {
card_holder_authenticated: details.card_holder_authenticated,
account_verified: details.account_verified,
}
}),
}),
tokenization_data: Some(payments_grpc::google_wallet::TokenizationData {
tokenization_data: Some(payments_grpc::google_wallet::tokenization_data::TokenizationData::foreign_try_from(&google_pay_wallet_data.tokenization_data)?),
}),
})),
}),
hyperswitch_domain_models::payment_method_data::WalletData::GooglePayThirdPartySdk(
google_pay_sdk_data,
) => {
Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::GooglePayThirdPartySdk(
payments_grpc::GooglePayThirdPartySdkWallet {
token: google_pay_sdk_data.token.map(|t| t.expose().into()),
}
)),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/verification/utils.rs | crates/router/src/core/verification/utils.rs | use common_utils::{errors::CustomResult, id_type::PaymentId};
use error_stack::{Report, ResultExt};
use crate::{
core::{
errors::{self, utils::StorageErrorExt},
utils,
},
logger,
routes::SessionState,
types::{self, domain, storage},
};
pub async fn check_existence_and_add_domain_to_db(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
profile_id_from_auth_layer: Option<common_utils::id_type::ProfileId>,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
domain_from_req: Vec<String>,
) -> CustomResult<Vec<String>, errors::ApiErrorResponse> {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
#[cfg(feature = "v1")]
let merchant_connector_account = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&merchant_id,
&merchant_connector_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
#[cfg(feature = "v2")]
let merchant_connector_account = state
.store
.find_merchant_connector_account_by_id(&merchant_connector_id, &key_store)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&merchant_connector_account,
)?;
let mut already_verified_domains = merchant_connector_account
.applepay_verified_domains
.clone()
.unwrap_or_default();
let mut new_verified_domains: Vec<String> = domain_from_req
.into_iter()
.filter(|req_domain| !already_verified_domains.contains(req_domain))
.collect();
already_verified_domains.append(&mut new_verified_domains);
#[cfg(feature = "v1")]
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
connector_type: None,
connector_name: None,
connector_account_details: Box::new(None),
test_mode: None,
disabled: None,
merchant_connector_id: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: Box::new(None),
applepay_verified_domains: Some(already_verified_domains.clone()),
pm_auth_config: Box::new(None),
connector_label: None,
status: None,
connector_wallets_details: Box::new(None),
additional_merchant_data: Box::new(None),
};
#[cfg(feature = "v2")]
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
connector_type: None,
connector_account_details: Box::new(None),
disabled: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: Box::new(None),
applepay_verified_domains: Some(already_verified_domains.clone()),
pm_auth_config: Box::new(None),
connector_label: None,
status: None,
connector_wallets_details: Box::new(None),
additional_merchant_data: Box::new(None),
feature_metadata: Box::new(None),
};
state
.store
.update_merchant_connector_account(
merchant_connector_account,
updated_mca.into(),
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating MerchantConnectorAccount: id: {merchant_connector_id:?}",
)
})?;
Ok(already_verified_domains.clone())
}
pub fn log_applepay_verification_response_if_error(
response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>,
) {
if let Err(error) = response.as_ref() {
logger::error!(applepay_domain_verification_error= ?error);
};
response.as_ref().ok().map(|res| {
res.as_ref()
.map_err(|error| logger::error!(applepay_domain_verification_error= ?error))
});
}
#[cfg(feature = "v2")]
pub async fn check_if_profile_id_is_present_in_payment_intent(
payment_id: PaymentId,
state: &SessionState,
processor: &domain::Processor,
profile_id: Option<common_utils::id_type::ProfileId>,
) -> CustomResult<(), errors::ApiErrorResponse> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn check_if_profile_id_is_present_in_payment_intent(
payment_id: PaymentId,
state: &SessionState,
processor: &domain::Processor,
profile_id: Option<common_utils::id_type::ProfileId>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let db = &*state.store;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&payment_id,
processor.get_account().get_id(),
processor.get_key_store(),
processor.get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
utils::validate_profile_id_from_auth_layer(profile_id, &payment_intent)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/access_token.rs | crates/router/src/core/payments/access_token.rs | use std::fmt::Debug;
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use hyperswitch_interfaces::api::{gateway, ConnectorAccessTokenSuffix, ConnectorSpecifications};
use crate::{
consts,
core::{
errors::{self, RouterResult},
payments::{self, gateway::context as gateway_context},
},
routes::{metrics, SessionState},
services::{self, logger},
types::{self, api as api_types, domain},
};
/// Get cached access token for UCS flows - only reads from cache, never generates
pub async fn get_cached_access_token_for_ucs(
state: &SessionState,
connector: &api_types::ConnectorData,
platform: &domain::Platform,
payment_method: common_enums::PaymentMethod,
creds_identifier: Option<&str>,
) -> RouterResult<Option<types::AccessToken>> {
if connector
.connector_name
.supports_access_token(payment_method)
{
let merchant_id = platform.get_processor().get_account().get_id();
let store = &*state.store;
let merchant_connector_id_or_connector_name = connector
.merchant_connector_id
.clone()
.map(|mca_id| mca_id.get_string_repr().to_string())
.or(creds_identifier.map(|id| id.to_string()))
.unwrap_or(connector.connector_name.to_string());
let key = common_utils::access_token::get_default_access_token_key(
merchant_id,
merchant_connector_id_or_connector_name,
);
let cached_access_token = store
.get_access_token(key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when accessing the access token")?;
if let Some(access_token) = cached_access_token {
router_env::logger::info!(
"Cached access token found for UCS flow - merchant_id: {:?}, connector: {} with expiry of: {} seconds",
platform.get_processor().get_account().get_id(),
connector.connector_name,
access_token.expires
);
metrics::ACCESS_TOKEN_CACHE_HIT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
Ok(Some(access_token))
} else {
router_env::logger::info!(
"No cached access token found for UCS flow - UCS will generate internally - merchant_id: {:?}, connector: {}",
platform.get_processor().get_account().get_id(),
connector.connector_name
);
metrics::ACCESS_TOKEN_CACHE_MISS.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
Ok(None)
}
} else {
Ok(None)
}
}
/// After we get the access token, check if there was an error and if the flow should proceed further
/// Returns bool
/// true - Everything is well, continue with the flow
/// false - There was an error, cannot proceed further
pub fn update_router_data_with_access_token_result<F, Req, Res>(
add_access_token_result: &types::AddAccessTokenResult,
router_data: &mut types::RouterData<F, Req, Res>,
call_connector_action: &payments::CallConnectorAction,
) -> bool {
// Update router data with access token or error only if it will be calling connector
let should_update_router_data = matches!(
(
add_access_token_result.connector_supports_access_token,
call_connector_action
),
(true, payments::CallConnectorAction::Trigger)
);
if should_update_router_data {
match add_access_token_result.access_token_result.as_ref() {
Ok(access_token) => {
router_data.access_token.clone_from(access_token);
true
}
Err(connector_error) => {
router_data.response = Err(connector_error.clone());
false
}
}
} else {
true
}
}
pub async fn add_access_token<
F: Clone + 'static,
Req: Debug + Clone + 'static,
Res: Debug + Clone + 'static,
>(
state: &SessionState,
connector: &api_types::ConnectorData,
router_data: &types::RouterData<F, Req, Res>,
creds_identifier: Option<&str>,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
if connector
.connector_name
.supports_access_token(router_data.payment_method)
{
let merchant_id = &router_data.merchant_id;
let store = &*state.store;
// `merchant_connector_id` may not be present in the below cases
// - when straight through routing is used without passing the `merchant_connector_id`
// - when creds identifier is passed
//
// In these cases fallback to `connector_name`.
// We cannot use multiple merchant connector account in these cases
let merchant_connector_id_or_connector_name = connector
.merchant_connector_id
.clone()
.map(|mca_id| mca_id.get_string_repr().to_string())
.or(creds_identifier.map(|id| id.to_string()))
.unwrap_or(connector.connector_name.to_string());
let key = connector
.connector
.get_access_token_key(router_data, merchant_connector_id_or_connector_name.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Failed to get access token key for connector: {:?}",
connector.connector_name
))?;
let old_access_token = store
.get_access_token(key.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when accessing the access token")?;
let res = match old_access_token {
Some(access_token) => {
router_env::logger::debug!(
"Access token found in redis for merchant_id: {:?}, payment_id: {:?}, connector: {} which has expiry of: {} seconds",
merchant_id,
router_data.payment_id,
connector.connector_name,
access_token.expires
);
metrics::ACCESS_TOKEN_CACHE_HIT.add(
1,
router_env::metric_attributes!((
"connector",
connector.connector_name.to_string()
)),
);
Ok(Some(access_token))
}
None => {
metrics::ACCESS_TOKEN_CACHE_MISS.add(
1,
router_env::metric_attributes!((
"connector",
connector.connector_name.to_string()
)),
);
let authentication_token =
execute_authentication_token(state, connector, router_data).await?;
let cloned_router_data = router_data.clone();
let refresh_token_request_data = types::AccessTokenRequestData::try_from((
router_data.connector_auth_type.clone(),
authentication_token,
))
.attach_printable(
"Could not create access token request, invalid connector account credentials",
)?;
let refresh_token_response_data: Result<types::AccessToken, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let refresh_token_router_data = payments::helpers::router_data_type_conversion::<
_,
api_types::AccessTokenAuth,
_,
_,
_,
_,
>(
cloned_router_data,
refresh_token_request_data,
refresh_token_response_data,
);
refresh_connector_auth(
state,
connector,
&refresh_token_router_data,
gateway_context,
)
.await?
.async_map(|access_token| async move {
let store = &*state.store;
// The expiry should be adjusted for network delays from the connector
// The access token might not have been expired when request is sent
// But once it reaches the connector, it might expire because of the network delay
// Subtract few seconds from the expiry in order to account for these network delays
// This will reduce the expiry time by `REDUCE_ACCESS_TOKEN_EXPIRY_TIME` seconds
let modified_access_token_with_expiry = types::AccessToken {
expires: access_token
.expires
.saturating_sub(consts::REDUCE_ACCESS_TOKEN_EXPIRY_TIME.into()),
..access_token
};
logger::debug!(
access_token_expiry_after_modification =
modified_access_token_with_expiry.expires
);
if let Err(access_token_set_error) = store
.set_access_token(key.clone(), modified_access_token_with_expiry.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DB error when setting the access token")
{
// If we are not able to set the access token in redis, the error should just be logged and proceed with the payment
// Payments should not fail, once the access token is successfully created
// The next request will create new access token, if required
logger::error!(access_token_set_error=?access_token_set_error);
}
Some(modified_access_token_with_expiry)
})
.await
}
};
Ok(types::AddAccessTokenResult {
access_token_result: res,
connector_supports_access_token: true,
})
} else {
Ok(types::AddAccessTokenResult {
access_token_result: Err(types::ErrorResponse::default()),
connector_supports_access_token: false,
})
}
}
pub async fn refresh_connector_auth(
state: &SessionState,
connector: &api_types::ConnectorData,
router_data: &types::RouterData<
api_types::AccessTokenAuth,
types::AccessTokenRequestData,
types::AccessToken,
>,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Result<types::AccessToken, types::ErrorResponse>> {
let connector_integration: services::BoxedAccessTokenConnectorIntegrationInterface<
api_types::AccessTokenAuth,
types::AccessTokenRequestData,
types::AccessToken,
> = connector.connector.get_connector_integration();
let access_token_router_data_result = gateway::execute_payment_gateway(
state,
connector_integration,
router_data,
payments::CallConnectorAction::Trigger,
None,
None,
gateway_context.clone(),
)
.await;
let access_token_router_data = match access_token_router_data_result {
Ok(router_data) => Ok(router_data.response),
Err(connector_error) => {
// If we receive a timeout error from the connector, then
// the error has to be handled gracefully by updating the payment status to failed.
// further payment flow will not be continued
if connector_error.current_context().is_connector_timeout() {
let error_response = types::ErrorResponse {
code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(),
reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()),
status_code: 504,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
};
Ok(Err(error_response))
} else {
Err(connector_error
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not refresh access token"))
}
}
}?;
metrics::ACCESS_TOKEN_CREATION.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
Ok(access_token_router_data)
}
pub async fn execute_authentication_token<
F: Clone + 'static,
Req: Debug + Clone + 'static,
Res: Debug + Clone + 'static,
>(
state: &SessionState,
connector: &api_types::ConnectorData,
router_data: &types::RouterData<F, Req, Res>,
) -> RouterResult<Option<types::AccessTokenAuthenticationResponse>> {
let should_create_authentication_token = connector
.connector
.authentication_token_for_token_creation();
if !should_create_authentication_token {
return Ok(None);
}
let authentication_token_request_data = types::AccessTokenAuthenticationRequestData::try_from(
router_data.connector_auth_type.clone(),
)
.attach_printable(
"Could not create authentication token request, invalid connector account credentials",
)?;
let authentication_token_response_data: Result<
types::AccessTokenAuthenticationResponse,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let auth_token_router_data = payments::helpers::router_data_type_conversion::<
_,
api_types::AccessTokenAuthentication,
_,
_,
_,
_,
>(
router_data.clone(),
authentication_token_request_data,
authentication_token_response_data,
);
let connector_integration: services::BoxedAuthenticationTokenConnectorIntegrationInterface<
api_types::AccessTokenAuthentication,
types::AccessTokenAuthenticationRequestData,
types::AccessTokenAuthenticationResponse,
> = connector.connector.get_connector_integration();
let auth_token_router_data_result = services::execute_connector_processing_step(
state,
connector_integration,
&auth_token_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await;
let auth_token_result = match auth_token_router_data_result {
Ok(router_data) => router_data.response,
Err(connector_error) => {
// Handle timeout errors
if connector_error.current_context().is_connector_timeout() {
let error_response = types::ErrorResponse {
code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(),
reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()),
status_code: 504,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
};
Err(error_response)
} else {
return Err(connector_error
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not get authentication token"));
}
}
};
let authentication_token = auth_token_result
.map_err(|_error| errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get authentication token")?;
Ok(Some(authentication_token))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/routing.rs | crates/router/src/core/payments/routing.rs | mod transformers;
pub mod utils;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use std::collections::hash_map;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use std::hash::{Hash, Hasher};
use std::{collections::HashMap, str::FromStr, sync::Arc};
#[cfg(feature = "v1")]
use api_models::open_router::{self as or_types, DecidedGateway, OpenRouterDecideGatewayRequest};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use api_models::routing as api_routing;
use api_models::{
admin as admin_api,
enums::{self as api_enums, CountryAlpha2},
routing::ConnectorSelection,
};
use common_types::payments as common_payments_types;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use common_utils::ext_traits::AsyncExt;
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
use euclid::{
backend::{self, inputs as dsl_inputs, EuclidBackend},
dssa::graph::{self as euclid_graph, CgraphExt},
enums as euclid_enums,
frontend::{ast, dir as euclid_dir},
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use external_services::grpc_client::dynamic_routing::{
contract_routing_client::ContractBasedDynamicRouting,
elimination_based_client::EliminationBasedRouting,
success_rate_client::SuccessBasedDynamicRouting, DynamicRoutingError,
};
use hyperswitch_domain_models::address::Address;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use hyperswitch_interfaces::events::routing_api_logs::{ApiMethod, RoutingEngine};
use kgraph_utils::{
mca as mca_graph,
transformers::{IntoContext, IntoDirValue},
types::CountryCurrencyFilter,
};
use masking::{PeekInterface, Secret};
use rand::distributions::{self, Distribution};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use rand::SeedableRng;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE};
#[cfg(feature = "v2")]
use crate::core::admin;
#[cfg(feature = "payouts")]
use crate::core::payouts;
#[cfg(feature = "v1")]
use crate::core::routing::transformers::OpenRouterDecideGatewayRequestExt;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use crate::routes::app::SessionStateInfo;
use crate::{
core::{
errors, errors as oss_errors,
payments::{
routing::utils::DecisionEngineApiHandler, OperationSessionGetters,
OperationSessionSetters,
},
routing,
},
logger, services,
types::{
api::{self, routing as routing_types},
domain, storage as oss_storage,
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
},
utils::{OptionExt, ValueExt},
SessionState,
};
pub enum CachedAlgorithm {
Single(Box<routing_types::RoutableConnectorChoice>),
Priority(Vec<routing_types::RoutableConnectorChoice>),
VolumeSplit(Vec<routing_types::ConnectorVolumeSplit>),
Advanced(backend::VirInterpreterBackend<ConnectorSelection>),
}
#[cfg(feature = "v1")]
pub struct SessionFlowRoutingInput<'a> {
pub state: &'a SessionState,
pub country: Option<CountryAlpha2>,
pub key_store: &'a domain::MerchantKeyStore,
pub merchant_account: &'a domain::MerchantAccount,
pub payment_attempt: &'a oss_storage::PaymentAttempt,
pub payment_intent: &'a oss_storage::PaymentIntent,
pub chosen: api::SessionConnectorDatas,
}
#[cfg(feature = "v2")]
pub struct SessionFlowRoutingInput<'a> {
pub country: Option<CountryAlpha2>,
pub payment_intent: &'a oss_storage::PaymentIntent,
pub chosen: api::SessionConnectorDatas,
}
#[allow(dead_code)]
#[cfg(feature = "v1")]
pub struct SessionRoutingPmTypeInput<'a> {
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
attempt_id: &'a str,
routing_algorithm: &'a MerchantAccountRoutingAlgorithm,
backend_input: dsl_inputs::BackendInput,
allowed_connectors: FxHashMap<String, api::GetToken>,
profile_id: &'a common_utils::id_type::ProfileId,
}
#[cfg(feature = "v2")]
pub struct SessionRoutingPmTypeInput<'a> {
routing_algorithm: &'a MerchantAccountRoutingAlgorithm,
backend_input: dsl_inputs::BackendInput,
allowed_connectors: FxHashMap<String, api::GetToken>,
profile_id: &'a common_utils::id_type::ProfileId,
}
type RoutingResult<O> = oss_errors::CustomResult<O, errors::RoutingError>;
#[cfg(feature = "v1")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum MerchantAccountRoutingAlgorithm {
V1(routing_types::RoutingAlgorithmRef),
}
#[cfg(feature = "v1")]
impl Default for MerchantAccountRoutingAlgorithm {
fn default() -> Self {
Self::V1(routing_types::RoutingAlgorithmRef::default())
}
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum MerchantAccountRoutingAlgorithm {
V1(Option<common_utils::id_type::RoutingId>),
}
#[cfg(feature = "payouts")]
pub fn make_dsl_input_for_payouts(
payout_data: &payouts::PayoutData,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate = dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
};
let metadata = payout_data
.payouts
.metadata
.clone()
.map(|val| val.parse_value("routing_parameters"))
.transpose()
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payouts")
.unwrap_or(None);
let payment = dsl_inputs::PaymentInput {
amount: payout_data.payouts.amount,
card_bin: None,
transaction_initiator: None,
extended_card_bin: None,
currency: payout_data.payouts.destination_currency,
authentication_type: None,
capture_method: None,
business_country: payout_data
.payout_attempt
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: payout_data
.billing_address
.as_ref()
.and_then(|ba| ba.address.as_ref())
.and_then(|addr| addr.country)
.map(api_enums::Country::from_alpha2),
business_label: payout_data.payout_attempt.business_label.clone(),
setup_future_usage: None,
};
let payment_method = dsl_inputs::PaymentMethodInput {
payment_method: payout_data
.payouts
.payout_type
.map(api_enums::PaymentMethod::foreign_from),
payment_method_type: payout_data
.payout_method_data
.as_ref()
.map(api_enums::PaymentMethodType::foreign_from)
.or_else(|| {
payout_data.payment_method.as_ref().and_then(|pm| {
#[cfg(feature = "v1")]
{
pm.payment_method_type
}
#[cfg(feature = "v2")]
{
pm.payment_method_subtype
}
})
}),
card_network: None,
};
Ok(dsl_inputs::BackendInput {
mandate,
metadata,
payment,
payment_method,
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
})
}
#[cfg(feature = "v2")]
pub fn make_dsl_input(
payments_dsl_input: &routing::PaymentsDslInput<'_>,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate_data = dsl_inputs::MandateData {
mandate_acceptance_type: payments_dsl_input.setup_mandate.as_ref().and_then(
|mandate_data| {
mandate_data
.customer_acceptance
.as_ref()
.map(|customer_accept| match customer_accept.acceptance_type {
common_payments_types::AcceptanceType::Online => {
euclid_enums::MandateAcceptanceType::Online
}
common_payments_types::AcceptanceType::Offline => {
euclid_enums::MandateAcceptanceType::Offline
}
})
},
),
mandate_type: payments_dsl_input
.setup_mandate
.as_ref()
.and_then(|mandate_data| {
mandate_data
.mandate_type
.clone()
.map(|mandate_type| match mandate_type {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => {
euclid_enums::MandateType::SingleUse
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => {
euclid_enums::MandateType::MultiUse
}
})
}),
payment_type: Some(
if payments_dsl_input
.recurring_details
.as_ref()
.is_some_and(|data| {
matches!(
data,
api_models::mandates::RecurringDetails::ProcessorPaymentToken(_)
)
})
{
euclid_enums::PaymentType::PptMandate
} else {
payments_dsl_input.setup_mandate.map_or_else(
|| euclid_enums::PaymentType::NonMandate,
|_| euclid_enums::PaymentType::SetupMandate,
)
},
),
};
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: Some(payments_dsl_input.payment_attempt.payment_method_type),
payment_method_type: Some(payments_dsl_input.payment_attempt.payment_method_subtype),
card_network: payments_dsl_input
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => card.card_network.clone(),
_ => None,
}),
};
let payment_input = dsl_inputs::PaymentInput {
amount: payments_dsl_input
.payment_attempt
.amount_details
.get_net_amount(),
card_bin: payments_dsl_input.payment_method_data.as_ref().and_then(
|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => Some(card.card_number.get_card_isin()),
_ => None,
},
),
transaction_initiator: None,
extended_card_bin: payments_dsl_input
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => {
Some(card.card_number.peek().chars().take(8).collect::<String>())
}
_ => None,
}),
currency: payments_dsl_input.currency,
authentication_type: Some(payments_dsl_input.payment_attempt.authentication_type),
capture_method: Some(payments_dsl_input.payment_intent.capture_method),
business_country: None,
billing_country: payments_dsl_input
.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address_details| address_details.country)
.map(api_enums::Country::from_alpha2),
business_label: None,
setup_future_usage: Some(payments_dsl_input.payment_intent.setup_future_usage),
};
let metadata = payments_dsl_input
.payment_intent
.metadata
.clone()
.map(|value| value.parse_value("routing_parameters"))
.transpose()
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
Ok(dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: mandate_data,
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
})
}
#[cfg(feature = "v1")]
pub fn make_dsl_input(
payments_dsl_input: &routing::PaymentsDslInput<'_>,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate_data = dsl_inputs::MandateData {
mandate_acceptance_type: payments_dsl_input.setup_mandate.as_ref().and_then(
|mandate_data| {
mandate_data
.customer_acceptance
.as_ref()
.map(|cat| match cat.acceptance_type {
common_payments_types::AcceptanceType::Online => {
euclid_enums::MandateAcceptanceType::Online
}
common_payments_types::AcceptanceType::Offline => {
euclid_enums::MandateAcceptanceType::Offline
}
})
},
),
mandate_type: payments_dsl_input
.setup_mandate
.as_ref()
.and_then(|mandate_data| {
mandate_data.mandate_type.clone().map(|mt| match mt {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(_) => {
euclid_enums::MandateType::SingleUse
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(_) => {
euclid_enums::MandateType::MultiUse
}
})
}),
payment_type: Some(
if payments_dsl_input
.recurring_details
.as_ref()
.is_some_and(|data| {
matches!(
data,
api_models::mandates::RecurringDetails::ProcessorPaymentToken(_)
)
})
{
euclid_enums::PaymentType::PptMandate
} else {
payments_dsl_input.setup_mandate.map_or_else(
|| euclid_enums::PaymentType::NonMandate,
|_| euclid_enums::PaymentType::SetupMandate,
)
},
),
};
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: payments_dsl_input.payment_attempt.payment_method,
payment_method_type: payments_dsl_input.payment_attempt.payment_method_type,
card_network: payments_dsl_input
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => card.card_network.clone(),
_ => None,
}),
};
let issuer_data_input = dsl_inputs::IssuerDataInput {
name: payments_dsl_input
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => card.card_issuer.clone(),
_ => None,
}),
country: payments_dsl_input.payment_method_data.as_ref().and_then(
|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => {
card.card_issuing_country_code.clone().and_then(|code| {
CountryAlpha2::from_str(&code)
.ok()
.map(common_enums::Country::from_alpha2)
})
}
_ => None,
},
),
};
let issuer_data = match (&issuer_data_input.name, &issuer_data_input.country) {
(None, None) => None,
_ => Some(issuer_data_input),
};
let payment_input = dsl_inputs::PaymentInput {
amount: payments_dsl_input.payment_attempt.get_total_amount(),
card_bin: payments_dsl_input.payment_method_data.as_ref().and_then(
|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => {
Some(card.card_number.peek().chars().take(6).collect())
}
_ => None,
},
),
transaction_initiator: match payments_dsl_input.payment_intent.off_session {
Some(true) => Some(euclid_dir::enums::TransactionInitiator::Merchant),
_ => Some(euclid_dir::enums::TransactionInitiator::Customer),
},
extended_card_bin: payments_dsl_input
.payment_method_data
.as_ref()
.and_then(|pm_data| match pm_data {
domain::PaymentMethodData::Card(card) => {
Some(card.card_number.peek().chars().take(8).collect())
}
_ => None,
}),
currency: payments_dsl_input.currency,
authentication_type: payments_dsl_input.payment_attempt.authentication_type,
capture_method: payments_dsl_input
.payment_attempt
.capture_method
.and_then(|cm| cm.foreign_into()),
business_country: payments_dsl_input
.payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: payments_dsl_input
.address
.get_payment_method_billing()
.and_then(|bic| bic.address.as_ref())
.and_then(|add| add.country)
.map(api_enums::Country::from_alpha2),
business_label: payments_dsl_input.payment_intent.business_label.clone(),
setup_future_usage: payments_dsl_input.payment_intent.setup_future_usage,
};
let metadata = payments_dsl_input
.payment_intent
.parse_and_get_metadata("routing_parameters")
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payment_intent")
.unwrap_or(None);
Ok(dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: mandate_data,
acquirer_data: None,
customer_device_data: None,
issuer_data,
})
}
pub async fn perform_static_routing_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: Option<&common_utils::id_type::RoutingId>,
business_profile: &domain::Profile,
transaction_data: &routing::TransactionData<'_>,
) -> RoutingResult<(
Vec<routing_types::RoutableConnectorChoice>,
Option<common_enums::RoutingApproach>,
)> {
logger::debug!("euclid_routing: performing routing for connector selection");
let get_merchant_fallback_config = || async {
#[cfg(feature = "v1")]
return routing::helpers::get_merchant_default_config(
&*state.clone().store,
business_profile.get_id().get_string_repr(),
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed);
#[cfg(feature = "v2")]
return admin::ProfileWrapper::new(business_profile.clone())
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed);
};
let fallback_config = get_merchant_fallback_config().await?;
let algorithm_id = if let Some(id) = algorithm_id {
id
} else {
logger::debug!("euclid_routing: active algorithm isn't present, default falling back");
return Ok((fallback_config, None));
};
let cached_algorithm = match ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
)
.await
{
Ok(algo) => algo,
Err(err) => {
logger::error!(
error=?err,
"euclid_routing: ensure_algorithm_cached failed, falling back to merchant default connectors"
);
return Ok((fallback_config, None));
}
};
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
let payment_id = match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
.payment_attempt
.payment_id
.clone()
.get_string_repr()
.to_string(),
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => payout_data
.payout_attempt
.payout_id
.get_string_repr()
.to_string(),
};
// Decision of de-routing is stored
let de_evaluated_connector = if !state.conf.open_router.static_routing_enabled {
logger::debug!("decision_engine_euclid: decision_engine routing not enabled");
Vec::default()
} else {
utils::decision_engine_routing(
state,
backend_input.clone(),
business_profile,
payment_id,
fallback_config,
)
.await
.map_err(|e|
// errors are ignored as this is just for diff checking as of now (optional flow).
logger::error!(decision_engine_euclid_evaluate_error=?e, "decision_engine_euclid: error in evaluation of rule")
)
.unwrap_or_default()
};
let (routable_connectors, routing_approach) = match cached_algorithm.as_ref() {
CachedAlgorithm::Single(conn) => (
vec![(**conn).clone()],
Some(common_enums::RoutingApproach::StraightThroughRouting),
),
CachedAlgorithm::Priority(plist) => (plist.clone(), None),
CachedAlgorithm::VolumeSplit(splits) => (
perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)?,
Some(common_enums::RoutingApproach::VolumeBasedRouting),
),
CachedAlgorithm::Advanced(interpreter) => (
execute_dsl_and_get_connector_v1(backend_input, interpreter)?,
Some(common_enums::RoutingApproach::RuleBasedRouting),
),
};
// Results are logged for diff(between legacy and decision_engine's euclid) and have parameters as:
// is_equal: verifies all output are matching in order,
// is_equal_length: matches length of both outputs (useful for verifying volume based routing
// results)
// de_response: response from the decision_engine's euclid
// hs_response: response from legacy_euclid
utils::compare_and_log_result(
de_evaluated_connector.clone(),
routable_connectors.clone(),
"evaluate_routing".to_string(),
);
Ok((
utils::select_routing_result(
state,
business_profile,
routable_connectors,
de_evaluated_connector,
)
.await,
routing_approach,
))
}
async fn ensure_algorithm_cached_v1(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let key = {
match transaction_type {
common_enums::TransactionType::Payment => {
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
)
}
#[cfg(feature = "payouts")]
common_enums::TransactionType::Payout => {
format!(
"routing_config_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
common_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
}
};
let cached_algorithm = ROUTING_CACHE
.get_val::<Arc<CachedAlgorithm>>(CacheKey {
key: key.clone(),
prefix: state.tenant.redis_key_prefix.clone(),
})
.await;
let algorithm = if let Some(algo) = cached_algorithm {
algo
} else {
refresh_routing_cache_v1(state, key.clone(), algorithm_id, profile_id).await?
};
Ok(algorithm)
}
pub fn perform_straight_through_routing(
algorithm: &routing_types::StraightThroughAlgorithm,
creds_identifier: Option<&str>,
) -> RoutingResult<(Vec<routing_types::RoutableConnectorChoice>, bool)> {
Ok(match algorithm {
routing_types::StraightThroughAlgorithm::Single(conn) => {
(vec![(**conn).clone()], creds_identifier.is_none())
}
routing_types::StraightThroughAlgorithm::Priority(conns) => (conns.clone(), true),
routing_types::StraightThroughAlgorithm::VolumeSplit(splits) => (
perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)
.attach_printable(
"Volume Split connector selection error in straight through routing",
)?,
true,
),
})
}
pub fn perform_routing_for_single_straight_through_algorithm(
algorithm: &routing_types::StraightThroughAlgorithm,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
Ok(match algorithm {
routing_types::StraightThroughAlgorithm::Single(connector) => vec![(**connector).clone()],
routing_types::StraightThroughAlgorithm::Priority(_)
| routing_types::StraightThroughAlgorithm::VolumeSplit(_) => {
Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.attach_printable("Unsupported algorithm received as a result of static routing")?
}
})
}
fn execute_dsl_and_get_connector_v1(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<ConnectorSelection>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let routing_output: routing_types::StaticRoutingAlgorithm = interpreter
.execute(backend_input)
.map(|out| out.connector_selection.foreign_into())
.change_context(errors::RoutingError::DslExecutionError)?;
Ok(match routing_output {
routing_types::StaticRoutingAlgorithm::Priority(plist) => plist,
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => perform_volume_split(splits)
.change_context(errors::RoutingError::DslFinalConnectorSelectionFailed)?,
_ => Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.attach_printable("Unsupported algorithm received as a result of static routing")?,
})
}
pub async fn refresh_routing_cache_v1(
state: &SessionState,
key: String,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> RoutingResult<Arc<CachedAlgorithm>> {
let algorithm = {
let algorithm = state
.store
.find_routing_algorithm_by_profile_id_algorithm_id(profile_id, algorithm_id)
.await
.change_context(errors::RoutingError::DslMissingInDb)?;
let algorithm: routing_types::StaticRoutingAlgorithm = algorithm
.algorithm_data
.parse_value("RoutingAlgorithm")
.change_context(errors::RoutingError::DslParsingError)?;
algorithm
};
let cached_algorithm = match algorithm {
routing_types::StaticRoutingAlgorithm::Single(conn) => CachedAlgorithm::Single(conn),
routing_types::StaticRoutingAlgorithm::Priority(plist) => CachedAlgorithm::Priority(plist),
routing_types::StaticRoutingAlgorithm::VolumeSplit(splits) => {
CachedAlgorithm::VolumeSplit(splits)
}
routing_types::StaticRoutingAlgorithm::Advanced(program) => {
let interpreter = backend::VirInterpreterBackend::with_program(program)
.change_context(errors::RoutingError::DslBackendInitError)
.attach_printable("Error initializing DSL interpreter backend")?;
CachedAlgorithm::Advanced(interpreter)
}
api_models::routing::StaticRoutingAlgorithm::ThreeDsDecisionRule(_program) => {
Err(errors::RoutingError::InvalidRoutingAlgorithmStructure)
.attach_printable("Unsupported algorithm received")?
}
};
let arc_cached_algorithm = Arc::new(cached_algorithm);
ROUTING_CACHE
.push(
CacheKey {
key,
prefix: state.tenant.redis_key_prefix.clone(),
},
arc_cached_algorithm.clone(),
)
.await;
Ok(arc_cached_algorithm)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub fn perform_dynamic_routing_volume_split(
splits: Vec<api_models::routing::RoutingVolumeSplit>,
rng_seed: Option<&str>,
) -> RoutingResult<api_models::routing::RoutingVolumeSplit> {
let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();
let weighted_index = distributions::WeightedIndex::new(weights)
.change_context(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Error creating weighted distribution for volume split")?;
let idx = if let Some(seed) = rng_seed {
let mut hasher = hash_map::DefaultHasher::new();
seed.hash(&mut hasher);
let hash = hasher.finish();
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(hash);
weighted_index.sample(&mut rng)
} else {
let mut rng = rand::thread_rng();
weighted_index.sample(&mut rng)
};
let routing_choice = *splits
.get(idx)
.ok_or(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Volume split index lookup failed")?;
Ok(routing_choice)
}
pub fn perform_volume_split(
mut splits: Vec<routing_types::ConnectorVolumeSplit>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let weights: Vec<u8> = splits.iter().map(|sp| sp.split).collect();
let weighted_index = distributions::WeightedIndex::new(weights)
.change_context(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Error creating weighted distribution for volume split")?;
let mut rng = rand::thread_rng();
let idx = weighted_index.sample(&mut rng);
splits
.get(idx)
.ok_or(errors::RoutingError::VolumeSplitFailed)
.attach_printable("Volume split index lookup failed")?;
// Panic Safety: We have performed a `get(idx)` operation just above which will
// ensure that the index is always present, else throw an error.
let removed = splits.remove(idx);
splits.insert(0, removed);
Ok(splits.into_iter().map(|sp| sp.connector).collect())
}
// #[cfg(feature = "v1")]
pub async fn get_merchant_cgraph(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let merchant_id = &key_store.merchant_id;
let key = {
match transaction_type {
api_enums::TransactionType::Payment => {
format!(
"cgraph_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
format!(
"cgraph_po_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
}
api_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
}
};
let cached_cgraph = CGRAPH_CACHE
.get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>>(
CacheKey {
key: key.clone(),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/customers.rs | crates/router/src/core/payments/customers.rs | pub use hyperswitch_domain_models::customer::update_connector_customer_in_customers;
use hyperswitch_interfaces::api::{gateway, ConnectorSpecifications};
use router_env::{instrument, tracing};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, gateway::context as gateway_context},
},
logger,
routes::{metrics, SessionState},
services,
types::{self, api, domain},
};
#[instrument(skip_all)]
pub async fn create_connector_customer<F: Clone, T: Clone>(
state: &SessionState,
connector: &api::ConnectorData,
router_data: &types::RouterData<F, T, types::PaymentsResponseData>,
customer_request_data: types::ConnectorCustomerData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<String>> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CreateConnectorCustomer,
types::ConnectorCustomerData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let customer_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let customer_router_data = payments::helpers::router_data_type_conversion::<
_,
api::CreateConnectorCustomer,
_,
_,
_,
_,
>(
router_data.clone(),
customer_request_data,
customer_response_data,
);
let resp = gateway::execute_payment_gateway(
state,
connector_integration,
&customer_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
gateway_context.clone(),
)
.await
.to_payment_failed_response()?;
metrics::CONNECTOR_CUSTOMER_CREATE.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_customer_id = match resp.response {
Ok(response) => match response {
types::PaymentsResponseData::ConnectorCustomerResponse(customer_data) => {
Some(customer_data.connector_customer_id)
}
_ => None,
},
Err(err) => {
logger::error!(create_connector_customer_error=?err);
None
}
};
Ok(connector_customer_id)
}
#[cfg(feature = "v1")]
pub fn should_call_connector_create_customer<'a>(
connector: &api::ConnectorData,
customer: &'a Option<domain::Customer>,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
connector_label: &str,
) -> (bool, Option<&'a str>) {
// Check if create customer is required for the connector
let connector_needs_customer = connector
.connector
.should_call_connector_customer(payment_attempt);
let connector_customer_details = customer
.as_ref()
.and_then(|customer| customer.get_connector_customer_id(connector_label));
if connector_needs_customer {
let should_call_connector = connector_customer_details.is_none();
(should_call_connector, connector_customer_details)
} else {
// Populates connector_customer_id if it is present after data migration
// For connector which does not have create connector customer flow
(false, connector_customer_details)
}
}
#[cfg(feature = "v2")]
pub fn should_call_connector_create_customer<'a>(
connector: &api::ConnectorData,
customer: &'a Option<domain::Customer>,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
) -> (bool, Option<&'a str>) {
// Check if create customer is required for the connector
match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(_) => {
let connector_needs_customer = connector
.connector
.should_call_connector_customer(payment_attempt);
if connector_needs_customer {
let connector_customer_details = customer
.as_ref()
.and_then(|cust| cust.get_connector_customer_id(merchant_connector_account));
let should_call_connector = connector_customer_details.is_none();
(should_call_connector, connector_customer_details)
} else {
(false, None)
}
}
// TODO: Construct connector_customer for MerchantConnectorDetails if required by connector.
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
todo!("Handle connector_customer construction for MerchantConnectorDetails");
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/session_token.rs | crates/router/src/core/payments/session_token.rs | use std::fmt::Debug;
use common_enums::enums;
use error_stack::{report, ResultExt};
use hyperswitch_interfaces::api::{gateway, ConnectorSpecifications};
use crate::{
core::{
errors,
errors::utils::ConnectorErrorExt,
payments::{gateway::context as gateway_context, RouterResult},
},
logger, routes, services, types,
types::{api as api_types, transformers::ForeignFrom},
};
pub(crate) async fn add_session_token_if_needed<F: Clone, Req: Debug + Clone>(
router_data: &types::RouterData<F, Req, types::PaymentsResponseData>,
state: &routes::SessionState,
connector: &api_types::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<String>>
where
types::AuthorizeSessionTokenData:
for<'a> ForeignFrom<&'a types::RouterData<F, Req, types::PaymentsResponseData>>,
{
if connector
.connector
.is_authorize_session_token_call_required()
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api_types::AuthorizeSessionToken,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let authorize_session_token_router_data =
&types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
router_data,
types::AuthorizeSessionTokenData::foreign_from(router_data),
));
let resp = gateway::execute_payment_gateway(
state,
connector_integration,
authorize_session_token_router_data,
enums::CallConnectorAction::Trigger,
None,
None,
gateway_context.clone(),
)
.await
.to_payment_failed_response()?;
let session_token_respone = resp
.response
.map_err(|error| {
logger::error!(session_token_create_error = error.reason);
report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Faied to perform session token call".to_string()
})
})
.attach_printable(format!(
"Failed to create session token for connector: {:?}",
connector.connector
))?;
let session_token = match session_token_respone {
types::PaymentsResponseData::SessionTokenResponse { session_token } => {
Ok(session_token)
}
_ => Err(report!(errors::ApiErrorResponse::InternalServerError)).attach_printable(
"Found Unexpected Response for Authorize Session Token Response from Connector",
),
}?;
Ok(Some(session_token))
} else {
Ok(None)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/helpers.rs | crates/router/src/core/payments/helpers.rs | use std::{borrow::Cow, collections::HashSet, net::IpAddr, ops::Deref, str::FromStr};
pub use ::payment_methods::helpers::{
populate_bin_details_for_payment_method_create,
validate_payment_method_type_against_payment_method,
};
#[cfg(feature = "v2")]
use api_models::ephemeral_key::ClientSecretResponse;
use api_models::{
mandates::RecurringDetails,
payments::{additional_info as payment_additional_types, RequestSurchargeDetails},
};
use base64::Engine;
use common_enums::{enums::ExecutionMode, ConnectorType};
#[cfg(feature = "v2")]
use common_utils::id_type::GenerateId;
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt},
fp_utils, generate_id,
id_type::{self},
new_type::{MaskedIban, MaskedSortCode},
pii, type_name,
types::{
keymanager::{Identifier, KeyManagerState, ToEncryptable},
MinorUnit,
},
};
use diesel_models::enums;
// TODO : Evaluate all the helper functions ()
use error_stack::{report, ResultExt};
use futures::future::Either;
pub use hyperswitch_domain_models::customer;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payments::payment_intent::CustomerData;
use hyperswitch_domain_models::{
mandates::MandateData,
payment_method_data::{GetPaymentMethodType, PazeWalletData},
payments::{
self as domain_payments, payment_attempt::PaymentAttempt,
payment_intent::PaymentIntentFetchConstraints, PaymentIntent,
},
router_data::{InteracCustomerInfo, KlarnaSdkResponse, PaymentMethodToken},
};
pub use hyperswitch_interfaces::{
api::ConnectorSpecifications,
configs::MerchantConnectorAccountType,
integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject},
};
use josekit::jwe;
use masking::{ExposeInterface, PeekInterface, SwitchStrategy};
use num_traits::{FromPrimitive, ToPrimitive};
use openssl::{
derive::Deriver,
pkey::PKey,
symm::{decrypt_aead, Cipher},
};
use rand::Rng;
#[cfg(feature = "v2")]
use redis_interface::errors::RedisError;
use router_env::{instrument, logger, tracing};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use x509_parser::parse_x509_certificate;
use super::{
operations::{BoxedOperation, Operation, PaymentResponse},
CustomerDetails, PaymentData,
};
#[cfg(feature = "v1")]
use crate::core::{
payments::{OperationSessionGetters, OperationSessionSetters},
utils as core_utils,
};
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, TempLockerEnableConfig},
connector,
consts::{self, BASE64_ENGINE},
core::{
authentication,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
self,
cards::{self},
network_tokenization, vault,
},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
},
db::StorageInterface,
routes::{metrics, payment_methods as payment_methods_handler, SessionState},
services,
types::{
api::{self, admin, enums as api_enums, MandateValidationFieldsExt},
domain::{self, types},
storage::{self, enums as storage_enums, ephemeral_key, CardTokenData},
transformers::{ForeignFrom, ForeignTryFrom},
AdditionalMerchantData, AdditionalPaymentMethodConnectorResponse, ErrorResponse,
MandateReference, MerchantAccountData, MerchantRecipientData, PaymentsResponseData,
RecipientIdType, RecurringMandatePaymentData, RouterData,
},
utils::{
self,
crypto::{self, SignMessage},
OptionExt, StringExt,
},
};
#[cfg(feature = "v2")]
use crate::{core::admin as core_admin, headers, types::ConnectorAuthType};
#[cfg(feature = "v1")]
use crate::{
core::payment_methods::cards::create_encrypted_data, types::storage::CustomerUpdate::Update,
};
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn create_or_update_address_for_payment_by_request(
session_state: &SessionState,
req_address: Option<&api::Address>,
address_id: Option<&str>,
merchant_id: &id_type::MerchantId,
customer_id: Option<&id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &id_type::PaymentId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
let key = merchant_key_store.key.get_inner().peek();
let db = &session_state.store;
Ok(match address_id {
Some(id) => match req_address {
Some(address) => {
let encrypted_data = types::crypto_operation(
&session_state.into(),
type_name!(domain::Address),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableAddress::to_encryptable(
domain::FromRequestEncryptableAddress {
line1: address.address.as_ref().and_then(|a| a.line1.clone()),
line2: address.address.as_ref().and_then(|a| a.line2.clone()),
line3: address.address.as_ref().and_then(|a| a.line3.clone()),
state: address.address.as_ref().and_then(|a| a.state.clone()),
first_name: address
.address
.as_ref()
.and_then(|a| a.first_name.clone()),
last_name: address
.address
.as_ref()
.and_then(|a| a.last_name.clone()),
zip: address.address.as_ref().and_then(|a| a.zip.clone()),
phone_number: address
.phone
.as_ref()
.and_then(|phone| phone.number.clone()),
email: address
.email
.as_ref()
.map(|a| a.clone().expose().switch_strategy()),
origin_zip: address
.address
.as_ref()
.and_then(|a| a.origin_zip.clone()),
},
),
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address")?;
let encryptable_address =
domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address")?;
let address_update = storage::AddressUpdate::Update {
city: address
.address
.as_ref()
.and_then(|value| value.city.clone()),
country: address.address.as_ref().and_then(|value| value.country),
line1: encryptable_address.line1,
line2: encryptable_address.line2,
line3: encryptable_address.line3,
state: encryptable_address.state,
zip: encryptable_address.zip,
first_name: encryptable_address.first_name,
last_name: encryptable_address.last_name,
phone_number: encryptable_address.phone_number,
country_code: address
.phone
.as_ref()
.and_then(|value| value.country_code.clone()),
updated_by: storage_scheme.to_string(),
email: encryptable_address.email.map(|email| {
let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
origin_zip: encryptable_address.origin_zip,
};
let address = db
.find_address_by_merchant_id_payment_id_address_id(
merchant_id,
payment_id,
id,
merchant_key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while fetching address")?;
Some(
db.update_address_for_payments(
address,
address_update,
payment_id.to_owned(),
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address)
.to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?,
)
}
None => Some(
db.find_address_by_merchant_id_payment_id_address_id(
merchant_id,
payment_id,
id,
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address),
)
.transpose()
.to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?,
},
None => match req_address {
Some(address) => {
let address =
get_domain_address(session_state, address, merchant_id, key, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address while insert")?;
let payment_address = domain::PaymentAddress {
address,
payment_id: payment_id.clone(),
customer_id: customer_id.cloned(),
};
Some(
db.insert_address_for_payments(
payment_id,
payment_address,
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while inserting new address")?,
)
}
None => None,
},
})
}
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn create_or_find_address_for_payment_by_request(
state: &SessionState,
req_address: Option<&api::Address>,
address_id: Option<&str>,
merchant_id: &id_type::MerchantId,
customer_id: Option<&id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &id_type::PaymentId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
let key = merchant_key_store.key.get_inner().peek();
let db = &state.store;
Ok(match address_id {
Some(id) => Some(
db.find_address_by_merchant_id_payment_id_address_id(
merchant_id,
payment_id,
id,
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address),
)
.transpose()
.to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?,
None => match req_address {
Some(address) => {
// generate a new address here
let address = get_domain_address(state, address, merchant_id, key, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address while insert")?;
let payment_address = domain::PaymentAddress {
address,
payment_id: payment_id.clone(),
customer_id: customer_id.cloned(),
};
Some(
db.insert_address_for_payments(
payment_id,
payment_address,
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while inserting new address")?,
)
}
None => None,
},
})
}
pub async fn get_domain_address(
session_state: &SessionState,
address: &api_models::payments::Address,
merchant_id: &id_type::MerchantId,
key: &[u8],
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<domain::Address, common_utils::errors::CryptoError> {
async {
let address_details = &address.address.as_ref();
let encrypted_data = types::crypto_operation(
&session_state.into(),
type_name!(domain::Address),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableAddress::to_encryptable(
domain::FromRequestEncryptableAddress {
line1: address.address.as_ref().and_then(|a| a.line1.clone()),
line2: address.address.as_ref().and_then(|a| a.line2.clone()),
line3: address.address.as_ref().and_then(|a| a.line3.clone()),
state: address.address.as_ref().and_then(|a| a.state.clone()),
first_name: address.address.as_ref().and_then(|a| a.first_name.clone()),
last_name: address.address.as_ref().and_then(|a| a.last_name.clone()),
zip: address.address.as_ref().and_then(|a| a.zip.clone()),
phone_number: address
.phone
.as_ref()
.and_then(|phone| phone.number.clone()),
email: address
.email
.as_ref()
.map(|a| a.clone().expose().switch_strategy()),
origin_zip: address.address.as_ref().and_then(|a| a.origin_zip.clone()),
},
),
),
Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let encryptable_address =
domain::FromRequestEncryptableAddress::from_encryptable(encrypted_data)
.change_context(common_utils::errors::CryptoError::EncodingFailed)?;
Ok(domain::Address {
phone_number: encryptable_address.phone_number,
country_code: address.phone.as_ref().and_then(|a| a.country_code.clone()),
merchant_id: merchant_id.to_owned(),
address_id: generate_id(consts::ID_LENGTH, "add"),
city: address_details.and_then(|address_details| address_details.city.clone()),
country: address_details.and_then(|address_details| address_details.country),
line1: encryptable_address.line1,
line2: encryptable_address.line2,
line3: encryptable_address.line3,
state: encryptable_address.state,
created_at: common_utils::date_time::now(),
first_name: encryptable_address.first_name,
last_name: encryptable_address.last_name,
modified_at: common_utils::date_time::now(),
zip: encryptable_address.zip,
updated_by: storage_scheme.to_string(),
email: encryptable_address.email.map(|email| {
let encryptable: Encryptable<masking::Secret<String, pii::EmailStrategy>> =
Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
origin_zip: encryptable_address.origin_zip,
})
}
.await
}
pub async fn get_address_by_id(
state: &SessionState,
address_id: Option<String>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
match address_id {
None => Ok(None),
Some(address_id) => {
let db = &*state.store;
Ok(db
.find_address_by_merchant_id_payment_id_address_id(
merchant_id,
payment_id,
&address_id,
merchant_key_store,
storage_scheme,
)
.await
.map(|payment_address| payment_address.address)
.ok())
}
}
}
#[cfg(feature = "v1")]
pub async fn get_token_pm_type_mandate_details(
state: &SessionState,
request: &api::PaymentsRequest,
mandate_type: Option<api::MandateTransactionType>,
platform: &domain::Platform,
payment_method_id: Option<String>,
payment_intent_customer_id: Option<&id_type::CustomerId>,
) -> RouterResult<MandateGenericData> {
let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from);
let (
payment_token,
payment_method,
payment_method_type,
mandate_data,
recurring_payment_data,
mandate_connector_details,
payment_method_info,
) = match mandate_type {
Some(api::MandateTransactionType::NewMandateTransaction) => (
request.payment_token.to_owned(),
request.payment_method,
request.payment_method_type,
mandate_data.clone(),
None,
None,
None,
),
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
match &request.recurring_details {
Some(recurring_details) => {
match recurring_details {
RecurringDetails::NetworkTransactionIdAndCardDetails(_) => {
(None, request.payment_method, None, None, None, None, None)
}
RecurringDetails::ProcessorPaymentToken(processor_payment_token) => {
if let Some(mca_id) = &processor_payment_token.merchant_connector_id {
let db = &*state.store;
#[cfg(feature = "v1")]
let connector_name = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
platform.get_processor().get_account().get_id(),
mca_id,
platform.get_processor().get_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: mca_id.clone().get_string_repr().to_string(),
})?.connector_name;
#[cfg(feature = "v2")]
let connector_name = db
.find_merchant_connector_account_by_id( mca_id, merchant_key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: mca_id.clone().get_string_repr().to_string(),
})?.connector_name;
(
None,
request.payment_method,
None,
None,
None,
Some(payments::MandateConnectorDetails {
connector: connector_name,
merchant_connector_id: Some(mca_id.clone()),
}),
None,
)
} else {
(None, request.payment_method, None, None, None, None, None)
}
}
RecurringDetails::MandateId(mandate_id) => {
let mandate_generic_data = Box::pin(get_token_for_recurring_mandate(
state,
request,
platform,
mandate_id.to_owned(),
))
.await?;
(
mandate_generic_data.token,
mandate_generic_data.payment_method,
mandate_generic_data
.payment_method_type
.or(request.payment_method_type),
None,
mandate_generic_data.recurring_mandate_payment_data,
mandate_generic_data.mandate_connector,
mandate_generic_data.payment_method_info,
)
}
RecurringDetails::PaymentMethodId(payment_method_id) => {
let payment_method_info = state
.store
.find_payment_method(
platform.get_processor().get_key_store(),
payment_method_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::PaymentMethodNotFound,
)?;
let customer_id = request
.get_customer_id()
.get_required_value("customer_id")?;
verify_mandate_details_for_recurring_payments(
&payment_method_info.merchant_id,
platform.get_processor().get_account().get_id(),
&payment_method_info.customer_id,
customer_id,
)?;
(
None,
payment_method_info.get_payment_method_type(),
payment_method_info.get_payment_method_subtype(),
None,
None,
None,
Some(payment_method_info),
)
}
RecurringDetails::NetworkTransactionIdAndNetworkTokenDetails(_) => (
None,
request.payment_method,
request.payment_method_type,
None,
None,
None,
None,
),
}
}
None => {
if let Some(mandate_id) = request.mandate_id.clone() {
let mandate_generic_data = Box::pin(get_token_for_recurring_mandate(
state, request, platform, mandate_id,
))
.await?;
(
mandate_generic_data.token,
mandate_generic_data.payment_method,
mandate_generic_data
.payment_method_type
.or(request.payment_method_type),
None,
mandate_generic_data.recurring_mandate_payment_data,
mandate_generic_data.mandate_connector,
mandate_generic_data.payment_method_info,
)
} else if request
.payment_method_type
.map(|payment_method_type_value| {
payment_method_type_value
.should_check_for_customer_saved_payment_method_type()
})
.unwrap_or(false)
{
let payment_request_customer_id = request.get_customer_id();
if let Some(customer_id) =
payment_request_customer_id.or(payment_intent_customer_id)
{
let customer_saved_pm_option = match state
.store
.find_payment_method_by_customer_id_merchant_id_list(
platform.get_processor().get_key_store(),
customer_id,
platform.get_processor().get_account().get_id(),
None,
)
.await
{
Ok(customer_payment_methods) => Ok(customer_payment_methods
.iter()
.find(|payment_method| {
payment_method.get_payment_method_subtype()
== request.payment_method_type
})
.cloned()),
Err(error) => {
if error.current_context().is_db_not_found() {
Ok(None)
} else {
Err(error)
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"failed to find payment methods for a customer",
)
}
}
}?;
(
None,
request.payment_method,
request.payment_method_type,
None,
None,
None,
customer_saved_pm_option,
)
} else {
(
None,
request.payment_method,
request.payment_method_type,
None,
None,
None,
None,
)
}
} else {
let payment_method_info = payment_method_id
.async_map(|payment_method_id| async move {
state
.store
.find_payment_method(
platform.get_processor().get_key_store(),
&payment_method_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::PaymentMethodNotFound,
)
})
.await
.transpose()?;
(
request.payment_token.to_owned(),
request.payment_method,
request.payment_method_type,
None,
None,
None,
payment_method_info,
)
}
}
}
}
None => {
let payment_method_info = payment_method_id
.async_map(|payment_method_id| async move {
state
.store
.find_payment_method(
platform.get_processor().get_key_store(),
&payment_method_id,
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
})
.await
.transpose()?;
(
request.payment_token.to_owned(),
request.payment_method,
request.payment_method_type,
mandate_data,
None,
None,
payment_method_info,
)
}
};
Ok(MandateGenericData {
token: payment_token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data: recurring_payment_data,
mandate_connector: mandate_connector_details,
payment_method_info,
})
}
#[cfg(feature = "v1")]
pub async fn get_token_for_recurring_mandate(
state: &SessionState,
req: &api::PaymentsRequest,
platform: &domain::Platform,
mandate_id: String,
) -> RouterResult<MandateGenericData> {
let db = &*state.store;
let mandate = db
.find_mandate_by_merchant_id_mandate_id(
platform.get_processor().get_account().get_id(),
mandate_id.as_str(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
let original_payment_intent = mandate
.original_payment_id
.as_ref()
.async_map(|payment_id| async {
db.find_payment_intent_by_payment_id_merchant_id(
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/conditional_configs.rs | crates/router/src/core/payments/conditional_configs.rs | use api_models::{conditional_configs::DecisionManagerRecord, routing};
use common_utils::ext_traits::StringExt;
use error_stack::ResultExt;
use euclid::backend::{self, inputs as dsl_inputs, EuclidBackend};
use router_env::{instrument, tracing};
use storage_impl::redis::cache::{self, DECISION_MANAGER_CACHE};
use super::routing::make_dsl_input;
#[cfg(feature = "v2")]
use crate::{core::errors::RouterResult, types::domain};
use crate::{
core::{errors, errors::ConditionalConfigError as ConfigError, routing as core_routing},
routes,
};
pub type ConditionalConfigResult<O> = errors::CustomResult<O, ConfigError>;
#[instrument(skip_all)]
#[cfg(feature = "v1")]
pub async fn perform_decision_management(
state: &routes::SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
merchant_id: &common_utils::id_type::MerchantId,
payment_data: &core_routing::PaymentsDslInput<'_>,
) -> ConditionalConfigResult<common_types::payments::ConditionalConfigs> {
let algorithm_id = if let Some(id) = algorithm_ref.config_algo_id {
id
} else {
return Ok(common_types::payments::ConditionalConfigs::default());
};
let db = &*state.store;
let key = merchant_id.get_dsl_config();
let find_key_from_db = || async {
let config = db.find_config_by_key(&algorithm_id).await?;
let rec: DecisionManagerRecord = config
.config
.parse_struct("Program")
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Error parsing routing algorithm from configs")?;
backend::VirInterpreterBackend::with_program(rec.program)
.change_context(errors::StorageError::ValueNotFound("Program".to_string()))
.attach_printable("Error initializing DSL interpreter backend")
};
let interpreter = cache::get_or_populate_in_memory(
db.get_cache_store().as_ref(),
&key,
find_key_from_db,
&DECISION_MANAGER_CACHE,
)
.await
.change_context(ConfigError::DslCachePoisoned)?;
let backend_input =
make_dsl_input(payment_data).change_context(ConfigError::InputConstructionError)?;
execute_dsl_and_get_conditional_config(backend_input, &interpreter)
}
#[cfg(feature = "v2")]
pub fn perform_decision_management(
record: common_types::payments::DecisionManagerRecord,
payment_data: &core_routing::PaymentsDslInput<'_>,
) -> RouterResult<common_types::payments::ConditionalConfigs> {
let interpreter = backend::VirInterpreterBackend::with_program(record.program)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error initializing DSL interpreter backend")?;
let backend_input = make_dsl_input(payment_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error constructing DSL input")?;
execute_dsl_and_get_conditional_config(backend_input, &interpreter)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error executing DSL")
}
pub fn execute_dsl_and_get_conditional_config(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<common_types::payments::ConditionalConfigs>,
) -> ConditionalConfigResult<common_types::payments::ConditionalConfigs> {
let routing_output = interpreter
.execute(backend_input)
.map(|out| out.connector_selection)
.change_context(ConfigError::DslExecutionError)?;
Ok(routing_output)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows.rs | crates/router/src/core/payments/flows.rs | pub mod approve_flow;
pub mod authorize_flow;
pub mod cancel_flow;
pub mod cancel_post_capture_flow;
pub mod capture_flow;
pub mod complete_authorize_flow;
pub mod extend_authorization_flow;
#[cfg(feature = "v2")]
pub mod external_proxy_flow;
pub mod incremental_authorization_flow;
pub mod post_session_tokens_flow;
pub mod psync_flow;
pub mod reject_flow;
pub mod session_flow;
pub mod session_update_flow;
pub mod setup_mandate_flow;
pub mod update_metadata_flow;
use async_trait::async_trait;
use common_enums;
use common_types::payments::CustomerAcceptance;
#[cfg(feature = "v2")]
use external_services::grpc_client;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use hyperswitch_domain_models::router_flow_types::{
BillingConnectorInvoiceSync, BillingConnectorPaymentsSync, InvoiceRecordBack,
};
use hyperswitch_domain_models::{
payments as domain_payments, router_request_types::PaymentsCaptureData,
};
use crate::{
core::{
errors::{ApiErrorResponse, RouterResult},
payments::{self, gateway::context as gateway_context, helpers},
},
logger,
routes::SessionState,
services, types as router_types,
types::{self, api, api::enums as api_enums, domain},
};
#[async_trait]
#[allow(clippy::too_many_arguments)]
pub trait ConstructFlowSpecificData<F, Req, Res> {
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::RouterData<F, Req, Res>>;
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_platform: &domain::Platform,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<types::RouterData<F, Req, Res>>;
async fn get_merchant_recipient_data<'a>(
&self,
_state: &SessionState,
_platform: &domain::Platform,
_merchant_connector_account: &helpers::MerchantConnectorAccountType,
_connector: &api::ConnectorData,
) -> RouterResult<Option<types::MerchantRecipientData>> {
Ok(None)
}
}
#[allow(clippy::too_many_arguments)]
#[async_trait]
pub trait Feature<F, T> {
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
gateway_context: gateway_context::RouterGatewayContext,
) -> RouterResult<Self>
where
Self: Sized,
F: Clone,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>;
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>;
async fn add_session_token<'a>(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<()>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(())
}
async fn add_payment_method_token<'a>(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_tokenization_action: &payments::TokenizationAction,
_should_continue_payment: bool,
_gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::PaymentMethodTokenResult>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
})
}
async fn pre_authentication_step<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<(Self, bool)>
where
F: Clone,
Self: Sized,
{
Ok((self, true))
}
async fn authentication_step<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<(Self, bool)>
where
F: Clone,
Self: Sized,
{
Ok((self, true))
}
async fn post_authentication_step<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<(Self, bool)>
where
F: Clone,
Self: Sized,
{
Ok((self, true))
}
async fn preprocessing_steps<'a>(
self,
_state: &SessionState,
_connector_data: &api::ConnectorData,
) -> RouterResult<Self>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(self)
}
async fn postprocessing_steps<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
) -> RouterResult<Self>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(self)
}
async fn create_connector_customer<'a>(
&self,
_state: &SessionState,
_connector: &api::ConnectorData,
_gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<String>>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(None)
}
/// Returns the connector request and a bool which specifies whether to proceed with further
async fn build_flow_specific_connector_request(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
Ok((None, true))
}
async fn create_order_at_connector(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_should_continue_payment: bool,
_gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<types::CreateOrderResult>>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(None)
}
fn update_router_data_with_create_order_response(
&mut self,
_create_order_result: types::CreateOrderResult,
) {
}
#[cfg(feature = "v2")]
async fn call_unified_connector_service_with_external_vault_proxy<'a>(
&mut self,
_state: &SessionState,
_header_payload: &domain_payments::HeaderPayload,
_lineage_ids: grpc_client::LineageIds,
_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
_external_vault_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
_platform: &domain::Platform,
_unified_connector_service_execution_mode: common_enums::ExecutionMode,
_merchant_order_reference_id: Option<String>,
) -> RouterResult<()>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(())
}
}
/// Determines whether a capture API call should be made for a payment attempt
/// This function evaluates whether an authorized payment should proceed with a capture API call
/// based on various payment parameters. It's primarily used in two-step (auth + capture) payment flows for CaptureMethod SequentialAutomatic
///
pub fn should_initiate_capture_flow(
connector_name: &router_types::Connector,
customer_acceptance: Option<CustomerAcceptance>,
capture_method: Option<api_enums::CaptureMethod>,
setup_future_usage: Option<api_enums::FutureUsage>,
status: common_enums::AttemptStatus,
) -> bool {
match status {
common_enums::AttemptStatus::Authorized => {
if let Some(api_enums::CaptureMethod::SequentialAutomatic) = capture_method {
match connector_name {
router_types::Connector::Paybox => {
// Check CIT conditions for Paybox
setup_future_usage == Some(api_enums::FutureUsage::OffSession)
&& customer_acceptance.is_some()
}
_ => false,
}
} else {
false
}
}
_ => false,
}
}
/// Executes a capture request by building a connector-specific request and deciding
/// the appropriate flow to send it to the payment connector.
pub async fn call_capture_request(
mut capture_router_data: types::RouterData<
api::Capture,
PaymentsCaptureData,
types::PaymentsResponseData,
>,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
context: gateway_context::RouterGatewayContext,
) -> RouterResult<types::RouterData<api::Capture, PaymentsCaptureData, types::PaymentsResponseData>>
{
// Build capture-specific connector request
let (connector_request, _should_continue_further) = capture_router_data
.build_flow_specific_connector_request(state, connector, call_connector_action.clone())
.await?;
// Execute capture flow
capture_router_data
.decide_flows(
state,
connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
None,
context, // gateway_context
)
.await
}
/// Processes the response from the capture flow and determines the final status and the response.
fn handle_post_capture_response(
authorize_router_data_response: types::PaymentsResponseData,
post_capture_router_data: Result<
types::RouterData<api::Capture, PaymentsCaptureData, types::PaymentsResponseData>,
error_stack::Report<ApiErrorResponse>,
>,
) -> RouterResult<(common_enums::AttemptStatus, types::PaymentsResponseData)> {
match post_capture_router_data {
Err(err) => {
logger::error!(
"Capture flow encountered an error: {:?}. Proceeding without updating.",
err
);
Ok((
common_enums::AttemptStatus::Authorized,
authorize_router_data_response,
))
}
Ok(post_capture_router_data) => {
match (
&post_capture_router_data.response,
post_capture_router_data.status,
) {
(Ok(post_capture_resp), common_enums::AttemptStatus::Charged) => Ok((
common_enums::AttemptStatus::Charged,
types::PaymentsResponseData::merge_transaction_responses(
&authorize_router_data_response,
post_capture_resp,
)?,
)),
_ => {
logger::error!(
"Error in post capture_router_data response: {:?}, Current Status: {:?}. Proceeding without updating.",
post_capture_router_data.response,
post_capture_router_data.status,
);
Ok((
common_enums::AttemptStatus::Authorized,
authorize_router_data_response,
))
}
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/types.rs | crates/router/src/core/payments/types.rs | use std::{collections::HashMap, num::TryFromIntError};
use api_models::payment_methods::SurchargeDetailsResponse;
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, OptionExt},
types::{self as common_types, ConnectorTransactionIdTrait},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
pub use hyperswitch_domain_models::router_request_types::{
self, AuthenticationData, SplitRefundsRequest, StripeSplitRefund, SurchargeDetails,
};
use redis_interface::errors::RedisError;
use router_env::{instrument, logger, tracing};
use crate::{
consts as router_consts,
core::errors::{self, RouterResult},
routes::SessionState,
types::{
domain::Profile,
storage::{self, enums as storage_enums},
transformers::ForeignTryFrom,
},
};
#[derive(Clone, Debug)]
pub struct MultipleCaptureData {
// key -> capture_id, value -> Capture
all_captures: HashMap<String, storage::Capture>,
latest_capture: storage::Capture,
pub expand_captures: Option<bool>,
_private: Private, // to restrict direct construction of MultipleCaptureData
}
#[derive(Clone, Debug)]
struct Private {}
impl MultipleCaptureData {
pub fn new_for_sync(
captures: Vec<storage::Capture>,
expand_captures: Option<bool>,
) -> RouterResult<Self> {
let latest_capture = captures
.last()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Cannot create MultipleCaptureData with empty captures list")?
.clone();
let multiple_capture_data = Self {
all_captures: captures
.into_iter()
.map(|capture| (capture.capture_id.clone(), capture))
.collect(),
latest_capture,
_private: Private {},
expand_captures,
};
Ok(multiple_capture_data)
}
pub fn new_for_create(
mut previous_captures: Vec<storage::Capture>,
new_capture: storage::Capture,
) -> Self {
previous_captures.push(new_capture.clone());
Self {
all_captures: previous_captures
.into_iter()
.map(|capture| (capture.capture_id.clone(), capture))
.collect(),
latest_capture: new_capture,
_private: Private {},
expand_captures: None,
}
}
pub fn update_capture(&mut self, updated_capture: storage::Capture) {
let capture_id = &updated_capture.capture_id;
if self.all_captures.contains_key(capture_id) {
self.all_captures
.entry(capture_id.into())
.and_modify(|capture| *capture = updated_capture.clone());
}
}
pub fn get_total_blocked_amount(&self) -> common_types::MinorUnit {
self.all_captures
.iter()
.fold(common_types::MinorUnit::new(0), |accumulator, capture| {
accumulator
+ match capture.1.status {
storage_enums::CaptureStatus::Charged
| storage_enums::CaptureStatus::Pending => capture.1.amount,
storage_enums::CaptureStatus::Started
| storage_enums::CaptureStatus::Failed => common_types::MinorUnit::new(0),
}
})
}
pub fn get_total_charged_amount(&self) -> common_types::MinorUnit {
self.all_captures
.iter()
.fold(common_types::MinorUnit::new(0), |accumulator, capture| {
accumulator
+ match capture.1.status {
storage_enums::CaptureStatus::Charged => capture.1.amount,
storage_enums::CaptureStatus::Pending
| storage_enums::CaptureStatus::Started
| storage_enums::CaptureStatus::Failed => common_types::MinorUnit::new(0),
}
})
}
pub fn get_captures_count(&self) -> RouterResult<i16> {
i16::try_from(self.all_captures.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while converting from usize to i16")
}
pub fn get_status_count(&self) -> HashMap<storage_enums::CaptureStatus, i16> {
let mut hash_map: HashMap<storage_enums::CaptureStatus, i16> = HashMap::new();
hash_map.insert(storage_enums::CaptureStatus::Charged, 0);
hash_map.insert(storage_enums::CaptureStatus::Pending, 0);
hash_map.insert(storage_enums::CaptureStatus::Started, 0);
hash_map.insert(storage_enums::CaptureStatus::Failed, 0);
self.all_captures
.iter()
.fold(hash_map, |mut accumulator, capture| {
let current_capture_status = capture.1.status;
accumulator
.entry(current_capture_status)
.and_modify(|count| *count += 1);
accumulator
})
}
pub fn get_attempt_status(
&self,
authorized_amount: common_types::MinorUnit,
) -> storage_enums::AttemptStatus {
let total_captured_amount = self.get_total_charged_amount();
if authorized_amount == total_captured_amount {
return storage_enums::AttemptStatus::Charged;
}
let status_count_map = self.get_status_count();
if status_count_map.get(&storage_enums::CaptureStatus::Charged) > Some(&0) {
storage_enums::AttemptStatus::PartialChargedAndChargeable
} else {
storage_enums::AttemptStatus::CaptureInitiated
}
}
pub fn get_pending_captures(&self) -> Vec<&storage::Capture> {
self.all_captures
.iter()
.filter(|capture| capture.1.status == storage_enums::CaptureStatus::Pending)
.map(|key_value| key_value.1)
.collect()
}
pub fn get_all_captures(&self) -> Vec<&storage::Capture> {
self.all_captures
.iter()
.map(|key_value| key_value.1)
.collect()
}
pub fn get_capture_by_capture_id(&self, capture_id: String) -> Option<&storage::Capture> {
self.all_captures.get(&capture_id)
}
pub fn get_capture_by_connector_capture_id(
&self,
connector_capture_id: &String,
) -> Option<&storage::Capture> {
self.all_captures
.iter()
.find(|(_, capture)| {
capture.get_optional_connector_transaction_id() == Some(connector_capture_id)
})
.map(|(_, capture)| capture)
}
pub fn get_latest_capture(&self) -> &storage::Capture {
&self.latest_capture
}
pub fn get_pending_connector_capture_ids(&self) -> Vec<String> {
let pending_connector_capture_ids = self
.get_pending_captures()
.into_iter()
.filter_map(|capture| capture.get_optional_connector_transaction_id().cloned())
.collect();
pending_connector_capture_ids
}
pub fn get_pending_captures_without_connector_capture_id(&self) -> Vec<&storage::Capture> {
self.get_pending_captures()
.into_iter()
.filter(|capture| capture.get_optional_connector_transaction_id().is_none())
.collect()
}
}
#[cfg(feature = "v2")]
impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsResponse {
type Error = TryFromIntError;
fn foreign_try_from(
(surcharge_details, payment_attempt): (&SurchargeDetails, &PaymentAttempt),
) -> Result<Self, Self::Error> {
todo!()
}
}
#[cfg(feature = "v1")]
impl ForeignTryFrom<(&SurchargeDetails, &PaymentAttempt)> for SurchargeDetailsResponse {
type Error = TryFromIntError;
fn foreign_try_from(
(surcharge_details, payment_attempt): (&SurchargeDetails, &PaymentAttempt),
) -> Result<Self, Self::Error> {
let currency = payment_attempt.currency.unwrap_or_default();
let display_surcharge_amount = currency
.to_currency_base_unit_asf64(surcharge_details.surcharge_amount.get_amount_as_i64())?;
let display_tax_on_surcharge_amount = currency.to_currency_base_unit_asf64(
surcharge_details
.tax_on_surcharge_amount
.get_amount_as_i64(),
)?;
let display_total_surcharge_amount = currency.to_currency_base_unit_asf64(
(surcharge_details.surcharge_amount + surcharge_details.tax_on_surcharge_amount)
.get_amount_as_i64(),
)?;
Ok(Self {
surcharge: surcharge_details.surcharge.clone().into(),
tax_on_surcharge: surcharge_details.tax_on_surcharge.clone().map(Into::into),
display_surcharge_amount,
display_tax_on_surcharge_amount,
display_total_surcharge_amount,
})
}
}
#[derive(Eq, Hash, PartialEq, Clone, Debug, strum::Display)]
pub enum SurchargeKey {
Token(String),
PaymentMethodData(
common_enums::PaymentMethod,
common_enums::PaymentMethodType,
Option<common_enums::CardNetwork>,
),
}
#[derive(Clone, Debug)]
pub struct SurchargeMetadata {
surcharge_results: HashMap<SurchargeKey, SurchargeDetails>,
pub payment_attempt_id: String,
}
impl SurchargeMetadata {
pub fn new(payment_attempt_id: String) -> Self {
Self {
surcharge_results: HashMap::new(),
payment_attempt_id,
}
}
pub fn is_empty_result(&self) -> bool {
self.surcharge_results.is_empty()
}
pub fn get_surcharge_results_size(&self) -> usize {
self.surcharge_results.len()
}
pub fn insert_surcharge_details(
&mut self,
surcharge_key: SurchargeKey,
surcharge_details: SurchargeDetails,
) {
self.surcharge_results
.insert(surcharge_key, surcharge_details);
}
pub fn get_surcharge_details(&self, surcharge_key: SurchargeKey) -> Option<&SurchargeDetails> {
self.surcharge_results.get(&surcharge_key)
}
pub fn get_surcharge_metadata_redis_key(payment_attempt_id: &str) -> String {
format!("surcharge_metadata_{payment_attempt_id}")
}
pub fn get_individual_surcharge_key_value_pairs(&self) -> Vec<(String, SurchargeDetails)> {
self.surcharge_results
.iter()
.map(|(surcharge_key, surcharge_details)| {
let key = Self::get_surcharge_details_redis_hashset_key(surcharge_key);
(key, surcharge_details.to_owned())
})
.collect()
}
pub fn get_surcharge_details_redis_hashset_key(surcharge_key: &SurchargeKey) -> String {
match surcharge_key {
SurchargeKey::Token(token) => {
format!("token_{token}")
}
SurchargeKey::PaymentMethodData(payment_method, payment_method_type, card_network) => {
if let Some(card_network) = card_network {
format!("{payment_method}_{payment_method_type}_{card_network}")
} else {
format!("{payment_method}_{payment_method_type}")
}
}
}
}
#[instrument(skip_all)]
pub async fn persist_individual_surcharge_details_in_redis(
&self,
state: &SessionState,
business_profile: &Profile,
) -> RouterResult<()> {
if !self.is_empty_result() {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let redis_key = Self::get_surcharge_metadata_redis_key(&self.payment_attempt_id);
let mut value_list = Vec::with_capacity(self.get_surcharge_results_size());
for (key, value) in self.get_individual_surcharge_key_value_pairs().into_iter() {
value_list.push((
key,
value
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode to string of json")?,
));
}
let intent_fulfillment_time = business_profile
.get_order_fulfillment_time()
.unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME);
redis_conn
.set_hash_fields(
&redis_key.as_str().into(),
value_list,
Some(intent_fulfillment_time),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to write to redis")?;
logger::debug!("Surcharge results stored in redis with key = {}", redis_key);
}
Ok(())
}
#[instrument(skip_all)]
pub async fn get_individual_surcharge_detail_from_redis(
state: &SessionState,
surcharge_key: SurchargeKey,
payment_attempt_id: &str,
) -> CustomResult<SurchargeDetails, RedisError> {
let redis_conn = state
.store
.get_redis_conn()
.attach_printable("Failed to get redis connection")?;
let redis_key = Self::get_surcharge_metadata_redis_key(payment_attempt_id);
let value_key = Self::get_surcharge_details_redis_hashset_key(&surcharge_key);
let result = redis_conn
.get_hash_field_and_deserialize(
&redis_key.as_str().into(),
&value_key,
"SurchargeDetails",
)
.await;
logger::debug!(
"Surcharge result fetched from redis with key = {} and {}",
redis_key,
value_key
);
result
}
}
impl ForeignTryFrom<&router_request_types::authentication::AuthenticationStore>
for router_request_types::UcsAuthenticationData
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
authentication_store: &router_request_types::authentication::AuthenticationStore,
) -> Result<Self, Self::Error> {
let authentication = &authentication_store.authentication;
if authentication.authentication_status == common_enums::AuthenticationStatus::Success {
let threeds_server_transaction_id =
authentication.threeds_server_transaction_id.clone();
let message_version = authentication.message_version.clone();
let cavv = authentication_store
.cavv
.clone()
.get_required_value("cavv")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("cavv must not be null when authentication_status is success")?;
Ok(Self {
trans_status: authentication.trans_status.clone(),
eci: authentication.eci.clone(),
cavv: Some(cavv),
threeds_server_transaction_id,
message_version,
ds_trans_id: authentication.ds_trans_id.clone(),
acs_trans_id: authentication.acs_trans_id.clone(),
transaction_id: authentication.connector_authentication_id.clone(),
ucaf_collection_indicator: None,
})
} else {
Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into())
}
}
}
impl ForeignTryFrom<&router_request_types::authentication::AuthenticationStore>
for AuthenticationData
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
authentication_store: &router_request_types::authentication::AuthenticationStore,
) -> Result<Self, Self::Error> {
let authentication = &authentication_store.authentication;
if authentication.authentication_status == common_enums::AuthenticationStatus::Success {
let threeds_server_transaction_id =
authentication.threeds_server_transaction_id.clone();
let message_version = authentication.message_version.clone();
let cavv = authentication_store
.cavv
.clone()
.get_required_value("cavv")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("cavv must not be null when authentication_status is success")?;
Ok(Self {
eci: authentication.eci.clone(),
created_at: authentication.created_at,
cavv,
threeds_server_transaction_id,
message_version,
ds_trans_id: authentication.ds_trans_id.clone(),
authentication_type: authentication.authentication_type,
challenge_code: authentication.challenge_code.clone(),
challenge_cancel: authentication.challenge_cancel.clone(),
challenge_code_reason: authentication.challenge_code_reason.clone(),
message_extension: authentication.message_extension.clone(),
acs_trans_id: authentication.acs_trans_id.clone(),
transaction_status: authentication.trans_status.clone(),
exemption_indicator: None,
cb_network_params: None,
})
} else {
Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into())
}
}
}
impl ForeignTryFrom<&api_models::payments::ExternalThreeDsData> for AuthenticationData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
external_auth_data: &api_models::payments::ExternalThreeDsData,
) -> Result<Self, Self::Error> {
let cavv = match &external_auth_data.authentication_cryptogram {
api_models::payments::Cryptogram::Cavv {
authentication_cryptogram,
} => authentication_cryptogram.clone(),
};
Ok(Self {
eci: Some(external_auth_data.eci.clone()),
cavv,
threeds_server_transaction_id: Some(external_auth_data.ds_trans_id.clone()),
message_version: Some(external_auth_data.version.clone()),
ds_trans_id: Some(external_auth_data.ds_trans_id.clone()),
created_at: time::PrimitiveDateTime::new(
time::OffsetDateTime::now_utc().date(),
time::OffsetDateTime::now_utc().time(),
),
challenge_code: None,
challenge_cancel: None,
challenge_code_reason: None,
message_extension: None,
acs_trans_id: None,
authentication_type: None,
transaction_status: Some(external_auth_data.transaction_status.clone()),
exemption_indicator: external_auth_data.exemption_indicator.clone(),
cb_network_params: external_auth_data.network_params.clone(),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/gateway.rs | crates/router/src/core/payments/gateway.rs | pub mod access_token_gateway;
pub mod authenticate_gateway;
pub mod authorize_gateway;
pub mod cancel_gateway;
pub mod capture_gateway;
pub mod complete_authorize_gateway;
pub mod context;
pub mod create_customer_gateway;
pub mod create_order_gateway;
pub mod payment_method_token_create_gateway;
pub mod post_authenticate_gateway;
pub mod pre_authenticate_gateway;
pub mod psync_gateway;
pub mod session_gateway;
pub mod session_token_gateway;
pub mod setup_mandate;
use std::sync;
use common_enums;
use hyperswitch_domain_models::{router_data_v2::PaymentFlowData, router_flow_types::payments};
use hyperswitch_interfaces::{
api::{gateway, Connector, ConnectorIntegration},
connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},
};
use crate::{
core::{errors::utils::ConnectorErrorExt, payments::gateway::context as gateway_context},
errors::RouterResult,
services, types,
types::api,
SessionState,
};
pub static GRANULAR_GATEWAY_SUPPORTED_FLOWS: sync::LazyLock<Vec<&'static str>> =
sync::LazyLock::new(|| {
vec![
std::any::type_name::<payments::PSync>(),
std::any::type_name::<payments::Authorize>(),
std::any::type_name::<payments::CompleteAuthorize>(),
std::any::type_name::<payments::SetupMandate>(),
]
});
pub async fn handle_gateway_call<Flow, Req, Resp, ResourceCommonData, FlowOutput>(
state: &SessionState,
router_data: types::RouterData<Flow, Req, Resp>,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<FlowOutput>
where
Flow: gateway::FlowGateway<
SessionState,
PaymentFlowData,
Req,
Resp,
gateway_context::RouterGatewayContext,
FlowOutput,
>,
FlowOutput: Clone + Send + Sync + gateway::GetRouterData<Flow, Req, Resp> + 'static,
Req: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,
Resp: std::fmt::Debug + Clone + Send + Sync + serde::Serialize + 'static,
dyn Connector + Sync: ConnectorIntegration<Flow, Req, Resp>,
dyn ConnectorV2 + Sync: ConnectorIntegrationV2<Flow, PaymentFlowData, Req, Resp>,
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
Flow,
Req,
Resp,
> = connector.connector.get_connector_integration();
// TODO: Handle gateway_context later
let resp = gateway::execute_payment_gateway(
state,
connector_integration,
&router_data,
common_enums::CallConnectorAction::Trigger,
None,
None,
gateway_context.clone(),
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/operations.rs | crates/router/src/core/payments/operations.rs | #[cfg(feature = "v1")]
pub mod payment_approve;
#[cfg(feature = "v1")]
pub mod payment_cancel;
#[cfg(feature = "v1")]
pub mod payment_cancel_post_capture;
#[cfg(feature = "v1")]
pub mod payment_capture;
#[cfg(feature = "v1")]
pub mod payment_complete_authorize;
#[cfg(feature = "v1")]
pub mod payment_confirm;
#[cfg(feature = "v1")]
pub mod payment_create;
#[cfg(feature = "v1")]
pub mod payment_post_session_tokens;
#[cfg(feature = "v1")]
pub mod payment_reject;
pub mod payment_response;
#[cfg(feature = "v1")]
pub mod payment_session;
#[cfg(feature = "v2")]
pub mod payment_session_intent;
#[cfg(feature = "v1")]
pub mod payment_start;
#[cfg(feature = "v1")]
pub mod payment_status;
#[cfg(feature = "v1")]
pub mod payment_update;
#[cfg(feature = "v1")]
pub mod payment_update_metadata;
#[cfg(feature = "v1")]
pub mod payments_extend_authorization;
#[cfg(feature = "v1")]
pub mod payments_incremental_authorization;
#[cfg(feature = "v1")]
pub mod tax_calculation;
#[cfg(feature = "v2")]
pub mod payment_attempt_list;
#[cfg(feature = "v2")]
pub mod payment_attempt_record;
#[cfg(feature = "v2")]
pub mod payment_confirm_intent;
#[cfg(feature = "v2")]
pub mod payment_create_intent;
#[cfg(feature = "v2")]
pub mod payment_get_intent;
#[cfg(feature = "v2")]
pub mod payment_update_intent;
#[cfg(feature = "v2")]
pub mod proxy_payments_intent;
#[cfg(feature = "v2")]
pub mod external_vault_proxy_payment_intent;
#[cfg(feature = "v2")]
pub mod payment_get;
#[cfg(feature = "v2")]
pub mod payment_capture_v2;
#[cfg(feature = "v2")]
pub mod payment_cancel_v2;
use api_models::enums::FrmSuggestion;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use api_models::routing::RoutableConnectorChoice;
use async_trait::async_trait;
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
#[cfg(feature = "v2")]
pub use self::payment_attempt_list::PaymentGetListAttempts;
#[cfg(feature = "v2")]
pub use self::payment_get::PaymentGet;
#[cfg(feature = "v2")]
pub use self::payment_get_intent::PaymentGetIntent;
pub use self::payment_response::PaymentResponse;
#[cfg(feature = "v2")]
pub use self::payment_update_intent::PaymentUpdateIntent;
#[cfg(feature = "v1")]
pub use self::{
payment_approve::PaymentApprove, payment_cancel::PaymentCancel,
payment_cancel_post_capture::PaymentCancelPostCapture, payment_capture::PaymentCapture,
payment_confirm::PaymentConfirm, payment_create::PaymentCreate,
payment_post_session_tokens::PaymentPostSessionTokens, payment_reject::PaymentReject,
payment_session::PaymentSession, payment_start::PaymentStart, payment_status::PaymentStatus,
payment_update::PaymentUpdate, payment_update_metadata::PaymentUpdateMetadata,
payments_extend_authorization::PaymentExtendAuthorization,
payments_incremental_authorization::PaymentIncrementalAuthorization,
tax_calculation::PaymentSessionUpdate,
};
#[cfg(feature = "v2")]
pub use self::{
payment_confirm_intent::PaymentIntentConfirm, payment_create_intent::PaymentIntentCreate,
payment_session_intent::PaymentSessionIntent,
};
use super::{helpers, CustomerDetails, OperationSessionGetters, OperationSessionSetters};
#[cfg(feature = "v2")]
use crate::core::payments;
use crate::{
core::errors::{self, CustomResult, RouterResult},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType},
domain,
storage::{self, enums},
PaymentsResponseData,
},
};
pub type BoxedOperation<'a, F, T, D> = Box<dyn Operation<F, T, Data = D> + Send + Sync + 'a>;
pub trait Operation<F: Clone, T>: Send + std::fmt::Debug {
type Data;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, T, Self::Data> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("validate request interface not found for {self:?}"))
}
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, T> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, T, Self::Data>> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("domain interface not found for {self:?}"))
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, T> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("update tracker interface not found for {self:?}"))
}
fn to_post_update_tracker(
&self,
) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, T> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError)).attach_printable_lazy(|| {
format!("post connector update tracker not found for {self:?}")
})
}
}
#[cfg(feature = "v1")]
#[derive(Clone)]
pub struct ValidateResult {
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: api::PaymentIdType,
pub storage_scheme: enums::MerchantStorageScheme,
pub requeue: bool,
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct ValidateResult {
pub merchant_id: common_utils::id_type::MerchantId,
pub storage_scheme: enums::MerchantStorageScheme,
pub requeue: bool,
}
#[cfg(feature = "v1")]
#[allow(clippy::type_complexity)]
pub trait ValidateRequest<F, R, D> {
fn validate_request<'b>(
&'b self,
request: &R,
platform: &domain::Processor,
) -> RouterResult<(BoxedOperation<'b, F, R, D>, ValidateResult)>;
}
#[cfg(feature = "v2")]
pub trait ValidateRequest<F, R, D> {
fn validate_request(
&self,
request: &R,
platform: &domain::Platform,
) -> RouterResult<ValidateResult>;
}
#[cfg(feature = "v2")]
pub struct GetTrackerResponse<D> {
pub payment_data: D,
}
#[cfg(feature = "v1")]
pub struct GetTrackerResponse<'a, F: Clone, R, D> {
pub operation: BoxedOperation<'a, F, R, D>,
pub customer_details: Option<CustomerDetails>,
pub payment_data: D,
pub business_profile: domain::Profile,
pub mandate_type: Option<api::MandateTransactionType>,
}
/// This trait is used to fetch / create all the tracker related information for a payment
/// This functions returns the session data that is used by subsequent functions
#[async_trait]
pub trait GetTracker<F: Clone, D, R>: Send {
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &R,
platform: &domain::Platform,
auth_flow: services::AuthFlow,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<GetTrackerResponse<'a, F, R, D>>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &R,
platform: &domain::Platform,
profile: &domain::Profile,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<GetTrackerResponse<D>>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn get_trackers_for_split_payments<'a>(
&'a self,
_state: &'a SessionState,
_payment_id: &common_utils::id_type::GlobalPaymentId,
_request: &R,
_merchant_context: &domain::Platform,
_profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
_pm_split_amount_data: domain::PaymentMethodDetailsWithSplitAmount,
_attempts_group_id: &common_utils::id_type::GlobalAttemptGroupId,
) -> RouterResult<GetTrackerResponse<D>> {
Err(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Default,
})?
}
async fn validate_request_with_state(
&self,
_state: &SessionState,
_request: &R,
_payment_data: &mut D,
_business_profile: &domain::Profile,
) -> RouterResult<()> {
Ok(())
}
}
#[async_trait]
pub trait Domain<F: Clone, R, D>: Send + Sync {
#[cfg(feature = "v1")]
/// This will populate raw customer details in payment intent (processor context)
async fn populate_raw_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
request: Option<&CustomerDetails>,
processor: &domain::Processor,
) -> CustomResult<(), errors::StorageError>;
#[cfg(feature = "v1")]
/// This will fetch customer details, (this operation is flow specific)
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
request: Option<CustomerDetails>,
provider: &domain::Provider,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>;
#[cfg(feature = "v2")]
/// This will fetch customer details, (this operation is flow specific)
async fn get_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>;
/// Update customer information at provider level
/// This handles connector_customer_id updates in the Customer table
async fn update_customer<'a>(
&'a self,
_db: &'a SessionState,
_provider: &domain::Provider,
_customer: Option<domain::Customer>,
_updated_customer: Option<storage::CustomerUpdate>,
) -> RouterResult<()> {
Ok(())
}
#[cfg(feature = "v2")]
/// This will run the decision manager for the payment
async fn run_decision_manager<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut D,
storage_scheme: enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
BoxedOperation<'a, F, R, D>,
Option<domain::PaymentMethodData>,
Option<String>,
)>;
async fn add_task_to_process_tracker<'a>(
&'a self,
_db: &'a SessionState,
_payment_attempt: &storage::PaymentAttempt,
_requeue: bool,
_schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
#[cfg(feature = "v1")]
async fn get_connector<'a>(
&'a self,
platform: &domain::Platform,
state: &SessionState,
request: &R,
payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse>;
#[cfg(feature = "v2")]
async fn get_connector_from_request<'a>(
&'a self,
state: &SessionState,
request: &R,
payment_data: &mut D,
) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| "get connector for tunnel not implemented".to_string())
}
#[cfg(feature = "v2")]
async fn perform_routing<'a>(
&'a self,
platform: &domain::Platform,
business_profile: &domain::Profile,
state: &SessionState,
// TODO: do not take the whole payment data here
payment_data: &mut D,
) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse>;
async fn populate_payment_data<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_platform: &domain::Platform,
_business_profile: &domain::Profile,
_connector_data: &api::ConnectorData,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn call_external_three_ds_authentication_if_eligible<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_should_continue_confirm_transaction: &mut bool,
_connector_call_type: &ConnectorCallType,
_business_profile: &domain::Profile,
_key_store: &domain::MerchantKeyStore,
_mandate_type: Option<api_models::payments::MandateTransactionType>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn call_unified_authentication_service_if_eligible<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_should_continue_confirm_transaction: &mut bool,
_connector_call_type: &ConnectorCallType,
_business_profile: &domain::Profile,
_key_store: &domain::MerchantKeyStore,
_mandate_type: Option<api_models::payments::MandateTransactionType>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_connector_call_type: &ConnectorCallType,
_business_profile: &domain::Profile,
_platform: &domain::Platform,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_platform: &domain::Platform,
_payment_data: &mut D,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
async fn store_extended_card_info_temporarily<'a>(
&'a self,
_state: &SessionState,
_payment_id: &common_utils::id_type::PaymentId,
_business_profile: &domain::Profile,
_payment_method_data: Option<&domain::PaymentMethodData>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
#[cfg(feature = "v2")]
async fn create_or_fetch_payment_method<'a>(
&'a self,
state: &SessionState,
platform: &domain::Platform,
business_profile: &domain::Profile,
payment_data: &mut D,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
// does not propagate error to not affect the payment flow
// must add debugger in case of internal error
#[cfg(feature = "v2")]
async fn update_payment_method<'a>(
&'a self,
state: &SessionState,
platform: &domain::Platform,
payment_data: &mut D,
) {
}
/// This function is used to apply the 3DS authentication strategy
async fn apply_three_ds_authentication_strategy<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_business_profile: &domain::Profile,
) {
}
/// Get connector tokenization action
#[cfg(feature = "v2")]
async fn get_connector_tokenization_action<'a>(
&'a self,
_state: &SessionState,
_payment_data: &D,
) -> RouterResult<(payments::TokenizationAction)> {
Ok(payments::TokenizationAction::SkipConnectorTokenization)
}
// #[cfg(feature = "v2")]
// async fn call_connector<'a, RouterDataReq>(
// &'a self,
// _state: &SessionState,
// _req_state: ReqState,
// _platform: &domain::Platform,
// _business_profile: &domain::Profile,
// _payment_method_data: Option<&domain::PaymentMethodData>,
// _connector: api::ConnectorData,
// _customer: &Option<domain::Customer>,
// _payment_data: &mut D,
// _call_connector_action: common_enums::CallConnectorAction,
// ) -> CustomResult<
// hyperswitch_domain_models::router_data::RouterData<F, RouterDataReq, PaymentsResponseData>,
// errors::ApiErrorResponse,
// > {
// // TODO: raise an error here
// todo!();
// }
}
#[async_trait]
#[allow(clippy::too_many_arguments)]
pub trait UpdateTracker<F, D, Req>: Send {
/// Update the tracker information with the new data from request or calculated by the operations performed after get trackers
/// This will persist the SessionData ( PaymentData ) in the database
///
/// In case we are calling a processor / connector, we persist all the data in the database and then call the connector
async fn update_trackers<'b>(
&'b self,
db: &'b SessionState,
req_state: ReqState,
processor: &domain::Processor,
payment_data: D,
customer: Option<domain::Customer>,
frm_suggestion: Option<FrmSuggestion>,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(BoxedOperation<'b, F, Req, D>, D)>
where
F: 'b + Send;
}
#[cfg(feature = "v2")]
#[async_trait]
#[allow(clippy::too_many_arguments)]
pub trait CallConnector<F, D, RouterDReq: Send>: Send {
async fn call_connector<'b>(
&'b self,
db: &'b SessionState,
req_state: ReqState,
payment_data: D,
key_store: &domain::MerchantKeyStore,
call_connector_action: common_enums::CallConnectorAction,
connector_data: api::ConnectorData,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<types::RouterData<F, RouterDReq, PaymentsResponseData>>
where
F: 'b + Send + Sync,
D: super::flows::ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>,
types::RouterData<F, RouterDReq, PaymentsResponseData>:
super::flows::Feature<F, RouterDReq> + Send;
}
#[async_trait]
#[allow(clippy::too_many_arguments)]
pub trait PostUpdateTracker<F, D, R: Send>: Send {
/// Update the tracker information with the response from the connector
/// The response from routerdata is used to update paymentdata and also persist this in the database
#[cfg(feature = "v1")]
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
payment_data: D,
response: types::RouterData<F, R, PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(feature = "dynamic_routing")] routable_connector: Vec<RoutableConnectorChoice>,
#[cfg(feature = "dynamic_routing")] business_profile: &domain::Profile,
) -> RouterResult<D>
where
F: 'b + Send + Sync;
#[cfg(feature = "v2")]
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
payment_data: D,
response: types::RouterData<F, R, PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<D>
where
F: 'b + Send + Sync,
types::RouterData<F, R, PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, R, D>;
async fn save_pm_and_mandate<'b>(
&self,
_state: &SessionState,
_resp: &types::RouterData<F, R, PaymentsResponseData>,
_platform: &domain::Platform,
_payment_data: &mut D,
_business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
Ok(())
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<
D,
F: Clone + Send,
Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest, Data = D>,
> Domain<F, api::PaymentsRetrieveRequest, D> for Op
where
for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest, Data = D>,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send,
{
#[instrument(skip_all)]
async fn populate_raw_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_request: Option<&CustomerDetails>,
_processor: &domain::Processor,
) -> CustomResult<(), errors::StorageError> {
Ok(())
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
_request: Option<CustomerDetails>,
provider: &domain::Provider,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
let db = &*state.store;
let merchant_key_store = provider.get_key_store();
let storage_scheme = provider.get_account().storage_scheme;
let customer = match payment_data.get_payment_intent().customer_id.as_ref() {
None => None,
Some(customer_id) => {
// This function is to retrieve customer details. If the customer is deleted, it returns
// customer details that contains the fields as Redacted
db.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
customer_id,
&merchant_key_store.merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
}
};
if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) {
payment_data.set_email_if_not_present(email.into());
}
Ok((Box::new(self), customer))
}
async fn get_connector<'a>(
&'a self,
_platform: &domain::Platform,
state: &SessionState,
_request: &api::PaymentsRetrieveRequest,
_payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, None).await
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut D,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_platform: &domain::Platform,
_payment_data: &mut D,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest, Data = D>>
Domain<F, api::PaymentsCaptureRequest, D> for Op
where
for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest, Data = D>,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send,
{
#[instrument(skip_all)]
async fn populate_raw_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_request: Option<&CustomerDetails>,
_processor: &domain::Processor,
) -> CustomResult<(), errors::StorageError> {
Ok(())
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
_request: Option<CustomerDetails>,
provider: &domain::Provider,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
let db = &*state.store;
let merchant_key_store = provider.get_key_store();
let storage_scheme = provider.get_account().storage_scheme;
let customer = match payment_data.get_payment_intent().customer_id.as_ref() {
None => None,
Some(customer_id) => {
db.find_customer_optional_by_customer_id_merchant_id(
customer_id,
&merchant_key_store.merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
}
};
if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) {
payment_data.set_email_if_not_present(email.into());
}
Ok((Box::new(self), customer))
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
todo!()
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut D,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_platform: &domain::Platform,
state: &SessionState,
_request: &api::PaymentsCaptureRequest,
_payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, None).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_platform: &domain::Platform,
_payment_data: &mut D,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCancelRequest, Data = D>>
Domain<F, api::PaymentsCancelRequest, D> for Op
where
for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest, Data = D>,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send,
{
#[instrument(skip_all)]
async fn populate_raw_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_request: Option<&CustomerDetails>,
_processor: &domain::Processor,
) -> CustomResult<(), errors::StorageError> {
Ok(())
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
_request: Option<CustomerDetails>,
provider: &domain::Provider,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCancelRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
let db = &*state.store;
let merchant_key_store = provider.get_key_store();
let storage_scheme = provider.get_account().storage_scheme;
let customer = match payment_data.get_payment_intent().customer_id.as_ref() {
None => None,
Some(customer_id) => {
db.find_customer_optional_by_customer_id_merchant_id(
customer_id,
&merchant_key_store.merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
}
};
if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) {
payment_data.set_email_if_not_present(email.into());
}
Ok((Box::new(self), customer))
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCancelRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
todo!()
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut D,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsCancelRequest, D>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_platform: &domain::Platform,
state: &SessionState,
_request: &api::PaymentsCancelRequest,
_payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, None).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_platform: &domain::Platform,
_payment_data: &mut D,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRejectRequest, Data = D>>
Domain<F, api::PaymentsRejectRequest, D> for Op
where
for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest, Data = D>,
{
#[instrument(skip_all)]
async fn populate_raw_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_request: Option<&CustomerDetails>,
_processor: &domain::Processor,
) -> CustomResult<(), errors::StorageError> {
Ok(())
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_request: Option<CustomerDetails>,
_provider: &domain::Provider,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRejectRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
Ok((Box::new(self), None))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut D,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRejectRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
Ok((Box::new(self), None))
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut D,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/vault_session.rs | crates/router/src/core/payments/vault_session.rs | use std::{fmt::Debug, str::FromStr};
pub use common_enums::enums::CallConnectorAction;
use common_utils::id_type;
use error_stack::{report, ResultExt};
pub use hyperswitch_domain_models::{
mandates::MandateData,
payment_address::PaymentAddress,
payments::{HeaderPayload, PaymentIntentData},
router_data::{PaymentMethodToken, RouterData},
router_data_v2::{flow_common_types::VaultConnectorFlowData, RouterDataV2},
router_flow_types::ExternalVaultCreateFlow,
router_request_types::CustomerDetails,
types::{VaultRouterData, VaultRouterDataV2},
};
use hyperswitch_interfaces::{
api::Connector as ConnectorTrait,
connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},
};
use masking::ExposeInterface;
use router_env::{env::Env, instrument, tracing};
use crate::{
core::{
errors::{self, utils::StorageErrorExt, RouterResult},
payments::{
self as payments_core, call_multiple_connectors_service, customers,
flows::{ConstructFlowSpecificData, Feature},
gateway::context as gateway_context,
helpers, helpers as payment_helpers, operations,
operations::{BoxedOperation, Operation},
transformers, OperationSessionGetters, OperationSessionSetters,
},
utils as core_utils,
},
db::errors::ConnectorErrorExt,
errors::RouterResponse,
routes::{app::ReqState, SessionState},
services::{self, connector_integration_interface::RouterDataConversion},
types::{
self as router_types,
api::{self, enums as api_enums, ConnectorCommon},
domain, storage,
},
utils::{OptionExt, ValueExt},
};
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn populate_vault_session_details<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
customer: &Option<domain::Customer>,
platform: &domain::Platform,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
profile: &domain::Profile,
payment_data: &mut D,
header_payload: HeaderPayload,
) -> RouterResult<()>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let is_external_vault_sdk_enabled = profile.is_vault_sdk_enabled();
if is_external_vault_sdk_enabled {
let external_vault_source = profile
.external_vault_connector_details
.as_ref()
.map(|details| &details.vault_connector_id);
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
platform.get_processor().get_key_store(),
external_vault_source,
)
.await?,
));
let updated_customer = call_create_connector_customer_if_required(
state,
customer,
platform,
&merchant_connector_account,
payment_data,
)
.await?;
if let Some((customer, updated_customer)) = customer.clone().zip(updated_customer) {
let db = &*state.store;
let customer_id = customer.get_id().clone();
let customer_merchant_id = customer.merchant_id.clone();
let _updated_customer = db
.update_customer_by_global_id(
&customer_id,
customer,
updated_customer,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update customer during Vault session")?;
};
let vault_session_details = generate_vault_session_details(
state,
platform,
&merchant_connector_account,
payment_data.get_connector_customer_id(),
)
.await?;
payment_data.set_vault_session_details(vault_session_details);
}
Ok(())
}
#[cfg(feature = "v2")]
pub async fn call_create_connector_customer_if_required<F, Req, D>(
state: &SessionState,
customer: &Option<domain::Customer>,
platform: &domain::Platform,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
payment_data: &mut D,
) -> RouterResult<Option<storage::CustomerUpdate>>
where
F: Send + Clone + Sync,
Req: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>,
RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,
{
let db_merchant_connector_account =
merchant_connector_account_type.get_inner_db_merchant_connector_account();
let profile_id = payment_data.get_payment_intent().profile_id.clone();
let default_gateway_context = gateway_context::RouterGatewayContext::direct(
platform.clone(),
merchant_connector_account_type.clone(),
payment_data.get_payment_intent().merchant_id.clone(),
profile_id,
payment_data.get_creds_identifier().map(|id| id.to_string()),
);
match db_merchant_connector_account {
Some(merchant_connector_account) => {
let connector_name = merchant_connector_account.get_connector_name_as_string();
let merchant_connector_id = merchant_connector_account.get_id();
let connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
Some(merchant_connector_id.clone()),
)?;
let (should_call_connector, existing_connector_customer_id) =
customers::should_call_connector_create_customer(
&connector,
customer,
payment_data.get_payment_attempt(),
merchant_connector_account_type,
);
if should_call_connector {
// Create customer at connector and update the customer table to store this data
let router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
platform,
customer,
merchant_connector_account_type,
None,
None,
)
.await?;
let connector_customer_id = router_data
.create_connector_customer(state, &connector, &default_gateway_context)
.await?;
let customer_update = customers::update_connector_customer_in_customers(
merchant_connector_account_type,
customer.as_ref(),
connector_customer_id.clone(),
)
.await;
payment_data.set_connector_customer_id(connector_customer_id);
Ok(customer_update)
} else {
// Customer already created in previous calls use the same value, no need to update
payment_data.set_connector_customer_id(
existing_connector_customer_id.map(ToOwned::to_owned),
);
Ok(None)
}
}
None => {
router_env::logger::error!(
"Merchant connector account is missing, cannot create customer for vault session"
);
Err(errors::ApiErrorResponse::InternalServerError.into())
}
}
}
#[cfg(feature = "v2")]
pub async fn generate_vault_session_details(
state: &SessionState,
platform: &domain::Platform,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
) -> RouterResult<Option<api::VaultSessionDetails>> {
let connector_name = merchant_connector_account_type
.get_connector_name()
.map(|name| name.to_string())
.ok_or(errors::ApiErrorResponse::InternalServerError)?; // should not panic since we should always have a connector name
let connector = api_enums::VaultConnectors::from_str(&connector_name)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let connector_auth_type: router_types::ConnectorAuthType = merchant_connector_account_type
.get_connector_account_details()
.map_err(|err| {
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse connector auth type")
})?;
match (connector, connector_auth_type) {
// create session for vgs vault
(
api_enums::VaultConnectors::Vgs,
router_types::ConnectorAuthType::SignatureKey { api_secret, .. },
) => {
let sdk_env = match state.conf.env {
Env::Sandbox | Env::Development | Env::Integ => "sandbox",
Env::Production => "live",
}
.to_string();
Ok(Some(api::VaultSessionDetails::Vgs(
api::VgsSessionDetails {
external_vault_id: api_secret,
sdk_env,
},
)))
}
// create session for hyperswitch vault
(
api_enums::VaultConnectors::HyperswitchVault,
router_types::ConnectorAuthType::SignatureKey {
key1, api_secret, ..
},
) => {
generate_hyperswitch_vault_session_details(
state,
platform,
merchant_connector_account_type,
connector_customer_id,
connector_name,
key1,
api_secret,
)
.await
}
_ => {
router_env::logger::warn!(
"External vault session creation is not supported for connector: {}",
connector_name
);
Ok(None)
}
}
}
async fn generate_hyperswitch_vault_session_details(
state: &SessionState,
platform: &domain::Platform,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
connector_name: String,
vault_publishable_key: masking::Secret<String>,
vault_profile_id: masking::Secret<String>,
) -> RouterResult<Option<api::VaultSessionDetails>> {
let connector_response = call_external_vault_create(
state,
platform,
connector_name,
merchant_connector_account_type,
connector_customer_id,
)
.await?;
match connector_response.response {
Ok(router_types::VaultResponseData::ExternalVaultCreateResponse {
session_id,
client_secret,
}) => Ok(Some(api::VaultSessionDetails::HyperswitchVault(
api::HyperswitchVaultSessionDetails {
payment_method_session_id: session_id,
client_secret,
publishable_key: vault_publishable_key,
profile_id: vault_profile_id,
},
))),
Ok(_) => {
router_env::logger::warn!("Unexpected response from external vault create API");
Err(errors::ApiErrorResponse::InternalServerError.into())
}
Err(err) => {
router_env::logger::error!(error_response_from_external_vault_create=?err);
Err(errors::ApiErrorResponse::InternalServerError.into())
}
}
}
#[cfg(feature = "v2")]
async fn call_external_vault_create(
state: &SessionState,
platform: &domain::Platform,
connector_name: String,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
) -> RouterResult<VaultRouterData<ExternalVaultCreateFlow>>
where
dyn ConnectorTrait + Sync: services::api::ConnectorIntegration<
ExternalVaultCreateFlow,
router_types::VaultRequestData,
router_types::VaultResponseData,
>,
dyn ConnectorV2 + Sync: ConnectorIntegrationV2<
ExternalVaultCreateFlow,
VaultConnectorFlowData,
router_types::VaultRequestData,
router_types::VaultResponseData,
>,
{
let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
merchant_connector_account_type.get_mca_id(),
)?;
let merchant_connector_account = match &merchant_connector_account_type {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => {
Ok(mca.as_ref())
}
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("MerchantConnectorDetails not supported for vault operations"))
}
}?;
let mut router_data = core_utils::construct_vault_router_data(
state,
platform.get_processor().get_account().get_id(),
merchant_connector_account,
None,
None,
connector_customer_id,
None,
)
.await?;
let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Cannot construct router data for making the external vault create api call",
)?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultCreateFlow,
router_types::VaultRequestData,
router_types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/payment_methods.rs | crates/router/src/core/payments/payment_methods.rs | //! Contains functions of payment methods that are used in payments
//! one of such functions is `list_payment_methods`
use std::{
collections::{BTreeMap, HashSet},
str::FromStr,
};
use common_utils::{
ext_traits::{OptionExt, ValueExt},
id_type,
};
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
use super::errors;
use crate::{
configs::settings,
core::{payment_methods, payments::helpers},
db::errors::StorageErrorExt,
logger, routes,
types::{self, api, domain, storage},
};
#[cfg(feature = "v2")]
pub async fn list_payment_methods(
state: routes::SessionState,
platform: domain::Platform,
profile: domain::Profile,
payment_id: id_type::GlobalPaymentId,
req: api_models::payments::ListMethodsForPaymentsRequest,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> errors::RouterResponse<api_models::payments::PaymentMethodListResponseForPayments> {
let db = &*state.store;
let payment_intent = db
.find_payment_intent_by_id(
&payment_id,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
validate_payment_status_for_payment_method_list(payment_intent.status)?;
let payment_connector_accounts = db
.list_enabled_connector_accounts_by_profile_id(
profile.get_id(),
platform.get_processor().get_key_store(),
common_enums::ConnectorType::PaymentProcessor,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error when fetching merchant connector accounts")?;
let customer_payment_methods = match &payment_intent.customer_id {
Some(customer_id) => Some(
payment_methods::list_customer_payment_methods_core(
&state,
platform.get_provider(),
customer_id,
)
.await?,
),
None => None,
};
let response =
FlattenedPaymentMethodsEnabled(hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts))
.perform_filtering(
&state,
&platform,
profile.get_id(),
&req,
&payment_intent,
).await?
.store_gift_card_mca_in_redis(&payment_id, db, &profile).await
.merge_and_transform()
.get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone(), payment_intent.setup_future_usage))
.perform_surcharge_calculation()
.populate_pm_subtype_specific_data(&state.conf.bank_config)
.generate_response(customer_payment_methods);
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
/// Container for the inputs required for the required fields
struct RequiredFieldsInput {
required_fields_config: settings::RequiredFields,
setup_future_usage: common_enums::FutureUsage,
}
impl RequiredFieldsInput {
fn new(
required_fields_config: settings::RequiredFields,
setup_future_usage: common_enums::FutureUsage,
) -> Self {
Self {
required_fields_config,
setup_future_usage,
}
}
}
trait GetRequiredFields {
fn get_required_fields(
&self,
payment_method_enabled: &MergedEnabledPaymentMethod,
) -> Option<&settings::RequiredFieldFinal>;
}
impl GetRequiredFields for settings::RequiredFields {
fn get_required_fields(
&self,
payment_method_enabled: &MergedEnabledPaymentMethod,
) -> Option<&settings::RequiredFieldFinal> {
self.0
.get(&payment_method_enabled.payment_method_type)
.and_then(|required_fields_for_payment_method| {
required_fields_for_payment_method
.0
.get(&payment_method_enabled.payment_method_subtype)
})
.map(|connector_fields| &connector_fields.fields)
.and_then(|connector_hashmap| {
payment_method_enabled
.connectors
.first()
.and_then(|connector| connector_hashmap.get(connector))
})
}
}
struct FlattenedPaymentMethodsEnabled(
hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled,
);
/// Container for the filtered payment methods
struct FilteredPaymentMethodsEnabled(
Vec<hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector>,
);
impl FilteredPaymentMethodsEnabled {
fn merge_and_transform(self) -> MergedEnabledPaymentMethodTypes {
let values = self
.0
.into_iter()
// BTreeMap used to ensure soretd response, otherwise the response is arbitrarily ordered
.fold(BTreeMap::new(), |mut acc, item| {
let key = (
item.payment_method,
item.payment_methods_enabled.payment_method_subtype,
);
let (experiences, connectors) = acc
.entry(key)
// HashSet used to ensure payment_experience does not have duplicates, due to multiple connectors for a pm_subtype
.or_insert_with(|| (HashSet::new(), Vec::new()));
if let Some(experience) = item.payment_methods_enabled.payment_experience {
experiences.insert(experience);
}
connectors.push(item.connector);
acc
})
.into_iter()
.map(
|(
(payment_method_type, payment_method_subtype),
(payment_experience, connectors),
)| {
MergedEnabledPaymentMethod {
payment_method_type,
payment_method_subtype,
payment_experience: if payment_experience.is_empty() {
None
} else {
Some(payment_experience.into_iter().collect())
},
connectors,
}
},
)
.collect();
MergedEnabledPaymentMethodTypes(values)
}
async fn store_gift_card_mca_in_redis(
self,
payment_id: &id_type::GlobalPaymentId,
db: &dyn crate::db::StorageInterface,
profile: &domain::Profile,
) -> Self {
let gift_card_connector_id = self
.0
.iter()
.find(|item| item.payment_method == common_enums::PaymentMethod::GiftCard)
.map(|item| &item.merchant_connector_id);
if let Some(gift_card_mca) = gift_card_connector_id {
let gc_key = payment_id.get_gift_card_connector_key();
let redis_expiry = profile
.get_order_fulfillment_time()
.unwrap_or(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME);
let redis_conn = db
.get_redis_conn()
.map_err(|redis_error| logger::error!(?redis_error))
.ok();
if let Some(rc) = redis_conn {
rc.set_key_with_expiry(
&gc_key.as_str().into(),
gift_card_mca.get_string_repr().to_string(),
redis_expiry,
)
.await
.attach_printable("Failed to store gift card mca_id in redis")
.unwrap_or_else(|error| {
logger::error!(?error);
})
};
} else {
logger::error!(
"Could not find any configured MCA supporting gift card for payment_id -> {}",
payment_id.get_string_repr()
);
}
self
}
}
/// Element container to hold the filtered payment methods with payment_experience and connectors merged for a pm_subtype
struct MergedEnabledPaymentMethod {
payment_method_subtype: common_enums::PaymentMethodType,
payment_method_type: common_enums::PaymentMethod,
payment_experience: Option<Vec<common_enums::PaymentExperience>>,
connectors: Vec<api_models::enums::Connector>,
}
/// Container to hold the filtered payment methods with payment_experience and connectors merged for a pm_subtype
struct MergedEnabledPaymentMethodTypes(Vec<MergedEnabledPaymentMethod>);
impl MergedEnabledPaymentMethodTypes {
fn get_required_fields(
self,
input: RequiredFieldsInput,
) -> RequiredFieldsForEnabledPaymentMethodTypes {
let required_fields_config = input.required_fields_config;
let is_cit_transaction = input.setup_future_usage == common_enums::FutureUsage::OffSession;
let required_fields_info = self
.0
.into_iter()
.map(|payment_methods_enabled| {
let required_fields =
required_fields_config.get_required_fields(&payment_methods_enabled);
let required_fields = required_fields
.map(|required_fields| {
let common_required_fields = required_fields
.common
.iter()
.flatten()
.map(ToOwned::to_owned);
// Collect mandate required fields because this is for zero auth mandates only
let mandate_required_fields = required_fields
.mandate
.iter()
.flatten()
.map(ToOwned::to_owned);
// Collect non-mandate required fields because this is for zero auth mandates only
let non_mandate_required_fields = required_fields
.non_mandate
.iter()
.flatten()
.map(ToOwned::to_owned);
// Combine mandate and non-mandate required fields based on setup_future_usage
if is_cit_transaction {
common_required_fields
.chain(non_mandate_required_fields)
.collect::<Vec<_>>()
} else {
common_required_fields
.chain(mandate_required_fields)
.collect::<Vec<_>>()
}
})
.unwrap_or_default();
RequiredFieldsForEnabledPaymentMethod {
required_fields,
payment_method_type: payment_methods_enabled.payment_method_type,
payment_method_subtype: payment_methods_enabled.payment_method_subtype,
payment_experience: payment_methods_enabled.payment_experience,
connectors: payment_methods_enabled.connectors,
}
})
.collect();
RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info)
}
}
/// Element container to hold the filtered payment methods with required fields
struct RequiredFieldsForEnabledPaymentMethod {
required_fields: Vec<api_models::payment_methods::RequiredFieldInfo>,
payment_method_subtype: common_enums::PaymentMethodType,
payment_method_type: common_enums::PaymentMethod,
payment_experience: Option<Vec<common_enums::PaymentExperience>>,
connectors: Vec<api_models::enums::Connector>,
}
/// Container to hold the filtered payment methods enabled with required fields
struct RequiredFieldsForEnabledPaymentMethodTypes(Vec<RequiredFieldsForEnabledPaymentMethod>);
impl RequiredFieldsForEnabledPaymentMethodTypes {
fn perform_surcharge_calculation(
self,
) -> RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes {
// TODO: Perform surcharge calculation
let details_with_surcharge = self
.0
.into_iter()
.map(
|payment_methods_enabled| RequiredFieldsAndSurchargeForEnabledPaymentMethodType {
payment_method_type: payment_methods_enabled.payment_method_type,
required_fields: payment_methods_enabled.required_fields,
payment_method_subtype: payment_methods_enabled.payment_method_subtype,
payment_experience: payment_methods_enabled.payment_experience,
surcharge: None,
connectors: payment_methods_enabled.connectors,
},
)
.collect();
RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes(details_with_surcharge)
}
}
/// Element Container to hold the filtered payment methods enabled with required fields and surcharge
struct RequiredFieldsAndSurchargeForEnabledPaymentMethodType {
required_fields: Vec<api_models::payment_methods::RequiredFieldInfo>,
payment_method_subtype: common_enums::PaymentMethodType,
payment_method_type: common_enums::PaymentMethod,
payment_experience: Option<Vec<common_enums::PaymentExperience>>,
connectors: Vec<api_models::enums::Connector>,
surcharge: Option<api_models::payment_methods::SurchargeDetailsResponse>,
}
/// Container to hold the filtered payment methods enabled with required fields and surcharge
struct RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes(
Vec<RequiredFieldsAndSurchargeForEnabledPaymentMethodType>,
);
fn get_pm_subtype_specific_data(
bank_config: &settings::BankRedirectConfig,
payment_method_type: common_enums::enums::PaymentMethod,
payment_method_subtype: common_enums::enums::PaymentMethodType,
connectors: &[api_models::enums::Connector],
) -> Option<api_models::payment_methods::PaymentMethodSubtypeSpecificData> {
match payment_method_type {
// TODO: Return card_networks
common_enums::PaymentMethod::Card | common_enums::PaymentMethod::CardRedirect => None,
common_enums::PaymentMethod::BankRedirect
| common_enums::PaymentMethod::BankTransfer
| common_enums::PaymentMethod::BankDebit
| common_enums::PaymentMethod::OpenBanking => {
if let Some(connector_bank_names) = bank_config.0.get(&payment_method_subtype) {
let bank_names = connectors
.iter()
.filter_map(|connector| {
connector_bank_names.0.get(&connector.to_string())
.map(|connector_hash_set| {
connector_hash_set.banks.clone()
})
.or_else(|| {
logger::debug!("Could not find any configured connectors for payment_method -> {payment_method_subtype} for connector -> {connector}");
None
})
})
.flatten()
.collect();
Some(
api_models::payment_methods::PaymentMethodSubtypeSpecificData::Bank {
bank_names,
},
)
} else {
logger::debug!("Could not find any configured banks for payment_method -> {payment_method_subtype}");
None
}
}
common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::Wallet
| common_enums::PaymentMethod::Crypto
| common_enums::PaymentMethod::Reward
| common_enums::PaymentMethod::RealTimePayment
| common_enums::PaymentMethod::Upi
| common_enums::PaymentMethod::Voucher
| common_enums::PaymentMethod::GiftCard
| common_enums::PaymentMethod::MobilePayment
| common_enums::PaymentMethod::NetworkToken => None,
}
}
impl RequiredFieldsAndSurchargeForEnabledPaymentMethodTypes {
fn populate_pm_subtype_specific_data(
self,
bank_config: &settings::BankRedirectConfig,
) -> RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes {
let response_payment_methods = self
.0
.into_iter()
.map(|payment_methods_enabled| {
RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodType {
payment_method_type: payment_methods_enabled.payment_method_type,
payment_method_subtype: payment_methods_enabled.payment_method_subtype,
payment_experience: payment_methods_enabled.payment_experience,
required_fields: payment_methods_enabled.required_fields,
surcharge: payment_methods_enabled.surcharge,
pm_subtype_specific_data: get_pm_subtype_specific_data(
bank_config,
payment_methods_enabled.payment_method_type,
payment_methods_enabled.payment_method_subtype,
&payment_methods_enabled.connectors,
),
}
})
.collect();
RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes(
response_payment_methods,
)
}
}
/// Element Container to hold the filtered payment methods enabled with required fields, surcharge and subtype specific data
struct RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodType {
required_fields: Vec<api_models::payment_methods::RequiredFieldInfo>,
payment_method_subtype: common_enums::PaymentMethodType,
payment_method_type: common_enums::PaymentMethod,
payment_experience: Option<Vec<common_enums::PaymentExperience>>,
surcharge: Option<api_models::payment_methods::SurchargeDetailsResponse>,
pm_subtype_specific_data: Option<api_models::payment_methods::PaymentMethodSubtypeSpecificData>,
}
/// Container to hold the filtered payment methods enabled with required fields, surcharge and subtype specific data
struct RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes(
Vec<RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodType>,
);
impl RequiredFieldsAndSurchargeWithExtraInfoForEnabledPaymentMethodTypes {
fn generate_response(
self,
customer_payment_methods: Option<
Vec<api_models::payment_methods::CustomerPaymentMethodResponseItem>,
>,
) -> api_models::payments::PaymentMethodListResponseForPayments {
let response_payment_methods = self
.0
.into_iter()
.map(|payment_methods_enabled| {
api_models::payments::ResponsePaymentMethodTypesForPayments {
payment_method_type: payment_methods_enabled.payment_method_type,
payment_method_subtype: payment_methods_enabled.payment_method_subtype,
payment_experience: payment_methods_enabled.payment_experience,
required_fields: payment_methods_enabled.required_fields,
surcharge_details: payment_methods_enabled.surcharge,
extra_information: payment_methods_enabled.pm_subtype_specific_data,
}
})
.collect();
api_models::payments::PaymentMethodListResponseForPayments {
payment_methods_enabled: response_payment_methods,
customer_payment_methods,
}
}
}
impl FlattenedPaymentMethodsEnabled {
async fn perform_filtering(
self,
state: &routes::SessionState,
platform: &domain::Platform,
profile_id: &id_type::ProfileId,
req: &api_models::payments::ListMethodsForPaymentsRequest,
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
) -> errors::RouterResult<FilteredPaymentMethodsEnabled> {
let billing_address = payment_intent
.billing_address
.clone()
.and_then(|address| address.into_inner().address);
let mut response: Vec<hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector> = vec![];
for payment_method_enabled_details in self.0.payment_methods_enabled {
filter_payment_methods(
payment_method_enabled_details,
req,
&mut response,
Some(payment_intent),
billing_address.as_ref(),
&state.conf,
)
.await?;
}
Ok(FilteredPaymentMethodsEnabled(response))
}
}
// note: v2 type for ListMethodsForPaymentMethodsRequest will not have the installment_payment_enabled field,
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn filter_payment_methods(
payment_method_type_details: hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
req: &api_models::payments::ListMethodsForPaymentsRequest,
resp: &mut Vec<
hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
>,
payment_intent: Option<&storage::PaymentIntent>,
address: Option<&hyperswitch_domain_models::address::AddressDetails>,
configs: &settings::Settings<RawSecret>,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
let payment_method = payment_method_type_details.payment_method;
let mut payment_method_object = payment_method_type_details.payment_methods_enabled.clone();
// filter based on request parameters
let request_based_filter =
filter_recurring_based(&payment_method_object, req.recurring_enabled)
&& filter_amount_based(&payment_method_object, req.amount)
&& filter_card_network_based(
payment_method_object.card_networks.as_ref(),
req.card_networks.as_ref(),
payment_method_object.payment_method_subtype,
);
// filter based on payment intent
let intent_based_filter = if let Some(payment_intent) = payment_intent {
filter_country_based(address, &payment_method_object)
&& filter_currency_based(
payment_intent.amount_details.currency,
&payment_method_object,
)
&& filter_amount_based(
&payment_method_object,
Some(payment_intent.amount_details.calculate_net_amount()),
)
&& filter_zero_mandate_based(configs, payment_intent, &payment_method_type_details)
&& filter_allowed_payment_method_types_based(
payment_intent.allowed_payment_method_types.as_ref(),
payment_method_object.payment_method_subtype,
)
} else {
true
};
// filter based on payment method type configuration
let config_based_filter = filter_config_based(
configs,
&payment_method_type_details.connector.to_string(),
payment_method_object.payment_method_subtype,
payment_intent,
&mut payment_method_object.card_networks,
address.and_then(|inner| inner.country),
payment_intent.map(|value| value.amount_details.currency),
);
// if all filters pass, add the payment method type details to the response
if request_based_filter && intent_based_filter && config_based_filter {
resp.push(payment_method_type_details);
}
Ok(())
}
// filter based on country supported by payment method type
// return true if the intent's country is null or if the country is in the accepted countries list
fn filter_country_based(
address: Option<&hyperswitch_domain_models::address::AddressDetails>,
pm: &common_types::payment_methods::RequestPaymentMethodTypes,
) -> bool {
address.is_none_or(|address| {
address.country.as_ref().is_none_or(|country| {
pm.accepted_countries.as_ref().is_none_or(|ac| match ac {
common_types::payment_methods::AcceptedCountries::EnableOnly(acc) => {
acc.contains(country)
}
common_types::payment_methods::AcceptedCountries::DisableOnly(den) => {
!den.contains(country)
}
common_types::payment_methods::AcceptedCountries::AllAccepted => true,
})
})
})
}
// filter based on currency supported by payment method type
// return true if the intent's currency is null or if the currency is in the accepted currencies list
fn filter_currency_based(
currency: common_enums::Currency,
pm: &common_types::payment_methods::RequestPaymentMethodTypes,
) -> bool {
pm.accepted_currencies.as_ref().is_none_or(|ac| match ac {
common_types::payment_methods::AcceptedCurrencies::EnableOnly(acc) => {
acc.contains(¤cy)
}
common_types::payment_methods::AcceptedCurrencies::DisableOnly(den) => {
!den.contains(¤cy)
}
common_types::payment_methods::AcceptedCurrencies::AllAccepted => true,
})
}
// filter based on payment method type configuration
// return true if the payment method type is in the configuration for the connector
// return true if the configuration is not available for the connector
fn filter_config_based<'a>(
config: &'a settings::Settings<RawSecret>,
connector: &'a str,
payment_method_type: common_enums::PaymentMethodType,
payment_intent: Option<&storage::PaymentIntent>,
card_network: &mut Option<Vec<common_enums::CardNetwork>>,
country: Option<common_enums::CountryAlpha2>,
currency: Option<common_enums::Currency>,
) -> bool {
config
.pm_filters
.0
.get(connector)
.or_else(|| config.pm_filters.0.get("default"))
.and_then(|inner| match payment_method_type {
common_enums::PaymentMethodType::Credit | common_enums::PaymentMethodType::Debit => {
inner
.0
.get(&settings::PaymentMethodFilterKey::PaymentMethodType(
payment_method_type,
))
.map(|value| filter_config_country_currency_based(value, country, currency))
}
payment_method_type => inner
.0
.get(&settings::PaymentMethodFilterKey::PaymentMethodType(
payment_method_type,
))
.map(|value| filter_config_country_currency_based(value, country, currency)),
})
.unwrap_or(true)
}
// filter country and currency based on config for payment method type
// return true if the country and currency are in the accepted countries and currencies list
fn filter_config_country_currency_based(
item: &settings::CurrencyCountryFlowFilter,
country: Option<common_enums::CountryAlpha2>,
currency: Option<common_enums::Currency>,
) -> bool {
let country_condition = item
.country
.as_ref()
.zip(country.as_ref())
.map(|(lhs, rhs)| lhs.contains(rhs));
let currency_condition = item
.currency
.as_ref()
.zip(currency)
.map(|(lhs, rhs)| lhs.contains(&rhs));
country_condition.unwrap_or(true) && currency_condition.unwrap_or(true)
}
// filter based on recurring enabled parameter of request
// return true if recurring_enabled is null or if it matches the payment method's recurring_enabled
fn filter_recurring_based(
payment_method: &common_types::payment_methods::RequestPaymentMethodTypes,
recurring_enabled: Option<bool>,
) -> bool {
recurring_enabled.is_none_or(|enabled| payment_method.recurring_enabled == Some(enabled))
}
// filter based on valid amount range of payment method type
// return true if the amount is within the payment method's minimum and maximum amount range
// return true if the amount is null or zero
fn filter_amount_based(
payment_method: &common_types::payment_methods::RequestPaymentMethodTypes,
amount: Option<types::MinorUnit>,
) -> bool {
let min_check = amount
.and_then(|amt| payment_method.minimum_amount.map(|min_amt| amt >= min_amt))
.unwrap_or(true);
let max_check = amount
.and_then(|amt| payment_method.maximum_amount.map(|max_amt| amt <= max_amt))
.unwrap_or(true);
(min_check && max_check) || amount == Some(types::MinorUnit::zero())
}
// return true if the intent is a zero mandate intent and the payment method is supported for zero mandates
// return false if the intent is a zero mandate intent and the payment method is not supported for zero mandates
// return true if the intent is not a zero mandate intent
fn filter_zero_mandate_based(
configs: &settings::Settings<RawSecret>,
payment_intent: &storage::PaymentIntent,
payment_method_type_details: &hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
) -> bool {
if payment_intent.setup_future_usage == common_enums::FutureUsage::OffSession
&& payment_intent.amount_details.calculate_net_amount() == types::MinorUnit::zero()
{
configs
.zero_mandates
.supported_payment_methods
.0
.get(&payment_method_type_details.payment_method)
.and_then(|supported_pm_for_mandates| {
supported_pm_for_mandates
.0
.get(
&payment_method_type_details
.payment_methods_enabled
.payment_method_subtype,
)
.map(|supported_connector_for_mandates| {
supported_connector_for_mandates
.connector_list
.contains(&payment_method_type_details.connector)
})
})
.unwrap_or(false)
} else {
true
}
}
// filter based on allowed payment method types
// return true if the allowed types are null or if the payment method type is in the allowed types list
fn filter_allowed_payment_method_types_based(
allowed_types: Option<&Vec<api_models::enums::PaymentMethodType>>,
payment_method_type: api_models::enums::PaymentMethodType,
) -> bool {
allowed_types.is_none_or(|pm| pm.contains(&payment_method_type))
}
// filter based on card networks
// return true if the payment method type's card networks are a subset of the request's card networks
// return true if the card networks are not specified in the request
fn filter_card_network_based(
pm_card_networks: Option<&Vec<api_models::enums::CardNetwork>>,
request_card_networks: Option<&Vec<api_models::enums::CardNetwork>>,
pm_type: api_models::enums::PaymentMethodType,
) -> bool {
match pm_type {
api_models::enums::PaymentMethodType::Credit
| api_models::enums::PaymentMethodType::Debit => {
match (pm_card_networks, request_card_networks) {
(Some(pm_card_networks), Some(request_card_networks)) => request_card_networks
.iter()
.all(|card_network| pm_card_networks.contains(card_network)),
(None, Some(_)) => false,
_ => true,
}
}
_ => true,
}
}
/// Validate if payment methods list can be performed on the current status of payment intent
fn validate_payment_status_for_payment_method_list(
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
common_enums::IntentStatus::RequiresPaymentMethod => Ok(()),
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Conflicted
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::Processing
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/transformers.rs | crates/router/src/core/payments/transformers.rs | use std::{fmt::Debug, marker::PhantomData, str::FromStr};
#[cfg(feature = "v2")]
use api_models::enums as api_enums;
#[cfg(feature = "v1")]
use api_models::payments::PaymentMethodTokenizationDetails;
#[cfg(feature = "v2")]
use api_models::payments::RevenueRecoveryGetIntentResponse;
use api_models::payments::{
Address, ConnectorMandateReferenceId, CustomerDetails, CustomerDetailsResponse, FrmMessage,
MandateIds, NetworkDetails, RequestSurchargeDetails,
};
use common_enums::{Currency, RequestIncrementalAuthorization};
#[cfg(feature = "v1")]
use common_utils::{
consts::X_HS_LATENCY,
fp_utils, pii,
types::{
self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnit,
StringMajorUnitForConnector,
},
};
#[cfg(feature = "v2")]
use common_utils::{
ext_traits::Encode,
fp_utils, pii,
types::{
self as common_utils_type, AmountConvertor, MinorUnit, StringMajorUnit,
StringMajorUnitForConnector,
},
};
use diesel_models::{
ephemeral_key,
payment_attempt::{
ConnectorMandateReferenceId as DieselConnectorMandateReferenceId,
NetworkDetails as DieselNetworkDetails,
},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{payments::payment_intent::CustomerData, router_request_types};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
router_data_v2::{flow_common_types, RouterDataV2},
ApiModelToDieselModelConvertor,
};
#[cfg(feature = "v2")]
use hyperswitch_interfaces::api::ConnectorSpecifications;
#[cfg(feature = "v2")]
use hyperswitch_interfaces::connector_integration_interface::RouterDataConversion;
use masking::{ExposeInterface, Maskable, Secret};
#[cfg(feature = "v2")]
use masking::{ExposeOptionInterface, PeekInterface};
use router_env::{instrument, tracing};
use super::{flows::Feature, types::AuthenticationData, OperationSessionGetters, PaymentData};
use crate::{
configs::settings::ConnectorRequestReferenceIdConfig,
core::{
errors::{self, RouterResponse, RouterResult},
payments::{self, helpers},
utils as core_utils,
},
headers::{X_CONNECTOR_HTTP_STATUS_CODE, X_PAYMENT_CONFIRM_SOURCE},
routes::{metrics, SessionState},
services::{self, RedirectForm},
types::{
self,
api::{self, ConnectorTransactionId},
domain, payment_methods as pm_types,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto, ForeignTryFrom},
MultipleCaptureRequestData,
},
utils::{OptionExt, ValueExt},
};
#[cfg(feature = "v2")]
pub async fn construct_router_data_to_update_calculated_tax<'a, F, T>(
state: &'a SessionState,
payment_data: PaymentData<F>,
connector_id: &str,
platform: &domain::Platform,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>,
F: Clone,
error_stack::Report<errors::ApiErrorResponse>:
From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>,
{
todo!()
}
#[cfg(feature = "v1")]
pub async fn construct_router_data_to_update_calculated_tax<'a, F, T>(
state: &'a SessionState,
payment_data: PaymentData<F>,
connector_id: &str,
platform: &domain::Platform,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>,
F: Clone,
error_stack::Report<errors::ApiErrorResponse>:
From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>,
{
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
})?;
let test_mode = 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)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let additional_data = PaymentAdditionalData {
router_base_url: state.base_url.clone(),
connector_name: connector_id.to_string(),
payment_data: payment_data.clone(),
state,
customer_data: customer,
};
let connector_mandate_request_reference_id = payment_data
.payment_attempt
.connector_mandate_detail
.as_ref()
.and_then(|detail| detail.get_connector_mandate_request_reference_id());
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: platform.get_processor().get_account().get_id().clone(),
customer_id: None,
connector: connector_id.to_owned(),
payment_id: payment_data
.payment_attempt
.payment_id
.get_string_repr()
.to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: payment_data.payment_attempt.get_id().to_owned(),
status: payment_data.payment_attempt.status,
payment_method: diesel_models::enums::PaymentMethod::default(),
payment_method_type: payment_data.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: payment_data.address.clone(),
auth_type: payment_data
.payment_attempt
.authentication_type
.unwrap_or_default(),
connector_meta_data: None,
connector_wallets_details: None,
request: T::try_from(additional_data)?,
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: None,
recurring_mandate_payment_data: None,
connector_request_reference_id: core_utils::get_connector_request_reference_id(
&state.conf,
platform.get_processor(),
&payment_data.payment_intent,
&payment_data.payment_attempt,
connector_id,
)?,
preprocessing_id: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
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,
payout_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: payment_data.payment_intent.is_payment_id_from_merchant,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_external_vault_proxy_router_data_v2<'a>(
state: &'a SessionState,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
payment_data: &hyperswitch_domain_models::payments::PaymentConfirmData<api::ExternalVaultProxy>,
request: types::ExternalVaultProxyPaymentsData,
connector_request_reference_id: String,
connector_customer_id: Option<String>,
customer_id: Option<common_utils::id_type::CustomerId>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
RouterDataV2<
api::ExternalVaultProxy,
hyperswitch_domain_models::router_data_v2::ExternalVaultProxyFlowData,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
>,
> {
use hyperswitch_domain_models::router_data_v2::{ExternalVaultProxyFlowData, RouterDataV2};
let auth_type = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let external_vault_proxy_flow_data = ExternalVaultProxyFlowData {
merchant_id: merchant_account.get_id().clone(),
customer_id,
connector_customer: connector_customer_id,
payment_id: payment_data
.payment_attempt
.payment_id
.get_string_repr()
.to_owned(),
attempt_id: payment_data
.payment_attempt
.get_id()
.get_string_repr()
.to_owned(),
status: payment_data.payment_attempt.status,
payment_method: payment_data.payment_attempt.payment_method_type,
description: payment_data
.payment_intent
.description
.as_ref()
.map(|description| description.get_string_repr())
.map(ToOwned::to_owned),
address: payment_data.payment_address.clone(),
auth_type: payment_data.payment_attempt.authentication_type,
connector_meta_data: merchant_connector_account.get_metadata(),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: payment_data.payment_attempt.preprocessing_step_id.clone(),
payment_method_balance: None,
connector_api_version: None,
connector_request_reference_id,
test_mode: Some(true),
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
connector_response: None,
payment_method_status: None,
};
let router_data_v2 = RouterDataV2 {
flow: PhantomData,
tenant_id: state.tenant.tenant_id.clone(),
resource_common_data: external_vault_proxy_flow_data,
connector_auth_type: auth_type,
request,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
};
Ok(router_data_v2)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_payment_router_data_for_authorize<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::Authorize>,
connector_id: &str,
platform: &domain::Platform,
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::PaymentsAuthorizeRouterData> {
use masking::ExposeOptionInterface;
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 =
payment_data.get_connector_customer_id(customer.as_ref(), merchant_connector_account);
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(),
)),
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
payment_data.webhook_url
}
};
let router_return_url = payment_data
.payment_intent
.create_finish_redirection_url(
router_base_url,
platform
.get_processor()
.get_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);
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_data.payment_attempt
.payment_method_data
.as_ref().map(|data| data.clone().parse_value("AdditionalPaymentData"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse AdditionalPaymentData from payment_data.payment_attempt.payment_method_data")?;
let connector_metadata = payment_data.payment_intent.connector_metadata.clone();
let order_category = connector_metadata.as_ref().and_then(|cm| {
cm.noon
.as_ref()
.and_then(|noon| noon.order_category.clone())
});
// TODO: few fields are repeated in both routerdata and request
let request = types::PaymentsAuthorizeData {
payment_method_data: payment_data
.payment_method_data
.get_required_value("payment_method_data")?,
setup_future_usage: Some(payment_data.payment_intent.setup_future_usage),
mandate_id: payment_data.mandate_data.clone(),
off_session: None,
setup_mandate_details: None,
confirm: true,
capture_method: Some(payment_data.payment_intent.capture_method),
amount: payment_data
.payment_attempt
.amount_details
.get_net_amount()
.get_amount_as_i64(),
minor_amount: payment_data.payment_attempt.amount_details.get_net_amount(),
order_tax_amount: None,
currency: payment_data.payment_intent.amount_details.currency,
browser_info,
email,
customer_name: None,
payment_experience: None,
order_details: None,
order_category,
session_token: None,
enrolled_for_3ds: true,
related_transaction_id: None,
payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype),
router_return_url: Some(router_return_url),
webhook_url,
complete_authorize_url,
customer_id: customer_id.clone(),
surcharge_details: None,
request_extended_authorization: None,
request_incremental_authorization: matches!(
payment_data
.payment_intent
.request_incremental_authorization,
RequestIncrementalAuthorization::True
),
metadata: payment_data.payment_intent.metadata.expose_option(),
authentication_data: None,
customer_acceptance: None,
split_payments: None,
merchant_order_reference_id: payment_data
.payment_intent
.merchant_reference_id
.map(|reference_id| reference_id.get_string_repr().to_owned()),
integrity_object: None,
shipping_cost: payment_data.payment_intent.amount_details.shipping_cost,
additional_payment_method_data,
merchant_account_id: None,
merchant_config_currency: None,
connector_testing_data: None,
order_id: None,
locale: None,
mit_category: None,
tokenization: None,
payment_channel: None,
enable_partial_authorization: Some(
payment_data.payment_intent.enable_partial_authorization,
),
enable_overcapture: None,
is_stored_credential: None,
billing_descriptor: None,
partner_merchant_identifier_details: 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: platform.get_processor().get_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,
payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype),
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: merchant_connector_account.get_metadata(),
connector_wallets_details: None,
request,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
amount_captured: payment_data
.payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_data.payment_intent.amount_captured,
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,
payout_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: payment_data.payment_intent.is_payment_id_from_merchant,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_external_vault_proxy_payment_router_data<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::ExternalVaultProxy>,
connector_id: &str,
platform: &domain::Platform,
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::ExternalVaultProxyPaymentsRouterData> {
use masking::ExposeOptionInterface;
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 =
payment_data.get_connector_customer_id(customer.as_ref(), merchant_connector_account);
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(),
)),
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
payment_data.webhook_url.clone()
}
};
let router_return_url = payment_data
.payment_intent
.create_finish_redirection_url(
router_base_url,
platform
.get_processor()
.get_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::ExternalVaultProxyPaymentsData {
payment_method_data: payment_data
.external_vault_pmd
.clone()
.get_required_value("external vault proxy payment_method_data")?,
setup_future_usage: Some(payment_data.payment_intent.setup_future_usage),
mandate_id: payment_data.mandate_data.clone(),
off_session: None,
setup_mandate_details: None,
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
capture_method: Some(payment_data.payment_intent.capture_method),
amount: payment_data
.payment_attempt
.amount_details
.get_net_amount()
.get_amount_as_i64(),
minor_amount: payment_data.payment_attempt.amount_details.get_net_amount(),
order_tax_amount: None,
currency: payment_data.payment_intent.amount_details.currency,
browser_info,
email,
customer_name: None,
payment_experience: None,
order_details: None,
order_category: None,
session_token: None,
enrolled_for_3ds: true,
related_transaction_id: None,
payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype),
router_return_url: Some(router_return_url),
webhook_url,
complete_authorize_url,
customer_id: customer_id.clone(),
surcharge_details: None,
request_extended_authorization: None,
request_incremental_authorization: matches!(
payment_data
.payment_intent
.request_incremental_authorization,
RequestIncrementalAuthorization::True
),
metadata: payment_data.payment_intent.metadata.clone().expose_option(),
authentication_data: None,
customer_acceptance: None,
split_payments: None,
merchant_order_reference_id: payment_data.payment_intent.merchant_reference_id.clone(),
integrity_object: None,
shipping_cost: payment_data.payment_intent.amount_details.shipping_cost,
additional_payment_method_data: None,
merchant_account_id: None,
merchant_config_currency: None,
connector_testing_data: None,
order_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());
// Construct RouterDataV2 for external vault proxy
let router_data_v2 = construct_external_vault_proxy_router_data_v2(
state,
platform.get_processor().get_account(),
merchant_connector_account,
&payment_data,
request,
connector_request_reference_id.clone(),
connector_customer_id.clone(),
customer_id.clone(),
header_payload.clone(),
)
.await?;
// Convert RouterDataV2 to old RouterData (v1) using the existing RouterDataConversion trait
let router_data =
flow_common_types::ExternalVaultProxyFlowData::to_old_router_data(router_data_v2)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Cannot construct router data for making the unified connector service call",
)?;
Ok(router_data)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_payment_router_data_for_capture<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentCaptureData<api::Capture>,
connector_id: &str,
platform: &domain::Platform,
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::PaymentsCaptureRouterData> {
use masking::ExposeOptionInterface;
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")?;
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 payment_method = payment_data.payment_attempt.payment_method_type;
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());
let connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_id,
api::GetToken::Connector,
payment_data.payment_attempt.merchant_connector_id.clone(),
)?;
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 amount_to_capture = payment_data
.payment_attempt
.amount_details
.get_amount_to_capture()
.unwrap_or(payment_data.payment_attempt.amount_details.get_net_amount());
let amount = payment_data.payment_attempt.amount_details.get_net_amount();
let request = types::PaymentsCaptureData {
capture_method: Some(payment_data.payment_intent.capture_method),
amount_to_capture: amount_to_capture.get_amount_as_i64(), // This should be removed once we start moving to connector module
minor_amount_to_capture: amount_to_capture,
currency: payment_data.payment_intent.amount_details.currency,
connector_transaction_id: connector
.connector
.connector_transaction_id(&payment_data.payment_attempt)?
.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,
payment_amount: amount.get_amount_as_i64(), // This should be removed once we start moving to connector module
minor_payment_amount: amount,
connector_meta: payment_data
.payment_attempt
.connector_metadata
.clone()
.expose_option(),
// TODO: add multiple capture data
multiple_capture_data: None,
// TODO: why do we need browser info during capture?
browser_info: None,
metadata: payment_data.payment_intent.metadata.expose_option(),
integrity_object: None,
split_payments: None,
webhook_url: None,
};
// TODO: evaluate the fields in router data, if they are required or not
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: platform.get_processor().get_account().get_id().clone(),
// TODO: evaluate why we need customer id at the connector level. We already have connector customer id.
customer_id,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/session_operation.rs | crates/router/src/core/payments/session_operation.rs | use std::{fmt::Debug, str::FromStr};
pub use common_enums::enums::CallConnectorAction;
use common_utils::id_type;
use error_stack::ResultExt;
pub use hyperswitch_domain_models::{
mandates::MandateData,
payment_address::PaymentAddress,
payments::{HeaderPayload, PaymentIntentData},
router_data::{PaymentMethodToken, RouterData},
router_data_v2::{flow_common_types::VaultConnectorFlowData, RouterDataV2},
router_flow_types::ExternalVaultCreateFlow,
router_request_types::CustomerDetails,
types::{VaultRouterData, VaultRouterDataV2},
};
use hyperswitch_interfaces::{
api::Connector as ConnectorTrait,
connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},
};
use masking::ExposeInterface;
use router_env::{env::Env, instrument, tracing};
use crate::{
core::{
errors::{self, utils::StorageErrorExt, RouterResult},
payments::{
self as payments_core, call_multiple_connectors_service,
flows::{ConstructFlowSpecificData, Feature},
helpers, helpers as payment_helpers, operations,
operations::{BoxedOperation, Operation},
transformers, vault_session, OperationSessionGetters, OperationSessionSetters,
},
utils as core_utils,
},
db::errors::ConnectorErrorExt,
errors::RouterResponse,
routes::{app::ReqState, SessionState},
services::{self, connector_integration_interface::RouterDataConversion},
types::{
self as router_types,
api::{self, enums as api_enums, ConnectorCommon},
domain, storage,
},
utils::{OptionExt, ValueExt},
};
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_session_core<F, Res, Req, Op, FData, D>(
state: SessionState,
req_state: ReqState,
platform: domain::Platform,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
Req: Send + Sync,
FData: Send + Sync + Clone,
Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
Req: Debug,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
Res: transformers::ToResponse<F, D, Op>,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
{
let (payment_data, _req, customer, connector_http_status_code, external_latency) =
payments_session_operation_core::<_, _, _, _, _>(
&state,
req_state,
platform.clone(),
profile,
operation.clone(),
req,
payment_id,
call_connector_action,
header_payload.clone(),
)
.await?;
Res::generate_response(
payment_data,
customer,
&state.base_url,
operation,
&state.conf.connector_request_reference_id_config,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&platform,
)
}
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn payments_session_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
platform: domain::Platform,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
_call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync,
Req: Send + Sync,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
FData: Send + Sync + Clone,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
let _validate_result = operation
.to_validate_request()?
.validate_request(&req, &platform)?;
let operations::GetTrackerResponse { mut payment_data } = operation
.to_get_tracker()?
.get_trackers(
state,
&payment_id,
&req,
&platform,
&profile,
&header_payload,
)
.await?;
let (_operation, customer) = operation
.to_domain()?
.get_customer_details(
state,
&mut payment_data,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
vault_session::populate_vault_session_details(
state,
req_state.clone(),
&customer,
&platform,
&operation,
&profile,
&mut payment_data,
header_payload.clone(),
)
.await?;
let connector = operation
.to_domain()?
.perform_routing(&platform, &profile, &state.clone(), &mut payment_data)
.await?;
let payment_data = match connector {
api::ConnectorCallType::PreDetermined(_connector) => {
todo!()
}
api::ConnectorCallType::Retryable(_connectors) => todo!(),
api::ConnectorCallType::Skip => todo!(),
api::ConnectorCallType::SessionMultiple(connectors) => {
operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
platform.get_processor(),
payment_data.clone(),
customer.clone(),
None,
header_payload.clone(),
)
.await?;
// todo: call surcharge manager for session token call.
Box::pin(call_multiple_connectors_service(
state,
&platform,
connectors,
&operation,
payment_data,
&customer,
None,
&profile,
header_payload.clone(),
None,
))
.await?
}
};
Ok((payment_data, req, customer, None, None))
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/retry.rs | crates/router/src/core/payments/retry.rs | use std::vec::IntoIter;
use common_utils::{ext_traits::Encode, types::MinorUnit};
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
use hyperswitch_domain_models::ext_traits::OptionExt;
use router_env::{
logger,
tracing::{self, instrument},
};
use crate::{
consts,
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{
self,
flows::{ConstructFlowSpecificData, Feature},
operations,
},
routing::helpers as routing_helpers,
},
db::StorageInterface,
routes::{
self,
app::{self, ReqState},
metrics,
},
services,
types::{self, api, domain, storage, transformers::ForeignFrom},
};
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "v1")]
pub async fn do_gsm_actions<'a, F, ApiRequest, FData, D>(
state: &app::SessionState,
req_state: ReqState,
payment_data: &mut D,
mut connector_routing_data: IntoIter<api::ConnectorRoutingData>,
original_connector_data: &api::ConnectorData,
mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
platform: &domain::Platform,
operation: &operations::BoxedOperation<'_, F, ApiRequest, D>,
customer: &Option<domain::Customer>,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
F: Clone + Send + Sync + std::fmt::Debug + 'static,
FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize,
payments::PaymentResponse: operations::Operation<F, FData>,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
{
let mut retries = None;
metrics::AUTO_RETRY_ELIGIBLE_REQUEST_COUNT.add(1, &[]);
let mut initial_gsm = get_gsm(state, &router_data).await?;
let step_up_possible = initial_gsm
.as_ref()
.and_then(|data| data.feature_data.get_retry_feature_data())
.map(|data| data.is_step_up_possible())
.unwrap_or(false);
#[cfg(feature = "v1")]
let is_no_three_ds_payment = matches!(
payment_data.get_payment_attempt().authentication_type,
Some(storage_enums::AuthenticationType::NoThreeDs)
);
#[cfg(feature = "v2")]
let is_no_three_ds_payment = matches!(
payment_data.get_payment_attempt().authentication_type,
storage_enums::AuthenticationType::NoThreeDs
);
let should_step_up = if step_up_possible && is_no_three_ds_payment {
is_step_up_enabled_for_merchant_connector(
state,
platform.get_processor().get_account().get_id(),
original_connector_data.connector_name,
)
.await
} else {
false
};
if should_step_up {
router_data = do_retry(
&state.clone(),
req_state.clone(),
original_connector_data,
operation,
customer,
platform,
payment_data,
router_data,
validate_result,
schedule_time,
true,
frm_suggestion,
business_profile,
false, //should_retry_with_pan is not applicable for step-up
None,
)
.await?;
}
// Step up is not applicable so proceed with auto retries flow
else {
loop {
// Use initial_gsm for first time alone
let gsm = match initial_gsm.as_ref() {
Some(gsm) => Some(gsm.clone()),
None => get_gsm(state, &router_data).await?,
};
match get_gsm_decision(gsm) {
storage_enums::GsmDecision::Retry => {
retries = get_retries(
state,
retries,
platform.get_processor().get_account().get_id(),
business_profile,
)
.await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]);
logger::info!("retries exhausted for auto_retry payment");
break;
}
if connector_routing_data.len() == 0 {
logger::info!("connectors exhausted for auto_retry payment");
metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(1, &[]);
break;
}
let is_network_token = payment_data
.get_payment_method_data()
.map(|pmd| pmd.is_network_token_payment_method_data())
.unwrap_or(false);
let clear_pan_possible = initial_gsm
.and_then(|data| data.feature_data.get_retry_feature_data())
.map(|data| data.is_clear_pan_possible())
.unwrap_or(false);
let should_retry_with_pan = is_network_token
&& clear_pan_possible
&& business_profile.is_clear_pan_retries_enabled;
// Currently we are taking off_session as a source of truth to identify MIT payments.
let is_mit_payment = payment_data
.get_payment_intent()
.off_session
.unwrap_or(false);
let (connector, routing_decision) = if is_mit_payment {
let connector_routing_data =
super::get_connector_data(&mut connector_routing_data)?;
let payment_method_info = payment_data
.get_payment_method_info()
.get_required_value("payment_method_info")?
.clone();
let mandate_reference_id = payments::get_mandate_reference_id(
connector_routing_data.action_type.clone(),
connector_routing_data.clone(),
payment_data,
&payment_method_info,
)?;
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id, //mandate_ref_id
});
(connector_routing_data.connector_data, None)
} else if should_retry_with_pan {
// If should_retry_with_pan is true, it indicates that we are retrying with PAN using the same connector.
(original_connector_data.clone(), None)
} else {
let connector_routing_data =
super::get_connector_data(&mut connector_routing_data)?;
let routing_decision = connector_routing_data.network.map(|card_network| {
routing_helpers::RoutingDecisionData::get_debit_routing_decision_data(
card_network,
None,
)
});
(connector_routing_data.connector_data, routing_decision)
};
router_data = do_retry(
&state.clone(),
req_state.clone(),
&connector,
operation,
customer,
platform,
payment_data,
router_data,
validate_result,
schedule_time,
//this is an auto retry payment, but not step-up
false,
frm_suggestion,
business_profile,
should_retry_with_pan,
routing_decision,
)
.await?;
retries = retries.map(|i| i - 1);
}
storage_enums::GsmDecision::DoDefault => break,
}
initial_gsm = None;
}
}
Ok(router_data)
}
#[instrument(skip_all)]
pub async fn is_step_up_enabled_for_merchant_connector(
state: &app::SessionState,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: types::Connector,
) -> bool {
let key = merchant_id.get_step_up_enabled_key();
let db = &*state.store;
db.find_config_by_key_unwrap_or(key.as_str(), Some("[]".to_string()))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|step_up_config| {
serde_json::from_str::<Vec<types::Connector>>(&step_up_config.config)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Step-up config parsing failed")
})
.map_err(|err| {
logger::error!(step_up_config_error=?err);
})
.ok()
.map(|connectors_enabled| connectors_enabled.contains(&connector_name))
.unwrap_or(false)
}
#[cfg(feature = "v1")]
pub async fn get_merchant_max_auto_retries_enabled(
db: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,
) -> Option<i32> {
let key = merchant_id.get_max_auto_retries_enabled();
db.find_config_by_key(key.as_str())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|retries_config| {
retries_config
.config
.parse::<i32>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Retries config parsing failed")
})
.map_err(|err| {
logger::error!(retries_error=?err);
None::<i32>
})
.ok()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn get_retries(
state: &app::SessionState,
retries: Option<i32>,
merchant_id: &common_utils::id_type::MerchantId,
profile: &domain::Profile,
) -> Option<i32> {
match retries {
Some(retries) => Some(retries),
None => get_merchant_max_auto_retries_enabled(state.store.as_ref(), merchant_id)
.await
.or(profile.max_auto_retries_enabled.map(i32::from)),
}
}
#[instrument(skip_all)]
pub async fn get_gsm<F, FData>(
state: &app::SessionState,
router_data: &types::RouterData<F, FData, types::PaymentsResponseData>,
) -> RouterResult<Option<hyperswitch_domain_models::gsm::GatewayStatusMap>> {
let error_response = router_data.response.as_ref().err();
let error_code = error_response.map(|err| err.code.to_owned());
let error_message = error_response.map(|err| err.message.to_owned());
let connector_name = router_data.connector.to_string();
let subflow = get_flow_name::<F>()?;
Ok(payments::helpers::get_gsm_record(
state,
error_code,
error_message,
connector_name,
consts::PAYMENT_FLOW_STR,
subflow.as_str(),
)
.await)
}
#[instrument(skip_all)]
pub fn get_gsm_decision(
option_gsm: Option<hyperswitch_domain_models::gsm::GatewayStatusMap>,
) -> storage_enums::GsmDecision {
let option_gsm_decision = option_gsm
.as_ref()
.map(|gsm| gsm.feature_data.get_decision());
if option_gsm_decision.is_some() {
metrics::AUTO_RETRY_GSM_MATCH_COUNT.add(1, &[]);
}
option_gsm_decision.unwrap_or_default()
}
#[inline]
fn get_flow_name<F>() -> RouterResult<String> {
Ok(std::any::type_name::<F>()
.to_string()
.rsplit("::")
.next()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Flow stringify failed")?
.to_string())
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn do_retry<'a, F, ApiRequest, FData, D>(
state: &'a routes::SessionState,
req_state: ReqState,
connector: &'a api::ConnectorData,
operation: &'a operations::BoxedOperation<'a, F, ApiRequest, D>,
customer: &'a Option<domain::Customer>,
platform: &domain::Platform,
payment_data: &'a mut D,
router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
is_step_up: bool,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
routing_decision: Option<routing_helpers::RoutingDecisionData>,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
F: Clone + Send + Sync + std::fmt::Debug + 'static,
FData: Send + Sync + types::Capturable + Clone + 'static + serde::Serialize,
payments::PaymentResponse: operations::Operation<F, FData>,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
D: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
{
metrics::AUTO_RETRY_PAYMENT_COUNT.add(1, &[]);
modify_trackers(
state,
connector.connector_name.to_string(),
payment_data,
platform.get_processor().get_key_store(),
platform.get_processor().get_account().storage_scheme,
router_data,
is_step_up,
)
.await?;
let (merchant_connector_account, router_data, tokenization_action) =
payments::call_connector_service_prerequisites(
state,
platform,
connector.clone(),
operation,
payment_data,
customer,
validate_result,
business_profile,
should_retry_with_pan,
routing_decision,
)
.await?;
let (router_data, _mca) = payments::decide_unified_connector_service_call(
state,
req_state,
platform,
connector.clone(),
operation,
payment_data,
customer,
payments::CallConnectorAction::Trigger,
None,
validate_result,
schedule_time,
hyperswitch_domain_models::payments::HeaderPayload::default(),
frm_suggestion,
business_profile,
true,
None,
merchant_connector_account,
router_data,
tokenization_action,
)
.await?;
Ok(router_data)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn modify_trackers<F, FData, D>(
state: &routes::SessionState,
connector: String,
payment_data: &mut D,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
is_step_up: bool,
) -> RouterResult<()>
where
F: Clone + Send,
FData: Send,
D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync,
{
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn modify_trackers<F, FData, D>(
state: &routes::SessionState,
connector: String,
payment_data: &mut D,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
is_step_up: bool,
) -> RouterResult<()>
where
F: Clone + Send,
FData: Send + types::Capturable,
D: payments::OperationSessionGetters<F> + payments::OperationSessionSetters<F> + Send + Sync,
{
let new_attempt_count = payment_data.get_payment_intent().attempt_count + 1;
let new_payment_attempt = make_new_payment_attempt(
connector,
payment_data.get_payment_attempt().clone(),
new_attempt_count,
is_step_up,
payment_data.get_payment_intent().setup_future_usage,
);
let db = &*state.store;
let additional_payment_method_data_intermediate =
payments::helpers::update_additional_payment_data_with_connector_response_pm_data(
payment_data
.get_payment_attempt()
.payment_method_data
.clone(),
router_data
.connector_response
.clone()
.and_then(|connector_response| connector_response.additional_payment_method_data),
)?;
let key_manager_state = &state.into();
// If the additional PM data is sensitive, encrypt it and populate encrypted_payment_method_data; otherwise populate additional_payment_method_data
let (additional_payment_method_data, encrypted_payment_method_data) =
payments::helpers::get_payment_method_data_and_encrypted_payment_method_data(
payment_data.get_payment_attempt(),
key_manager_state,
key_store,
additional_payment_method_data_intermediate,
)
.await?;
let debit_routing_savings = payment_data.get_payment_method_data().and_then(|data| {
payments::helpers::get_debit_routing_savings_amount(
data,
payment_data.get_payment_attempt(),
)
});
match router_data.response {
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id,
connector_metadata,
redirection_data,
charges,
..
}) => {
let encoded_data = payment_data.get_payment_attempt().encoded_data.clone();
let authentication_data = (*redirection_data)
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not parse the connector response")?;
let payment_attempt_update = storage::PaymentAttemptUpdate::ResponseUpdate {
status: router_data.status,
connector: None,
connector_transaction_id: match resource_id {
types::ResponseId::NoResponseId => None,
types::ResponseId::ConnectorTransactionId(id)
| types::ResponseId::EncodedData(id) => Some(id),
},
connector_response_reference_id: payment_data
.get_payment_attempt()
.connector_response_reference_id
.clone(),
authentication_type: None,
payment_method_id: payment_data.get_payment_attempt().payment_method_id.clone(),
mandate_id: payment_data
.get_mandate_id()
.and_then(|mandate| mandate.mandate_id.clone()),
connector_metadata,
payment_token: None,
error_code: None,
error_message: None,
error_reason: None,
amount_capturable: if router_data.status.is_terminal_status() {
Some(MinorUnit::new(0))
} else {
None
},
updated_by: storage_scheme.to_string(),
authentication_data,
encoded_data,
unified_code: None,
unified_message: None,
capture_before: None,
extended_authorization_applied: None,
extended_authorization_last_applied_at: None,
payment_method_data: additional_payment_method_data,
encrypted_payment_method_data,
connector_mandate_detail: None,
charges,
setup_future_usage_applied: None,
debit_routing_savings,
network_transaction_id: payment_data
.get_payment_attempt()
.network_transaction_id
.clone(),
is_overcapture_enabled: None,
authorized_amount: router_data.authorized_amount,
tokenization: None,
};
#[cfg(feature = "v1")]
db.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
db.update_payment_attempt_with_attempt_id(
key_manager_state,
key_store,
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
Ok(_) => {
logger::error!("unexpected response: this response was not expected in Retry flow");
return Ok(());
}
Err(ref error_response) => {
let option_gsm = get_gsm(state, &router_data).await?;
let auth_update = if Some(router_data.auth_type)
!= payment_data.get_payment_attempt().authentication_type
{
Some(router_data.auth_type)
} else {
None
};
let payment_attempt_update = storage::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
error_code: Some(Some(error_response.code.clone())),
error_message: Some(Some(error_response.message.clone())),
status: storage_enums::AttemptStatus::Failure,
error_reason: Some(error_response.reason.clone()),
amount_capturable: Some(MinorUnit::new(0)),
updated_by: storage_scheme.to_string(),
unified_code: option_gsm.clone().map(|gsm| gsm.unified_code),
unified_message: option_gsm.map(|gsm| gsm.unified_message),
connector_transaction_id: error_response.connector_transaction_id.clone(),
payment_method_data: additional_payment_method_data,
encrypted_payment_method_data,
authentication_type: auth_update,
issuer_error_code: error_response.network_decline_code.clone(),
issuer_error_message: error_response.network_error_message.clone(),
network_details: Some(ForeignFrom::foreign_from(error_response)),
};
#[cfg(feature = "v1")]
db.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
db.update_payment_attempt_with_attempt_id(
key_manager_state,
key_store,
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
}
#[cfg(feature = "v1")]
let payment_attempt = db
.insert_payment_attempt(new_payment_attempt, storage_scheme, key_store)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting payment attempt")?;
#[cfg(feature = "v2")]
let payment_attempt = db
.insert_payment_attempt(key_store, new_payment_attempt, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting payment attempt")?;
// update payment_attempt, connector_response and payment_intent in payment_data
payment_data.set_payment_attempt(payment_attempt);
let payment_intent = db
.update_payment_intent(
payment_data.get_payment_intent().clone(),
storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {
active_attempt_id: payment_data.get_payment_attempt().get_id().to_owned(),
attempt_count: new_attempt_count,
updated_by: storage_scheme.to_string(),
},
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.set_payment_intent(payment_intent);
Ok(())
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub fn make_new_payment_attempt(
connector: String,
old_payment_attempt: storage::PaymentAttempt,
new_attempt_count: i16,
is_step_up: bool,
setup_future_usage_intent: Option<storage_enums::FutureUsage>,
) -> storage::PaymentAttempt {
let created_at @ modified_at @ last_synced = common_utils::date_time::now();
storage::PaymentAttempt {
connector: Some(connector),
attempt_id: old_payment_attempt
.payment_id
.get_attempt_id(new_attempt_count),
payment_id: old_payment_attempt.payment_id,
merchant_id: old_payment_attempt.merchant_id,
status: old_payment_attempt.status,
currency: old_payment_attempt.currency,
save_to_locker: old_payment_attempt.save_to_locker,
offer_amount: old_payment_attempt.offer_amount,
payment_method_id: old_payment_attempt.payment_method_id,
payment_method: old_payment_attempt.payment_method,
payment_method_type: old_payment_attempt.payment_method_type,
capture_method: old_payment_attempt.capture_method,
capture_on: old_payment_attempt.capture_on,
confirm: old_payment_attempt.confirm,
authentication_type: if is_step_up {
Some(storage_enums::AuthenticationType::ThreeDs)
} else {
old_payment_attempt.authentication_type
},
amount_to_capture: old_payment_attempt.amount_to_capture,
mandate_id: old_payment_attempt.mandate_id,
browser_info: old_payment_attempt.browser_info,
payment_token: old_payment_attempt.payment_token,
client_source: old_payment_attempt.client_source,
client_version: old_payment_attempt.client_version,
created_at,
modified_at,
last_synced: Some(last_synced),
profile_id: old_payment_attempt.profile_id,
organization_id: old_payment_attempt.organization_id,
net_amount: old_payment_attempt.net_amount,
error_message: Default::default(),
cancellation_reason: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
customer_acceptance: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
extended_authorization_last_applied_at: Default::default(),
capture_before: Default::default(),
card_discovery: old_payment_attempt.card_discovery,
processor_merchant_id: old_payment_attempt.processor_merchant_id,
created_by: old_payment_attempt.created_by,
setup_future_usage_applied: setup_future_usage_intent, // setup future usage is picked from intent for new payment attempt
routing_approach: old_payment_attempt.routing_approach,
connector_request_reference_id: Default::default(),
network_transaction_id: old_payment_attempt.network_transaction_id,
network_details: Default::default(),
is_stored_credential: old_payment_attempt.is_stored_credential,
authorized_amount: old_payment_attempt.authorized_amount,
tokenization: Default::default(),
encrypted_payment_method_data: Default::default(),
connector_transaction_id: Default::default(),
charge_id: Default::default(),
charges: Default::default(),
issuer_error_code: Default::default(),
issuer_error_message: Default::default(),
debit_routing_savings: Default::default(),
is_overcapture_enabled: Default::default(),
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub fn make_new_payment_attempt(
_connector: String,
_old_payment_attempt: storage::PaymentAttempt,
_new_attempt_count: i16,
_is_step_up: bool,
) -> storage::PaymentAttempt {
todo!()
}
pub async fn get_merchant_config_for_gsm(
db: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,
) -> bool {
let config = db
.find_config_by_key_unwrap_or(
&merchant_id.get_should_call_gsm_key(),
Some("false".to_string()),
)
.await;
match config {
Ok(conf) => conf.config == "true",
Err(error) => {
logger::error!(?error);
false
}
}
}
#[cfg(feature = "v1")]
pub async fn config_should_call_gsm(
db: &dyn StorageInterface,
merchant_id: &common_utils::id_type::MerchantId,
profile: &domain::Profile,
) -> bool {
let merchant_config_gsm = get_merchant_config_for_gsm(db, merchant_id).await;
let profile_config_gsm = profile.is_auto_retries_enabled;
merchant_config_gsm || profile_config_gsm
}
pub trait GsmValidation<F: Send + Clone + Sync, FData: Send + Sync, Resp> {
// TODO : move this function to appropriate place later.
fn should_call_gsm(&self) -> bool;
}
impl<F: Send + Clone + Sync, FData: Send + Sync>
GsmValidation<F, FData, types::PaymentsResponseData>
for types::RouterData<F, FData, types::PaymentsResponseData>
{
#[inline(always)]
fn should_call_gsm(&self) -> bool {
if self.response.is_err() {
true
} else {
match self.status {
storage_enums::AttemptStatus::Started
| storage_enums::AttemptStatus::AuthenticationPending
| storage_enums::AttemptStatus::AuthenticationSuccessful
| storage_enums::AttemptStatus::Authorized
| storage_enums::AttemptStatus::Charged
| storage_enums::AttemptStatus::Authorizing
| storage_enums::AttemptStatus::CodInitiated
| storage_enums::AttemptStatus::Voided
| storage_enums::AttemptStatus::VoidedPostCharge
| storage_enums::AttemptStatus::VoidInitiated
| storage_enums::AttemptStatus::CaptureInitiated
| storage_enums::AttemptStatus::RouterDeclined
| storage_enums::AttemptStatus::VoidFailed
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/tokenization.rs | crates/router/src/core/payments/tokenization.rs | use std::collections::HashMap;
use ::payment_methods::controller::PaymentMethodsController;
use api_models::payments::ConnectorMandateReferenceId;
use common_enums::{ConnectorMandateStatus, PaymentMethod};
use common_types::callback_mapper::CallbackMapperData;
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, Encode, ValueExt},
id_type,
metrics::utils::record_operation_time,
pii,
};
use diesel_models::business_profile::ExternalVaultConnectorDetails;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payment_method_data::{
get_applepay_wallet_info, get_googlepay_wallet_info,
};
#[cfg(feature = "v1")]
use hyperswitch_domain_models::{
callback_mapper::CallbackMapper,
mandates::{CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord},
payment_method_data,
};
use hyperswitch_interfaces::api::gateway;
use masking::{ExposeInterface, Secret};
use router_env::{instrument, tracing};
use super::helpers;
#[cfg(feature = "v1")]
use crate::core::payment_methods::{
get_payment_method_custom_data, vault_payment_method_external_v1,
};
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},
mandate,
payment_methods::{
self,
cards::{create_encrypted_data, PmCards},
network_tokenization,
},
payments::{self, gateway::context as gateway_context},
},
logger,
routes::{metrics, SessionState},
services,
types::{
self,
api::{self, CardDetailFromLocker, PaymentMethodCreateExt},
domain, payment_methods as pm_types,
storage::enums as storage_enums,
},
utils::{generate_id, OptionExt},
};
#[cfg(feature = "v1")]
async fn save_in_locker(
state: &SessionState,
platform: &domain::Platform,
payment_method_request: api::PaymentMethodCreate,
card_detail: Option<api::CardDetail>,
business_profile: &domain::Profile,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
match &business_profile.external_vault_details {
domain::ExternalVaultDetails::ExternalVaultEnabled(external_vault_details) => {
logger::info!("External vault is enabled, using vault_payment_method_external_v1");
Box::pin(save_in_locker_external(
state,
platform,
payment_method_request,
card_detail,
external_vault_details,
))
.await
}
domain::ExternalVaultDetails::Skip => {
// Use internal vault (locker)
save_in_locker_internal(state, platform, payment_method_request, card_detail).await
}
}
}
pub struct SavePaymentMethodData<Req> {
request: Req,
response: Result<types::PaymentsResponseData, types::ErrorResponse>,
payment_method_token: Option<types::PaymentMethodToken>,
payment_method: PaymentMethod,
attempt_status: common_enums::AttemptStatus,
}
impl<F, Req: Clone> From<&types::RouterData<F, Req, types::PaymentsResponseData>>
for SavePaymentMethodData<Req>
{
fn from(router_data: &types::RouterData<F, Req, types::PaymentsResponseData>) -> Self {
Self {
request: router_data.request.clone(),
response: router_data.response.clone(),
payment_method_token: router_data.payment_method_token.clone(),
payment_method: router_data.payment_method,
attempt_status: router_data.status,
}
}
}
pub struct SavePaymentMethodDataResponse {
pub payment_method_id: Option<String>,
pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
pub connector_mandate_reference_id: Option<ConnectorMandateReferenceId>,
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn save_payment_method<FData>(
state: &SessionState,
connector_name: String,
save_payment_method_data: SavePaymentMethodData<FData>,
customer_id: Option<id_type::CustomerId>,
platform: &domain::Platform,
payment_method_type: Option<storage_enums::PaymentMethodType>,
billing_name: Option<Secret<String>>,
payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>,
business_profile: &domain::Profile,
mut original_connector_mandate_reference_id: Option<ConnectorMandateReferenceId>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>,
payment_method_info: Option<domain::PaymentMethod>,
payment_method_token: Option<hyperswitch_domain_models::router_data::PaymentMethodToken>,
) -> RouterResult<SavePaymentMethodDataResponse>
where
FData: mandate::MandateBehaviour + Clone,
{
let mut pm_status = None;
let cards = PmCards {
state,
provider: platform.get_provider(),
};
match save_payment_method_data.response {
Ok(responses) => {
let db = &*state.store;
let token_store = state
.conf
.tokenization
.0
.get(&connector_name.to_string())
.map(|token_filter| token_filter.long_lived_token)
.unwrap_or(false);
let network_transaction_id = match &responses {
types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => {
network_txn_id.clone()
}
_ => None,
};
let network_transaction_id =
if save_payment_method_data.request.get_setup_future_usage()
== Some(storage_enums::FutureUsage::OffSession)
{
if network_transaction_id.is_some() {
network_transaction_id
} else {
logger::info!("Skip storing network transaction id");
None
}
} else {
None
};
let connector_token = if token_store {
let tokens = save_payment_method_data
.payment_method_token
.to_owned()
.get_required_value("payment_token")?;
let token = match tokens {
types::PaymentMethodToken::Token(connector_token) => connector_token.expose(),
types::PaymentMethodToken::ApplePayDecrypt(_) => {
Err(errors::ApiErrorResponse::NotSupported {
message: "Apple Pay Decrypt token is not supported".to_string(),
})?
}
types::PaymentMethodToken::PazeDecrypt(_) => {
Err(errors::ApiErrorResponse::NotSupported {
message: "Paze Decrypt token is not supported".to_string(),
})?
}
types::PaymentMethodToken::GooglePayDecrypt(_) => {
Err(errors::ApiErrorResponse::NotSupported {
message: "Google Pay Decrypt token is not supported".to_string(),
})?
}
};
Some((connector_name, token))
} else {
None
};
let mandate_data_customer_acceptance = save_payment_method_data
.request
.get_setup_mandate_details()
.and_then(|mandate_data| mandate_data.customer_acceptance.clone());
let customer_acceptance = save_payment_method_data
.request
.get_customer_acceptance()
.or(mandate_data_customer_acceptance.clone())
.map(|ca| ca.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize customer acceptance to value")?;
let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) =
match responses {
types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
} => {
if let Some(ref mandate_ref) = *mandate_reference {
(
mandate_ref.connector_mandate_id.clone(),
mandate_ref.mandate_metadata.clone(),
mandate_ref.connector_mandate_request_reference_id.clone(),
)
} else {
(None, None, None)
}
}
_ => (None, None, None),
};
let pm_id = if customer_acceptance.is_some() {
let payment_method_data =
save_payment_method_data.request.get_payment_method_data();
let payment_method_create_request =
payment_methods::get_payment_method_create_request(
Some(&payment_method_data),
Some(save_payment_method_data.payment_method),
payment_method_type,
&customer_id.clone(),
billing_name,
payment_method_billing_address,
)
.await?;
let payment_methods_data =
&save_payment_method_data.request.get_payment_method_data();
let co_badged_card_data = payment_methods_data.get_co_badged_card_data();
let customer_id = customer_id.to_owned().get_required_value("customer_id")?;
let merchant_id = platform.get_processor().get_account().get_id();
let is_network_tokenization_enabled =
business_profile.is_network_tokenization_enabled;
let (
(mut resp, duplication_check, network_token_requestor_ref_id),
network_token_resp,
) = if !state.conf.locker.locker_enabled {
let (res, dc) = skip_saving_card_in_locker(
platform,
payment_method_create_request.to_owned(),
)
.await?;
((res, dc, None), None)
} else {
let payment_method_status = common_enums::PaymentMethodStatus::from(
save_payment_method_data.attempt_status,
);
pm_status = Some(payment_method_status);
save_card_and_network_token_in_locker(
state,
customer_id.clone(),
payment_method_status,
payment_method_data.clone(),
vault_operation,
payment_method_info,
platform,
payment_method_create_request.clone(),
is_network_tokenization_enabled,
business_profile,
)
.await?
};
let network_token_locker_id = match network_token_resp {
Some(ref token_resp) => {
if network_token_requestor_ref_id.is_some() {
Some(token_resp.payment_method_id.clone())
} else {
None
}
}
None => None,
};
let optional_pm_details = match (resp.card.as_ref(), payment_method_data) {
(Some(card), _) => Some(domain::PaymentMethodsData::Card(
domain::CardDetailsPaymentMethod::from((card.clone(), co_badged_card_data)),
)),
(
_,
domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(applepay)),
) => Some(domain::PaymentMethodsData::WalletDetails(
get_applepay_wallet_info(applepay, payment_method_token.clone()),
)),
(
_,
domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay(googlepay)),
) => Some(domain::PaymentMethodsData::WalletDetails(
get_googlepay_wallet_info(googlepay, payment_method_token),
)),
(_, domain::PaymentMethodData::BankDebit(bank_debit_data)) => bank_debit_data
.get_bank_debit_details()
.map(domain::PaymentMethodsData::BankDebit),
_ => None,
};
let key_manager_state = state.into();
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> =
optional_pm_details
.async_map(|pm| {
create_encrypted_data(
&key_manager_state,
platform.get_processor().get_key_store(),
pm,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_network_token_data_encrypted: Option<
Encryptable<Secret<serde_json::Value>>,
> = match network_token_resp {
Some(token_resp) => {
let pm_token_details = token_resp.card.as_ref().map(|card| {
domain::PaymentMethodsData::Card(
domain::CardDetailsPaymentMethod::from((card.clone(), None)),
)
});
pm_token_details
.async_map(|pm_card| {
create_encrypted_data(
&key_manager_state,
platform.get_processor().get_key_store(),
pm_card,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?
}
None => None,
};
let encrypted_payment_method_billing_address: Option<
Encryptable<Secret<serde_json::Value>>,
> = payment_method_billing_address
.async_map(|address| {
create_encrypted_data(
&key_manager_state,
platform.get_processor().get_key_store(),
address.clone(),
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method billing address")?;
let mut payment_method_id = resp.payment_method_id.clone();
let mut locker_id = None;
let (external_vault_details, vault_type) = match &business_profile.external_vault_details{
hyperswitch_domain_models::business_profile::ExternalVaultDetails::ExternalVaultEnabled(external_vault_connector_details) => {
(Some(external_vault_connector_details), Some(common_enums::VaultType::External))
},
hyperswitch_domain_models::business_profile::ExternalVaultDetails::Skip => (None, Some(common_enums::VaultType::Internal)),
};
let external_vault_mca_id = external_vault_details
.map(|connector_details| connector_details.vault_connector_id.clone());
let vault_source_details = domain::PaymentMethodVaultSourceDetails::try_from((
vault_type,
external_vault_mca_id,
))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create vault source details")?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::transformers::DataDuplicationCheck::Duplicated => {
let payment_method = {
let existing_pm_by_pmid = db
.find_payment_method(
platform.get_processor().get_key_store(),
&payment_method_id,
platform.get_processor().get_account().storage_scheme,
)
.await;
if let Err(err) = existing_pm_by_pmid {
if err.current_context().is_db_not_found() {
locker_id = Some(payment_method_id.clone());
let existing_pm_by_locker_id = db
.find_payment_method_by_locker_id(
platform.get_processor().get_key_store(),
&payment_method_id,
platform
.get_processor()
.get_account()
.storage_scheme,
)
.await;
match &existing_pm_by_locker_id {
Ok(pm) => {
payment_method_id.clone_from(&pm.payment_method_id);
}
Err(_) => {
payment_method_id =
generate_id(consts::ID_LENGTH, "pm")
}
};
existing_pm_by_locker_id
} else {
Err(err)
}
} else {
existing_pm_by_pmid
}
};
resp.payment_method_id = payment_method_id;
match payment_method {
Ok(pm) => {
let pm_metadata = create_payment_method_metadata(
pm.metadata.as_ref(),
connector_token,
)?;
payment_methods::cards::update_payment_method_metadata_and_last_used(
platform.get_processor().get_key_store(),
db,
pm.clone(),
pm_metadata,
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
}
Err(err) => {
if err.current_context().is_db_not_found() {
let pm_metadata =
create_payment_method_metadata(None, connector_token)?;
cards
.create_payment_method(
&payment_method_create_request,
&customer_id,
&resp.payment_method_id,
locker_id,
merchant_id,
pm_metadata,
customer_acceptance,
pm_data_encrypted,
None,
pm_status,
network_transaction_id,
encrypted_payment_method_billing_address,
resp.card.and_then(|card| {
card.card_network.map(|card_network| {
card_network.to_string()
})
}),
network_token_requestor_ref_id,
network_token_locker_id,
pm_network_token_data_encrypted,
Some(vault_source_details),
)
.await
} else {
Err(err)
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable("Error while finding payment method")
}?;
}
};
}
payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = payment_method_create_request.card.clone() {
let payment_method = {
let existing_pm_by_pmid = db
.find_payment_method(
platform.get_processor().get_key_store(),
&payment_method_id,
platform.get_processor().get_account().storage_scheme,
)
.await;
if let Err(err) = existing_pm_by_pmid {
if err.current_context().is_db_not_found() {
locker_id = Some(payment_method_id.clone());
let existing_pm_by_locker_id = db
.find_payment_method_by_locker_id(
platform.get_processor().get_key_store(),
&payment_method_id,
platform
.get_processor()
.get_account()
.storage_scheme,
)
.await;
match &existing_pm_by_locker_id {
Ok(pm) => {
payment_method_id
.clone_from(&pm.payment_method_id);
}
Err(_) => {
payment_method_id =
generate_id(consts::ID_LENGTH, "pm")
}
};
existing_pm_by_locker_id
} else {
Err(err)
}
} else {
existing_pm_by_pmid
}
};
resp.payment_method_id = payment_method_id;
let existing_pm = match payment_method {
Ok(pm) => {
let mandate_details = pm
.connector_mandate_details
.clone()
.map(|val| {
val.parse_value::<PaymentsMandateReference>(
"PaymentsMandateReference",
)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
if let Some((mandate_details, merchant_connector_id)) =
mandate_details.zip(merchant_connector_id)
{
let connector_mandate_details =
update_connector_mandate_details_status(
merchant_connector_id,
mandate_details,
ConnectorMandateStatus::Inactive,
)?;
payment_methods::cards::update_payment_method_connector_mandate_details(
platform.get_processor().get_key_store(),
db,
pm.clone(),
connector_mandate_details,
platform.get_processor().get_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
}
Ok(pm)
}
Err(err) => {
if err.current_context().is_db_not_found() {
cards
.create_payment_method(
&payment_method_create_request,
&customer_id,
&resp.payment_method_id,
locker_id,
merchant_id,
resp.metadata.clone().map(|val| val.expose()),
customer_acceptance,
pm_data_encrypted,
None,
pm_status,
network_transaction_id,
encrypted_payment_method_billing_address,
resp.card.and_then(|card| {
card.card_network.map(|card_network| {
card_network.to_string()
})
}),
network_token_requestor_ref_id,
network_token_locker_id,
pm_network_token_data_encrypted,
Some(vault_source_details),
)
.await
} else {
Err(err)
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"Error while finding payment method",
)
}
}
}?;
cards
.delete_card_from_locker(
&customer_id,
merchant_id,
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = cards
.add_card_hs(
payment_method_create_request,
&card,
&customer_id,
Some(
existing_pm
.locker_id
.as_ref()
.unwrap_or(&existing_pm.payment_method_id),
),
)
.await;
if let Err(err) = add_card_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
platform.get_processor().get_key_store(),
merchant_id,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/routing/utils.rs | crates/router/src/core/payments/routing/utils.rs | use std::{
collections::{HashMap, HashSet},
str::FromStr,
sync::LazyLock,
};
use api_models::{
open_router as or_types,
routing::{
self as api_routing, ComparisonType, ConnectorSelection, ConnectorVolumeSplit,
DeRoutableConnectorChoice, MetadataValue, NumberComparison, RoutableConnectorChoice,
RoutingEvaluateRequest, RoutingEvaluateResponse, ValueType,
},
};
use async_trait::async_trait;
use common_enums::TransactionType;
use common_utils::{
ext_traits::{BytesExt, StringExt},
id_type,
};
use diesel_models::{enums, routing_algorithm};
use error_stack::ResultExt;
use euclid::{
backend::BackendInput,
enums::RoutableConnectors,
frontend::{
ast::{self},
dir::{self, transformers::IntoDirValue},
},
};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use external_services::grpc_client::dynamic_routing as ir_client;
use hyperswitch_domain_models::business_profile;
use hyperswitch_interfaces::events::routing_api_logs as routing_events;
use router_env::RequestId;
use serde::{Deserialize, Serialize};
use super::RoutingResult;
use crate::{
core::errors,
db::domain,
routes::{app::SessionStateInfo, SessionState},
services::{self, logger},
types::transformers::ForeignInto,
};
// New Trait for handling Euclid API calls
#[async_trait]
pub trait DecisionEngineApiHandler {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>, // Option to handle GET/DELETE requests without body
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone;
}
// Struct to implement the DecisionEngineApiHandler trait
pub struct EuclidApiClient;
pub struct ConfigApiClient;
pub struct SRApiClient;
pub async fn build_and_send_decision_engine_http_request<Req, Res, ErrRes>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
_timeout: Option<u64>,
context_message: &str,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + std::fmt::Debug + Clone + 'static,
ErrRes: serde::de::DeserializeOwned + std::fmt::Debug + Clone + DecisionEngineErrorsInterface,
{
let decision_engine_base_url = &state.conf.open_router.url;
let url = format!("{decision_engine_base_url}/{path}");
logger::debug!(decision_engine_api_call_url = %url, decision_engine_request_path = %path, http_method = ?http_method, "decision_engine: Initiating decision_engine API call ({})", context_message);
let mut request_builder = services::RequestBuilder::new()
.method(http_method)
.url(&url);
if let Some(body_content) = request_body {
let body = common_utils::request::RequestContent::Json(Box::new(body_content));
request_builder = request_builder.set_body(body);
}
let http_request = request_builder.build();
logger::info!(?http_request, decision_engine_request_path = %path, "decision_engine: Constructed Decision Engine API request details ({})", context_message);
let should_parse_response = events_wrapper
.as_ref()
.map(|wrapper| wrapper.parse_response)
.unwrap_or(true);
let closure = || async {
let response =
services::call_connector_api(state, http_request, "Decision Engine API call")
.await
.change_context(errors::RoutingError::OpenRouterCallFailed)?;
match response {
Ok(resp) => {
logger::debug!(
"decision_engine: Received response from Decision Engine API ({:?})",
String::from_utf8_lossy(&resp.response) // For logging
);
let resp = should_parse_response
.then(|| {
if std::any::TypeId::of::<Res>() == std::any::TypeId::of::<String>()
&& resp.response.is_empty()
{
return serde_json::from_str::<Res>("\"\"").change_context(
errors::RoutingError::OpenRouterError(
"Failed to parse empty response as String".into(),
),
);
}
let response_type: Res = resp
.response
.parse_struct(std::any::type_name::<Res>())
.change_context(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))?;
Ok::<_, error_stack::Report<errors::RoutingError>>(response_type)
})
.transpose()?;
logger::debug!("decision_engine_success_response: {:?}", resp);
Ok(resp)
}
Err(err) => {
logger::debug!(
"decision_engine: Received response from Decision Engine API ({:?})",
String::from_utf8_lossy(&err.response) // For logging
);
let err_resp: ErrRes = err
.response
.parse_struct(std::any::type_name::<ErrRes>())
.change_context(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))?;
logger::error!(
decision_engine_error_code = %err_resp.get_error_code(),
decision_engine_error_message = %err_resp.get_error_message(),
decision_engine_raw_response = ?err_resp.get_error_data(),
);
Err(error_stack::report!(
errors::RoutingError::RoutingEventsError {
message: err_resp.get_error_message(),
status_code: err.status_code,
}
))
}
}
};
let events_response = if let Some(wrapper) = events_wrapper {
wrapper
.construct_event_builder(
url,
routing_events::RoutingEngine::DecisionEngine,
routing_events::ApiMethod::Rest(http_method),
)?
.trigger_event(state, closure)
.await?
} else {
let resp = closure()
.await
.change_context(errors::RoutingError::OpenRouterCallFailed)?;
RoutingEventsResponse::new(None, resp)
};
Ok(events_response)
}
#[async_trait]
impl DecisionEngineApiHandler for EuclidApiClient {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>, // Option to handle GET/DELETE requests without body
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone,
{
let event_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>(
state,
http_method,
path,
request_body,
timeout,
"parsing response",
events_wrapper,
)
.await?;
let parsed_response =
event_response
.response
.as_ref()
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), euclid_request_path = %path, "decision_engine_euclid: Successfully parsed response from Euclid API");
Ok(event_response)
}
}
#[async_trait]
impl DecisionEngineApiHandler for ConfigApiClient {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone,
{
let events_response = build_and_send_decision_engine_http_request::<_, _, DeErrorResponse>(
state,
http_method,
path,
request_body,
timeout,
"parsing response",
events_wrapper,
)
.await?;
let parsed_response =
events_response
.response
.as_ref()
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API");
Ok(events_response)
}
}
#[async_trait]
impl DecisionEngineApiHandler for SRApiClient {
async fn send_decision_engine_request<Req, Res>(
state: &SessionState,
http_method: services::Method,
path: &str,
request_body: Option<Req>,
timeout: Option<u64>,
events_wrapper: Option<RoutingEventsWrapper<Req>>,
) -> RoutingResult<RoutingEventsResponse<Res>>
where
Req: Serialize + Send + Sync + 'static + Clone,
Res: Serialize + serde::de::DeserializeOwned + Send + 'static + std::fmt::Debug + Clone,
{
let events_response =
build_and_send_decision_engine_http_request::<_, _, or_types::ErrorResponse>(
state,
http_method,
path,
request_body,
timeout,
"parsing response",
events_wrapper,
)
.await?;
let parsed_response =
events_response
.response
.as_ref()
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(parsed_response = ?parsed_response, response_type = %std::any::type_name::<Res>(), decision_engine_request_path = %path, "decision_engine_config: Successfully parsed response from Decision Engine config API");
Ok(events_response)
}
}
const EUCLID_API_TIMEOUT: u64 = 5;
pub async fn perform_decision_euclid_routing(
state: &SessionState,
input: BackendInput,
created_by: String,
events_wrapper: RoutingEventsWrapper<RoutingEvaluateRequest>,
fallback_output: Vec<RoutableConnectorChoice>,
) -> RoutingResult<RoutingEvaluateResponse> {
logger::debug!("decision_engine_euclid: evaluate api call for euclid routing evaluation");
let mut events_wrapper = events_wrapper;
let fallback_output = fallback_output
.into_iter()
.map(|c| DeRoutableConnectorChoice {
gateway_name: c.connector,
gateway_id: c.merchant_connector_id,
})
.collect::<Vec<_>>();
let routing_request =
convert_backend_input_to_routing_eval(created_by, input, fallback_output)?;
events_wrapper.set_request_body(routing_request.clone());
let event_response = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
"routing/evaluate",
Some(routing_request),
Some(EUCLID_API_TIMEOUT),
Some(events_wrapper),
)
.await?;
let euclid_response: RoutingEvaluateResponse =
event_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
let mut routing_event =
event_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message: "Routing event not found in EventsResponse".to_string(),
status_code: 500,
})?;
routing_event.set_routing_approach(RoutingApproach::StaticRouting.to_string());
routing_event.set_routable_connectors(euclid_response.evaluated_output.clone());
state.event_handler.log_event(&routing_event);
logger::debug!(decision_engine_euclid_response=?euclid_response,"decision_engine_euclid");
logger::debug!(decision_engine_euclid_selected_connector=?euclid_response.evaluated_output,"decision_engine_euclid");
Ok(euclid_response)
}
/// This function transforms the decision_engine response in a way that's usable for further flows:
/// It places evaluated_output connectors first, followed by remaining output connectors (no duplicates).
pub fn transform_de_output_for_router(
de_output: Vec<ConnectorInfo>,
de_evaluated_output: Vec<RoutableConnectorChoice>,
) -> RoutingResult<Vec<RoutableConnectorChoice>> {
let mut seen = HashSet::new();
// evaluated connectors on top, to ensure the fallback is based on other connectors.
let mut ordered = Vec::with_capacity(de_output.len() + de_evaluated_output.len());
for eval_conn in de_evaluated_output {
if seen.insert(eval_conn.connector) {
ordered.push(eval_conn);
}
}
// Add remaining connectors from de_output (only if not already seen), for fallback
for conn in de_output {
let key = RoutableConnectors::from_str(&conn.gateway_name).map_err(|_| {
errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
}
})?;
if seen.insert(key) {
let de_choice = DeRoutableConnectorChoice::try_from(conn)?;
ordered.push(RoutableConnectorChoice::from(de_choice));
}
}
Ok(ordered)
}
pub async fn decision_engine_routing(
state: &SessionState,
backend_input: BackendInput,
business_profile: &domain::Profile,
payment_id: String,
merchant_fallback_config: Vec<RoutableConnectorChoice>,
) -> RoutingResult<Vec<RoutableConnectorChoice>> {
let routing_events_wrapper = RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id.clone(),
payment_id,
business_profile.get_id().to_owned(),
business_profile.merchant_id.to_owned(),
"DecisionEngine: Euclid Static Routing".to_string(),
None,
true,
false,
);
let de_euclid_evaluate_response = perform_decision_euclid_routing(
state,
backend_input.clone(),
business_profile.get_id().get_string_repr().to_string(),
routing_events_wrapper,
merchant_fallback_config,
)
.await;
let Ok(de_euclid_response) = de_euclid_evaluate_response else {
logger::error!("decision_engine_euclid_evaluation_error: error in evaluation of rule");
return Ok(Vec::default());
};
let de_output_connector = extract_de_output_connectors(de_euclid_response.output)
.map_err(|e| {
logger::error!(error=?e, "decision_engine_euclid_evaluation_error: Failed to extract connector from Output");
e
})?;
transform_de_output_for_router(
de_output_connector.clone(),
de_euclid_response.evaluated_output.clone(),
)
.map_err(|e| {
logger::error!(error=?e, "decision_engine_euclid_evaluation_error: failed to transform connector from de-output");
e
})
}
/// Custom deserializer for output from decision_engine, this is required as untagged enum is
/// stored but the enum requires tagged deserialization, hence deserializing it into specific
/// variants
pub fn extract_de_output_connectors(
output_value: serde_json::Value,
) -> RoutingResult<Vec<ConnectorInfo>> {
const SINGLE: &str = "straight_through";
const PRIORITY: &str = "priority";
const VOLUME_SPLIT: &str = "volume_split";
const VOLUME_SPLIT_PRIORITY: &str = "volume_split_priority";
let obj = output_value.as_object().ok_or_else(|| {
logger::error!("decision_engine_euclid_error: output is not a JSON object");
errors::RoutingError::OpenRouterError("Expected output to be a JSON object".into())
})?;
let type_str = obj.get("type").and_then(|v| v.as_str()).ok_or_else(|| {
logger::error!("decision_engine_euclid_error: missing or invalid 'type' in output");
errors::RoutingError::OpenRouterError("Missing or invalid 'type' field in output".into())
})?;
match type_str {
SINGLE => {
let connector_value = obj.get("connector").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'connector' field for type=single"
);
errors::RoutingError::OpenRouterError(
"Missing 'connector' field for single output".into(),
)
})?;
let connector: ConnectorInfo = serde_json::from_value(connector_value.clone())
.map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse single connector"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize single connector".into(),
)
})?;
Ok(vec![connector])
}
PRIORITY => {
let connectors_value = obj.get("connectors").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'connectors' field for type=priority"
);
errors::RoutingError::OpenRouterError(
"Missing 'connectors' field for priority output".into(),
)
})?;
let connectors: Vec<ConnectorInfo> = serde_json::from_value(connectors_value.clone())
.map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse connectors for priority"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize priority connectors".into(),
)
})?;
Ok(connectors)
}
VOLUME_SPLIT => {
let splits_value = obj.get("splits").ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: missing 'splits' field for type=volume_split"
);
errors::RoutingError::OpenRouterError(
"Missing 'splits' field for volume_split output".into(),
)
})?;
// Transform each {connector, split} into {output, split}
let fixed_splits: Vec<_> = splits_value
.as_array()
.ok_or_else(|| {
logger::error!("decision_engine_euclid_error: 'splits' is not an array");
errors::RoutingError::OpenRouterError("'splits' field must be an array".into())
})?
.iter()
.map(|entry| {
let mut entry_map = entry.as_object().cloned().ok_or_else(|| {
logger::error!(
"decision_engine_euclid_error: invalid split entry in volume_split"
);
errors::RoutingError::OpenRouterError(
"Invalid entry in splits array".into(),
)
})?;
if let Some(connector) = entry_map.remove("connector") {
entry_map.insert("output".to_string(), connector);
}
Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(
entry_map,
))
})
.collect::<Result<Vec<_>, _>>()?;
let splits: Vec<VolumeSplit<ConnectorInfo>> =
serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse volume_split"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize volume_split connectors".into(),
)
})?;
Ok(splits.into_iter().map(|s| s.output).collect())
}
VOLUME_SPLIT_PRIORITY => {
let splits_value = obj.get("splits").ok_or_else(|| {
logger::error!("decision_engine_euclid_error: missing 'splits' field for type=volume_split_priority");
errors::RoutingError::OpenRouterError("Missing 'splits' field for volume_split_priority output".into())
})?;
// Transform each {connector: [...], split} into {output: [...], split}
let fixed_splits: Vec<_> = splits_value
.as_array()
.ok_or_else(|| {
logger::error!("decision_engine_euclid_error: 'splits' is not an array");
errors::RoutingError::OpenRouterError("'splits' field must be an array".into())
})?
.iter()
.map(|entry| {
let mut entry_map = entry.as_object().cloned().ok_or_else(|| {
logger::error!("decision_engine_euclid_error: invalid split entry in volume_split_priority");
errors::RoutingError::OpenRouterError("Invalid entry in splits array".into())
})?;
if let Some(connector) = entry_map.remove("connector") {
entry_map.insert("output".to_string(), connector);
}
Ok::<_, error_stack::Report<errors::RoutingError>>(serde_json::Value::Object(entry_map))
})
.collect::<Result<Vec<_>, _>>()?;
let splits: Vec<VolumeSplit<Vec<ConnectorInfo>>> =
serde_json::from_value(serde_json::Value::Array(fixed_splits)).map_err(|e| {
logger::error!(
?e,
"decision_engine_euclid_error: Failed to parse volume_split_priority"
);
errors::RoutingError::OpenRouterError(
"Failed to deserialize volume_split_priority connectors".into(),
)
})?;
Ok(splits.into_iter().flat_map(|s| s.output).collect())
}
other => {
logger::error!(type_str=%other, "decision_engine_euclid_error: unknown output type");
Err(
errors::RoutingError::OpenRouterError(format!("Unknown output type: {other}"))
.into(),
)
}
}
}
pub async fn create_de_euclid_routing_algo(
state: &SessionState,
routing_request: &RoutingRule,
) -> RoutingResult<String> {
logger::debug!("decision_engine_euclid: create api call for euclid routing rule creation");
logger::debug!(decision_engine_euclid_request=?routing_request,"decision_engine_euclid");
let events_response = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
"routing/create",
Some(routing_request.clone()),
Some(EUCLID_API_TIMEOUT),
None,
)
.await?;
let euclid_response: RoutingDictionaryRecord =
events_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
logger::debug!(decision_engine_euclid_parsed_response=?euclid_response,"decision_engine_euclid");
Ok(euclid_response.rule_id)
}
pub async fn link_de_euclid_routing_algorithm(
state: &SessionState,
routing_request: ActivateRoutingConfigRequest,
) -> RoutingResult<()> {
logger::debug!("decision_engine_euclid: link api call for euclid routing algorithm");
EuclidApiClient::send_decision_engine_request::<_, String>(
state,
services::Method::Post,
"routing/activate",
Some(routing_request.clone()),
Some(EUCLID_API_TIMEOUT),
None,
)
.await?;
logger::debug!(decision_engine_euclid_activated=?routing_request, "decision_engine_euclid: link_de_euclid_routing_algorithm completed");
Ok(())
}
pub async fn list_de_euclid_routing_algorithms(
state: &SessionState,
routing_list_request: ListRountingAlgorithmsRequest,
) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> {
logger::debug!("decision_engine_euclid: list api call for euclid routing algorithms");
let created_by = routing_list_request.created_by;
let events_response = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
format!("routing/list/{created_by}").as_str(),
None::<()>,
Some(EUCLID_API_TIMEOUT),
None,
)
.await?;
let euclid_response: Vec<RoutingAlgorithmRecord> =
events_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
Ok(euclid_response
.into_iter()
.map(routing_algorithm::RoutingProfileMetadata::from)
.map(ForeignInto::foreign_into)
.collect::<Vec<_>>())
}
pub async fn list_de_euclid_active_routing_algorithm(
state: &SessionState,
created_by: String,
) -> RoutingResult<Vec<api_routing::RoutingDictionaryRecord>> {
logger::debug!("decision_engine_euclid: list api call for euclid active routing algorithm");
let response: Vec<RoutingAlgorithmRecord> = EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
format!("routing/list/active/{created_by}").as_str(),
None::<()>,
Some(EUCLID_API_TIMEOUT),
None,
)
.await?
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
Ok(response
.into_iter()
.map(|record| routing_algorithm::RoutingProfileMetadata::from(record).foreign_into())
.collect())
}
pub fn compare_and_log_result<T: RoutingEq<T> + Serialize>(
de_result: Vec<T>,
result: Vec<T>,
flow: String,
) {
let is_equal = if de_result.is_empty() && result.is_empty() {
true
} else {
de_result
.iter()
.zip(result.iter())
.all(|(a, b)| T::is_equal(a, b))
};
let is_equal_in_length = de_result.len() == result.len();
router_env::logger::debug!(
routing_flow=?flow,
is_equal=?is_equal,
is_equal_length=?is_equal_in_length,
de_response=?to_json_string(&de_result),
hs_response=?to_json_string(&result),
"decision_engine_euclid"
);
}
pub trait RoutingEq<T> {
fn is_equal(a: &T, b: &T) -> bool;
}
impl RoutingEq<Self> for api_routing::RoutingDictionaryRecord {
fn is_equal(a: &Self, b: &Self) -> bool {
a.id == b.id
&& a.name == b.name
&& a.profile_id == b.profile_id
&& a.description == b.description
&& a.kind == b.kind
&& a.algorithm_for == b.algorithm_for
}
}
impl RoutingEq<Self> for String {
fn is_equal(a: &Self, b: &Self) -> bool {
a.to_lowercase() == b.to_lowercase()
}
}
impl RoutingEq<Self> for RoutableConnectorChoice {
fn is_equal(a: &Self, b: &Self) -> bool {
a.connector.eq(&b.connector)
&& a.choice_kind.eq(&b.choice_kind)
&& a.merchant_connector_id.eq(&b.merchant_connector_id)
}
}
pub fn to_json_string<T: Serialize>(value: &T) -> String {
serde_json::to_string(value)
.map_err(|_| errors::RoutingError::GenericConversionError {
from: "T".to_string(),
to: "JsonValue".to_string(),
})
.unwrap_or_default()
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ActivateRoutingConfigRequest {
pub created_by: String,
pub routing_algorithm_id: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListRountingAlgorithmsRequest {
pub created_by: String,
}
// Maps Hyperswitch `BackendInput` to a `RoutingEvaluateRequest` compatible with Decision Engine
pub fn convert_backend_input_to_routing_eval(
created_by: String,
input: BackendInput,
fallback_output: Vec<DeRoutableConnectorChoice>,
) -> RoutingResult<RoutingEvaluateRequest> {
let mut params: HashMap<String, Option<ValueType>> = HashMap::new();
// Payment
params.insert(
"amount".to_string(),
Some(ValueType::Number(
input
.payment
.amount
.get_amount_as_i64()
.try_into()
.unwrap_or_default(),
)),
);
params.insert(
"currency".to_string(),
Some(ValueType::EnumVariant(input.payment.currency.to_string())),
);
if let Some(auth_type) = input.payment.authentication_type {
params.insert(
"authentication_type".to_string(),
Some(ValueType::EnumVariant(auth_type.to_string())),
);
}
if let Some(extended_bin) = input.payment.extended_card_bin {
params.insert(
"extended_card_bin".to_string(),
Some(ValueType::StrValue(extended_bin)),
);
}
if let Some(bin) = input.payment.card_bin {
params.insert("card_bin".to_string(), Some(ValueType::StrValue(bin)));
}
if let Some(capture_method) = input.payment.capture_method {
params.insert(
"capture_method".to_string(),
Some(ValueType::EnumVariant(capture_method.to_string())),
);
}
if let Some(country) = input.payment.business_country {
params.insert(
"business_country".to_string(),
Some(ValueType::EnumVariant(country.to_string())),
);
}
if let Some(country) = input.payment.billing_country {
params.insert(
"billing_country".to_string(),
Some(ValueType::EnumVariant(country.to_string())),
);
}
if let Some(label) = input.payment.business_label {
params.insert(
"business_label".to_string(),
Some(ValueType::StrValue(label)),
);
}
if let Some(sfu) = input.payment.setup_future_usage {
params.insert(
"setup_future_usage".to_string(),
Some(ValueType::EnumVariant(sfu.to_string())),
);
}
// PaymentMethod
if let Some(pm) = input.payment_method.payment_method {
params.insert(
"payment_method".to_string(),
Some(ValueType::EnumVariant(pm.to_string())),
);
if let Some(pmt) = input.payment_method.payment_method_type {
match (pmt, pm).into_dir_value() {
Ok(dv) => insert_dirvalue_param(&mut params, dv),
Err(e) => logger::debug!(
?e,
?pmt,
?pm,
"decision_engine_euclid: into_dir_value failed; skipping subset param"
),
}
}
}
if let Some(pmt) = input.payment_method.payment_method_type {
params.insert(
"payment_method_type".to_string(),
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/routing/transformers.rs | crates/router/src/core/payments/routing/transformers.rs | use std::collections::HashMap;
use api_models::{self, routing as routing_types};
use common_types::payments as common_payments_types;
use diesel_models::enums as storage_enums;
use euclid::{enums as dsl_enums, frontend::ast as dsl_ast};
use kgraph_utils::types;
use crate::{
configs::settings,
types::transformers::{ForeignFrom, ForeignInto},
};
impl ForeignFrom<routing_types::RoutableConnectorChoice> for dsl_ast::ConnectorChoice {
fn foreign_from(from: routing_types::RoutableConnectorChoice) -> Self {
Self {
connector: from.connector,
}
}
}
impl ForeignFrom<storage_enums::CaptureMethod> for Option<dsl_enums::CaptureMethod> {
fn foreign_from(value: storage_enums::CaptureMethod) -> Self {
match value {
storage_enums::CaptureMethod::Automatic => Some(dsl_enums::CaptureMethod::Automatic),
storage_enums::CaptureMethod::SequentialAutomatic => {
Some(dsl_enums::CaptureMethod::SequentialAutomatic)
}
storage_enums::CaptureMethod::Manual => Some(dsl_enums::CaptureMethod::Manual),
_ => None,
}
}
}
impl ForeignFrom<common_payments_types::AcceptanceType> for dsl_enums::MandateAcceptanceType {
fn foreign_from(from: common_payments_types::AcceptanceType) -> Self {
match from {
common_payments_types::AcceptanceType::Online => Self::Online,
common_payments_types::AcceptanceType::Offline => Self::Offline,
}
}
}
impl ForeignFrom<api_models::payments::MandateType> for dsl_enums::MandateType {
fn foreign_from(from: api_models::payments::MandateType) -> Self {
match from {
api_models::payments::MandateType::MultiUse(_) => Self::MultiUse,
api_models::payments::MandateType::SingleUse(_) => Self::SingleUse,
}
}
}
impl ForeignFrom<storage_enums::MandateDataType> for dsl_enums::MandateType {
fn foreign_from(from: storage_enums::MandateDataType) -> Self {
match from {
storage_enums::MandateDataType::MultiUse(_) => Self::MultiUse,
storage_enums::MandateDataType::SingleUse(_) => Self::SingleUse,
}
}
}
impl ForeignFrom<settings::PaymentMethodFilterKey> for types::PaymentMethodFilterKey {
fn foreign_from(from: settings::PaymentMethodFilterKey) -> Self {
match from {
settings::PaymentMethodFilterKey::PaymentMethodType(pmt) => {
Self::PaymentMethodType(pmt)
}
settings::PaymentMethodFilterKey::CardNetwork(cn) => Self::CardNetwork(cn),
}
}
}
impl ForeignFrom<settings::CurrencyCountryFlowFilter> for types::CurrencyCountryFlowFilter {
fn foreign_from(from: settings::CurrencyCountryFlowFilter) -> Self {
Self {
currency: from.currency,
country: from.country,
not_available_flows: from.not_available_flows.map(ForeignInto::foreign_into),
}
}
}
impl ForeignFrom<settings::NotAvailableFlows> for types::NotAvailableFlows {
fn foreign_from(from: settings::NotAvailableFlows) -> Self {
Self {
capture_method: from.capture_method,
}
}
}
impl ForeignFrom<settings::PaymentMethodFilters> for types::PaymentMethodFilters {
fn foreign_from(from: settings::PaymentMethodFilters) -> Self {
let iter_map = from
.0
.into_iter()
.map(|(key, val)| (key.foreign_into(), val.foreign_into()))
.collect::<HashMap<_, _>>();
Self(iter_map)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/external_proxy_flow.rs | crates/router/src/core/payments/flows/external_proxy_flow.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums as enums;
use common_utils::{id_type, ucs_types, ucs_types::UcsReferenceId};
use error_stack::ResultExt;
use external_services::grpc_client;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentConfirmData;
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse, payments as domain_payments,
};
use hyperswitch_interfaces::api::gateway;
use masking::ExposeInterface;
use unified_connector_service_client::payments as payments_grpc;
use unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterface;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, gateway::context as gateway_context, helpers,
session_token, tokenization, transformers, PaymentData,
},
unified_connector_service::{self, ucs_logging_wrapper},
},
logger,
routes::{metrics, SessionState},
services::{self, api::ConnectorValidation},
types::{
self, api, domain,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
> for PaymentConfirmData<api::ExternalVaultProxy>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
>,
> {
Box::pin(
transformers::construct_external_vault_proxy_payment_router_data(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
),
)
.await
}
}
#[async_trait]
impl Feature<api::ExternalVaultProxy, types::ExternalVaultProxyPaymentsData>
for types::ExternalVaultProxyPaymentsRouterData
{
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
gateway_context: gateway_context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
logger::debug!(auth_type=?self.auth_type);
let mut auth_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
// External vault proxy doesn't use integrity checks
auth_router_data.integrity_check = Ok(());
metrics::PAYMENT_COUNT.add(1, &[]);
Ok(auth_router_data)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
access_token::add_access_token(state, connector, self, creds_identifier, gateway_context)
.await
}
async fn add_session_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<()>
where
Self: Sized,
{
self.session_token =
session_token::add_session_token_if_needed(self, state, connector, gateway_context)
.await?;
Ok(())
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::PaymentMethodTokenResult> {
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
gateway_context,
)
.await
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
todo!()
}
async fn postprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
todo!()
}
async fn create_connector_customer<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self)?,
gateway_context,
)
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
connector
.connector
.validate_connector_against_payment_request(
self.request.capture_method,
self.payment_method,
self.request.payment_method_type,
)
.to_payment_failed_response()?;
// Check if the connector supports mandate payment
// if the payment_method_type does not support mandate for the given connector, downgrade the setup future usage to on session
if self.request.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
&& !self
.request
.payment_method_type
.and_then(|payment_method_type| {
state
.conf
.mandates
.supported_payment_methods
.0
.get(&enums::PaymentMethod::from(payment_method_type))
.and_then(|supported_pm_for_mandates| {
supported_pm_for_mandates.0.get(&payment_method_type).map(
|supported_connector_for_mandates| {
supported_connector_for_mandates
.connector_list
.contains(&connector.connector_name)
},
)
})
})
.unwrap_or(false)
{
// downgrade the setup future usage to on session
self.request.setup_future_usage =
Some(diesel_models::enums::FutureUsage::OnSession);
};
// External vault proxy doesn't use regular payment method validation
// Skip mandate payment validation for external vault proxy
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExternalVaultProxy,
types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
metrics::EXECUTE_PRETASK_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("flow", format!("{:?}", api::ExternalVaultProxy)),
),
);
logger::debug!(completed_pre_tasks=?true);
// External vault proxy always proceeds
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
}
_ => Ok((None, true)),
}
}
async fn create_order_at_connector(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
should_continue_payment: bool,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<types::CreateOrderResult>> {
if connector
.connector_name
.requires_order_creation_before_payment(self.payment_method)
&& should_continue_payment
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CreateOrder,
types::CreateOrderRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let request_data = types::CreateOrderRequestData::try_from(self.request.clone())?;
let response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let createorder_router_data =
helpers::router_data_type_conversion::<_, api::CreateOrder, _, _, _, _>(
self.clone(),
request_data,
response_data,
);
let resp = gateway::execute_payment_gateway(
state,
connector_integration,
&createorder_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
gateway_context.clone(),
)
.await
.to_payment_failed_response()?;
let create_order_resp = match resp.response {
Ok(res) => {
if let types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id } =
res
{
Ok(order_id)
} else {
Err(error_stack::report!(ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Unexpected response format from connector: {res:?}",
)))?
}
}
Err(error) => Err(error),
};
Ok(Some(types::CreateOrderResult {
create_order_result: create_order_resp,
should_continue_further: should_continue_payment,
}))
} else {
// If the connector does not require order creation, return None
Ok(None)
}
}
fn update_router_data_with_create_order_response(
&mut self,
create_order_result: types::CreateOrderResult,
) {
match create_order_result.create_order_result {
Ok(order_id) => {
self.request.order_id = Some(order_id.clone()); // ? why this is assigned here and ucs also wants this to populate data
}
Err(_err) => (),
}
}
#[cfg(feature = "v2")]
async fn call_unified_connector_service_with_external_vault_proxy<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
external_vault_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
platform: &domain::Platform,
unified_connector_service_execution_mode: enums::ExecutionMode,
merchant_order_reference_id: Option<String>,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_authorize_request =
payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&*self)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata =
unified_connector_service::build_unified_connector_service_auth_metadata(
merchant_connector_account,
platform,
self.connector.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let external_vault_proxy_metadata =
unified_connector_service::build_unified_connector_service_external_vault_proxy_metadata(
external_vault_merchant_connector_account
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct external vault proxy metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.or(merchant_order_reference_id)
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let headers_builder = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(Some(external_vault_proxy_metadata))
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
let (updated_router_data, _) = Box::pin(ucs_logging_wrapper(
self.clone(),
state,
payment_authorize_request.clone(),
headers_builder,
|mut router_data, payment_authorize_request, grpc_headers| async move {
let response = Box::pin(client
.payment_authorize(
payment_authorize_request,
connector_auth_metadata,
grpc_headers,
))
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_authorize_response = response.into_inner();
let ucs_data =
unified_connector_service::handle_unified_connector_service_response_for_payment_authorize(
payment_authorize_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = ucs_data.router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_authorize_response
.raw_connector_response
.clone()
.map(|raw_connector_response| raw_connector_response.expose().into());
router_data.connector_http_status_code = Some(ucs_data.status_code);
Ok((router_data,(), payment_authorize_response))
}
)).await?;
// Copy back the updated data
*self = updated_router_data;
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/update_metadata_flow.rs | crates/router/src/core/payments/flows/update_metadata_flow.rs | use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> for PaymentData<api::UpdateMetadata>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsUpdateMetadataRouterData> {
Box::pin(
transformers::construct_payment_router_data_for_update_metadata(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
),
)
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsUpdateMetadataRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::UpdateMetadata, types::PaymentsUpdateMetadataData>
for types::RouterData<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
_gateway_context: payments::gateway::context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/authorize_flow.rs | crates/router/src/core/payments/flows/authorize_flow.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums as enums;
use common_types::payments as common_payments_types;
#[cfg(feature = "v2")]
use common_utils::types::MinorUnit;
use common_utils::{errors, ext_traits::ValueExt, id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentConfirmData;
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse, payments as domain_payments,
router_data_v2::PaymentFlowData, router_response_types,
};
use hyperswitch_interfaces::{
api::{self as api_interface, gateway, ConnectorSpecifications},
errors as interface_errors,
unified_connector_service::transformers as ucs_transformers,
};
use masking::ExposeInterface;
use unified_connector_service_client::payments as payments_grpc;
use unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterface;
// use router_env::tracing::Instrument;
use super::{ConstructFlowSpecificData, Feature};
#[cfg(feature = "v2")]
use crate::core::unified_connector_service::{
get_access_token_from_ucs_response,
handle_unified_connector_service_response_for_payment_authorize,
handle_unified_connector_service_response_for_payment_repeat, set_access_token_for_ucs,
ucs_logging_wrapper,
};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, flows::gateway_context, gateway as payments_gateway,
helpers, session_token, tokenization, transformers, PaymentData,
},
unified_connector_service::{
self, build_unified_connector_service_auth_metadata, ucs_logging_wrapper_granular,
},
},
logger,
routes::{metrics, SessionState},
services::{self, api::ConnectorValidation},
types::{self, api, domain, transformers::ForeignTryFrom},
utils::OptionExt,
};
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> for PaymentConfirmData<api::Authorize>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
> {
Box::pin(transformers::construct_payment_router_data_for_authorize(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
async fn get_merchant_recipient_data<'a>(
&self,
state: &SessionState,
platform: &domain::Platform,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
connector: &api::ConnectorData,
) -> RouterResult<Option<types::MerchantRecipientData>> {
let is_open_banking = &self
.payment_attempt
.get_payment_method()
.get_required_value("PaymentMethod")?
.eq(&enums::PaymentMethod::OpenBanking);
if *is_open_banking {
payments::get_merchant_bank_data_for_open_banking_connectors(
merchant_connector_account,
platform,
connector,
state,
)
.await
} else {
Ok(None)
}
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> for PaymentData<api::Authorize>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<
types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
> {
Box::pin(transformers::construct_payment_router_data::<
api::Authorize,
types::PaymentsAuthorizeData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
async fn get_merchant_recipient_data<'a>(
&self,
state: &SessionState,
platform: &domain::Platform,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
connector: &api::ConnectorData,
) -> RouterResult<Option<types::MerchantRecipientData>> {
match &self.payment_intent.is_payment_processor_token_flow {
Some(true) => Ok(None),
Some(false) | None => {
let is_open_banking = &self
.payment_attempt
.get_payment_method()
.get_required_value("PaymentMethod")?
.eq(&enums::PaymentMethod::OpenBanking);
Ok(if *is_open_banking {
payments::get_merchant_bank_data_for_open_banking_connectors(
merchant_connector_account,
platform,
connector,
state,
)
.await?
} else {
None
})
}
}
}
}
#[async_trait]
impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuthorizeRouterData {
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
gateway_context: gateway_context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
logger::debug!(auth_type=?self.auth_type);
let mut auth_router_data = gateway::execute_payment_gateway(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
return_raw_connector_response,
gateway_context.clone(),
)
.await
.to_payment_failed_response()?;
// Initiating Integrity check
let integrity_result = helpers::check_integrity_based_on_flow(
&auth_router_data.request,
&auth_router_data.response,
);
auth_router_data.integrity_check = integrity_result;
metrics::PAYMENT_COUNT.add(1, &[]); // Move outside of the if block
match auth_router_data.response.clone() {
Err(_) => Ok(auth_router_data),
Ok(authorize_response) => {
// Check if the Capture API should be called based on the connector and other parameters
if super::should_initiate_capture_flow(
&connector.connector_name,
self.request.customer_acceptance,
self.request.capture_method,
self.request.setup_future_usage,
auth_router_data.status,
) {
auth_router_data = Box::pin(process_capture_flow(
auth_router_data,
authorize_response,
state,
connector,
call_connector_action.clone(),
business_profile,
header_payload,
gateway_context,
))
.await?;
}
Ok(auth_router_data)
}
}
} else {
Ok(self.clone())
}
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn add_session_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<()>
where
Self: Sized,
{
self.session_token =
session_token::add_session_token_if_needed(self, state, connector, gateway_context)
.await?;
Ok(())
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::PaymentMethodTokenResult> {
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
gateway_context,
)
.await
}
async fn pre_authentication_step<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<(Self, bool)>
where
Self: Sized,
{
if connector.connector.is_pre_authentication_flow_required(
api_interface::CurrentFlowInfo::Authorize {
auth_type: &self.auth_type,
request_data: &self.request,
},
) {
logger::info!(
"Pre-authentication flow is required for connector: {}",
connector.connector_name
);
let authorize_request_data = self.request.clone();
let pre_authenticate_request_data =
types::PaymentsPreAuthenticateData::try_from(self.request.to_owned())?;
let pre_authenticate_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let pre_authenticate_router_data =
helpers::router_data_type_conversion::<_, api::PreAuthenticate, _, _, _, _>(
self.clone(),
pre_authenticate_request_data,
pre_authenticate_response_data,
);
let pre_authenticate_router_data = Box::pin(payments_gateway::handle_gateway_call::<
_,
_,
_,
PaymentFlowData,
_,
>(
state,
pre_authenticate_router_data,
connector,
gateway_context,
))
.await?;
// Convert back to CompleteAuthorize router data while preserving preprocessing response data
let pre_authenticate_response = pre_authenticate_router_data.response.clone();
let authorize_router_data =
helpers::router_data_type_conversion::<_, api::Authorize, _, _, _, _>(
pre_authenticate_router_data,
authorize_request_data,
pre_authenticate_response,
);
let should_continue_after_preauthenticate = match connector.connector_name {
api_models::enums::Connector::Redsys => match &authorize_router_data.response {
Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata,
..
}) => {
let three_ds_invoke_data: Option<
api_models::payments::PaymentsConnectorThreeDsInvokeData,
> = connector_metadata.clone().and_then(|metadata| {
metadata
.parse_value("PaymentsConnectorThreeDsInvokeData")
.ok()
});
three_ds_invoke_data.is_none()
}
_ => false,
},
_ => false,
};
Ok((authorize_router_data, should_continue_after_preauthenticate))
} else {
Ok((self, true))
}
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
authorize_preprocessing_steps(state, &self, true, connector).await
}
async fn postprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
authorize_postprocessing_steps(state, &self, true, connector).await
}
async fn create_connector_customer<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self)?,
gateway_context,
)
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
connector
.connector
.validate_connector_against_payment_request(
self.request.capture_method,
self.payment_method,
self.request.payment_method_type,
)
.to_payment_failed_response()?;
// Check if the connector supports mandate payment
// if the payment_method_type does not support mandate for the given connector, downgrade the setup future usage to on session
if self.request.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
&& !self
.request
.payment_method_type
.and_then(|payment_method_type| {
state
.conf
.mandates
.supported_payment_methods
.0
.get(&enums::PaymentMethod::from(payment_method_type))
.and_then(|supported_pm_for_mandates| {
supported_pm_for_mandates.0.get(&payment_method_type).map(
|supported_connector_for_mandates| {
supported_connector_for_mandates
.connector_list
.contains(&connector.connector_name)
},
)
})
})
.unwrap_or(false)
{
// downgrade the setup future usage to on session
self.request.setup_future_usage =
Some(diesel_models::enums::FutureUsage::OnSession);
};
if crate::connector::utils::PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment(
&self.request,
) {
connector
.connector
.validate_mandate_payment(
self.request.payment_method_type,
self.request.payment_method_data.clone(),
)
.to_payment_failed_response()?;
};
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
metrics::EXECUTE_PRETASK_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("flow", format!("{:?}", api::Authorize)),
),
);
logger::debug!(completed_pre_tasks=?true);
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
logger::debug!(auth_type=?self.auth_type);
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
} else {
Ok((None, false))
}
}
_ => Ok((None, true)),
}
}
async fn create_order_at_connector(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
should_continue_payment: bool,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<types::CreateOrderResult>> {
let is_order_create_bloated_connector = connector.connector.is_order_create_flow_required(
api_interface::CurrentFlowInfo::Authorize {
auth_type: &self.auth_type,
request_data: &self.request,
},
) && state
.conf
.preprocessing_flow_config
.as_ref()
.is_some_and(|config| {
// check order create flow is bloated up for the current connector
config
.order_create_bloated_connectors
.contains(&connector.connector_name)
});
if (connector
.connector_name
.requires_order_creation_before_payment(self.payment_method)
|| is_order_create_bloated_connector)
&& should_continue_payment
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CreateOrder,
types::CreateOrderRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let request_data = types::CreateOrderRequestData::try_from(self.request.clone())?;
let response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let createorder_router_data =
helpers::router_data_type_conversion::<_, api::CreateOrder, _, _, _, _>(
self.clone(),
request_data,
response_data,
);
let order_create_response_router_data = gateway::execute_payment_gateway(
state,
connector_integration,
&createorder_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
gateway_context.clone(),
)
.await
.to_payment_failed_response()?;
let order_create_response = order_create_response_router_data.response.clone();
let create_order_resp = match &order_create_response {
Ok(types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id }) => {
types::CreateOrderResult {
create_order_result: Ok(order_id.clone()),
should_continue_further: should_continue_payment,
}
}
// Some connector return PreProcessingResponse and TransactionResponse response type
// Rest of the match statements are temporary fixes for satisfying current connector side response handling
// Create Order response must always be PaymentsResponseData::PaymentsCreateOrderResponse only
Ok(types::PaymentsResponseData::PreProcessingResponse {
pre_processing_id,
session_token,
..
}) => {
let should_continue_further = if session_token.is_some() {
// if SDK session token is returned in order create response, do not continue and return control to SDK
false
} else {
should_continue_payment
};
types::CreateOrderResult {
create_order_result: Ok(pre_processing_id.get_string_repr().clone()),
should_continue_further,
}
}
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
..
}) => {
let order_id = resource_id
.get_connector_transaction_id()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to get connector_transaction_id during order create",
)?;
let should_continue_further = if redirection_data.is_some() {
// if redirection_data is returned in order create response, do not continue and return control to SDK
false
} else {
should_continue_payment
};
types::CreateOrderResult {
create_order_result: Ok(order_id),
should_continue_further,
}
}
Ok(res) => Err(error_stack::report!(ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Unexpected response format from connector: {res:?}",
)))?,
Err(error) => types::CreateOrderResult {
create_order_result: Err(error.clone()),
should_continue_further: false,
},
};
// persist order create response
*self = helpers::router_data_type_conversion::<_, api::Authorize, _, _, _, _>(
order_create_response_router_data,
self.request.clone(),
order_create_response,
);
Ok(Some(create_order_resp))
} else {
// If the connector does not require order creation, return None
Ok(None)
}
}
fn update_router_data_with_create_order_response(
&mut self,
create_order_result: types::CreateOrderResult,
) {
match create_order_result.create_order_result {
Ok(order_id) => {
self.request.order_id = Some(order_id.clone()); // ? why this is assigned here and ucs also wants this to populate data
}
Err(_err) => (),
}
}
}
pub trait RouterDataAuthorize {
fn decide_authentication_type(&mut self);
/// to decide if we need to proceed with authorize or not, Eg: If any of the pretask returns `redirection_response` then we should not proceed with authorize call
fn should_proceed_with_authorize(&self) -> bool;
}
impl RouterDataAuthorize for types::PaymentsAuthorizeRouterData {
fn decide_authentication_type(&mut self) {
if let hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(
hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(google_pay_data),
) = &self.request.payment_method_data
{
if let Some(assurance_details) = google_pay_data.info.assurance_details.as_ref() {
// Step up the transaction to 3DS when either assurance_details.card_holder_authenticated or assurance_details.account_verified is false
if !assurance_details.card_holder_authenticated
|| !assurance_details.account_verified
{
logger::info!("Googlepay transaction stepped up to 3DS");
self.auth_type = diesel_models::enums::AuthenticationType::ThreeDs;
}
}
}
if self.auth_type == diesel_models::enums::AuthenticationType::ThreeDs
&& !self.request.enrolled_for_3ds
{
self.auth_type = diesel_models::enums::AuthenticationType::NoThreeDs
}
}
/// to decide if we need to proceed with authorize or not, Eg: If any of the pretask returns `redirection_response` then we should not proceed with authorize call
fn should_proceed_with_authorize(&self) -> bool {
match &self.response {
Ok(types::PaymentsResponseData::TransactionResponse {
redirection_data, ..
}) => !redirection_data.is_some(),
_ => true,
}
}
}
impl mandate::MandateBehaviour for types::PaymentsAuthorizeData {
fn get_amount(&self) -> i64 {
self.amount
}
fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds> {
self.mandate_id.as_ref()
}
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData {
self.payment_method_data.clone()
}
fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage> {
self.setup_future_usage
}
fn get_setup_mandate_details(
&self,
) -> Option<&hyperswitch_domain_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) {
self.mandate_id = new_mandate_id;
}
fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance> {
self.customer_acceptance.clone()
}
}
pub async fn authorize_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
metrics::PREPROCESSING_STEPS_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
(
"payment_method_type",
router_data
.request
.payment_method_type
.map(|inner| inner.to_string())
.unwrap_or("null".to_string()),
),
),
);
let mut authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response.clone(),
);
if connector.connector_name == api_models::enums::Connector::Nuvei {
let (enrolled_for_3ds, related_transaction_id) = match &authorize_router_data.response {
Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse {
enrolled_v2,
related_transaction_id,
}) => (*enrolled_v2, related_transaction_id.clone()),
_ => (false, None),
};
authorize_router_data.request.enrolled_for_3ds = enrolled_for_3ds;
authorize_router_data.request.related_transaction_id = related_transaction_id;
} else if connector.connector_name == api_models::enums::Connector::Shift4 {
if resp.request.enrolled_for_3ds {
authorize_router_data.response = resp.response;
authorize_router_data.status = resp.status;
} else {
authorize_router_data.request.enrolled_for_3ds = false;
}
}
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
pub async fn authorize_postprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostProcessing,
types::PaymentsPostProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let postprocessing_request_data =
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/complete_authorize_flow.rs | crates/router/src/core/payments/flows/complete_authorize_flow.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::connector_enums;
use common_utils::{errors, id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
use hyperswitch_domain_models::{
router_data_v2::PaymentFlowData, router_request_types, router_response_types,
};
use hyperswitch_interfaces::{
api as api_interface,
api::{gateway, ConnectorSpecifications},
errors as interface_errors,
unified_connector_service::transformers as ucs_transformers,
};
use masking::{self, ExposeInterface};
use unified_connector_service_client::payments as payments_grpc;
use unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterface;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{
self, access_token, gateway as payments_gateway, gateway::context as gateway_context,
helpers, transformers, PaymentData,
},
unified_connector_service as ucs_core,
},
logger,
routes::{metrics, SessionState},
services,
types::{self, api, domain, transformers::ForeignTryFrom},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> for PaymentData<api::CompleteAuthorize>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
> {
Box::pin(transformers::construct_payment_router_data::<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
> {
todo!()
}
}
#[async_trait]
impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
for types::RouterData<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
gateway_context: gateway_context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let mut complete_authorize_router_data = gateway::execute_payment_gateway(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
None,
gateway_context.clone(),
)
.await
.to_payment_failed_response()?;
match complete_authorize_router_data.response.clone() {
Err(_) => Ok(complete_authorize_router_data),
Ok(complete_authorize_response) => {
// Check if the Capture API should be called based on the connector and other parameters
if super::should_initiate_capture_flow(
&connector.connector_name,
self.request.customer_acceptance,
self.request.capture_method,
self.request.setup_future_usage,
complete_authorize_router_data.status,
) {
complete_authorize_router_data = Box::pin(process_capture_flow(
complete_authorize_router_data,
complete_authorize_response,
state,
connector,
call_connector_action.clone(),
business_profile,
header_payload,
gateway_context,
))
.await?;
}
Ok(complete_authorize_router_data)
}
}
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
_tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::PaymentMethodTokenResult> {
// TODO: remove this and handle it in core
if matches!(connector.connector_name, types::Connector::Payme) {
let request = self.request.clone();
payments::tokenization::add_payment_method_token(
state,
connector,
&payments::TokenizationAction::TokenizeInConnector,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
gateway_context,
)
.await
} else {
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
})
}
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CompleteAuthorize,
types::CompleteAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
complete_authorize_preprocessing_steps(state, &self, true, connector).await
}
async fn authentication_step<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<(Self, bool)>
where
Self: Sized,
{
if connector.connector.is_authentication_flow_required(
api_interface::CurrentFlowInfo::CompleteAuthorize {
request_data: &self.request,
payment_method: Some(self.payment_method),
},
) {
let router_data = self;
logger::info!(
"Authentication flow is required for connector: {}",
connector.connector_name
);
let mut complete_authorize_request_data = router_data.request.clone();
let authenticate_request_data =
types::PaymentsAuthenticateData::try_from(router_data.request.to_owned())?;
let authenticate_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let authenticate_router_data =
helpers::router_data_type_conversion::<_, api::Authenticate, _, _, _, _>(
router_data.clone(),
authenticate_request_data,
authenticate_response_data,
);
// Call UCS for Authenticate flow and store authentication result for next step
let (authenticate_router_data, authentication_data) =
Box::pin(payments_gateway::handle_gateway_call::<
_,
_,
_,
PaymentFlowData,
_,
>(
state,
authenticate_router_data,
connector,
gateway_context,
))
.await?;
// Convert back to CompleteAuthorize router data while preserving preprocessing response data
let authenticate_response = authenticate_router_data.response.clone();
if let Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata, ..
}) = &authenticate_router_data.response
{
connector_metadata.clone_into(&mut complete_authorize_request_data.connector_meta);
};
complete_authorize_request_data.authentication_data = authentication_data;
let complete_authorize_router_data =
helpers::router_data_type_conversion::<_, api::CompleteAuthorize, _, _, _, _>(
authenticate_router_data,
complete_authorize_request_data,
authenticate_response,
);
// check if redirection is not present in the response and attempt status is not AuthenticationFailed
// if condition does not satisfy, then we don't need to proceed further
let should_continue = (matches!(
complete_authorize_router_data.response,
Ok(types::PaymentsResponseData::TransactionResponse {
ref redirection_data,
..
}) if redirection_data.is_none()
) && complete_authorize_router_data.status
!= common_enums::AttemptStatus::AuthenticationFailed);
Ok((complete_authorize_router_data, should_continue))
} else {
Ok((self, true))
}
}
async fn post_authentication_step<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<(Self, bool)>
where
Self: Sized,
{
if connector.connector.is_post_authentication_flow_required(
api_interface::CurrentFlowInfo::CompleteAuthorize {
request_data: &self.request,
payment_method: Some(self.payment_method),
},
) {
let router_data = self;
logger::info!(
"Post-authentication flow is required for connector: {}",
connector.connector_name
);
// Convert CompleteAuthorize to PostAuthenticate for UCS call
let mut complete_authorize_request_data = router_data.request.clone();
let post_authenticate_request_data =
types::PaymentsPostAuthenticateData::try_from(router_data.request.to_owned())?;
let post_authenticate_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let post_authenticate_router_data =
helpers::router_data_type_conversion::<_, api::PostAuthenticate, _, _, _, _>(
router_data.clone(),
post_authenticate_request_data,
post_authenticate_response_data,
);
let (post_authenticate_router_data, authentication_data) =
Box::pin(payments_gateway::handle_gateway_call::<
_,
_,
_,
PaymentFlowData,
_,
>(
state,
post_authenticate_router_data,
connector,
gateway_context,
))
.await?;
// Convert back to CompleteAuthorize router data while preserving preprocessing response data
let post_authenticate_response = post_authenticate_router_data.response.clone();
if let Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata, ..
}) = &post_authenticate_router_data.response
{
connector_metadata.clone_into(&mut complete_authorize_request_data.connector_meta);
};
complete_authorize_request_data.authentication_data = authentication_data;
let complete_authorize_router_data =
helpers::router_data_type_conversion::<_, api::CompleteAuthorize, _, _, _, _>(
post_authenticate_router_data,
complete_authorize_request_data,
post_authenticate_response,
);
// check if redirection is not present in the response and attempt status is not AuthenticationFailed
// if condition does not satisfy, then we don't need to proceed further
let should_continue = matches!(
complete_authorize_router_data.response,
Ok(types::PaymentsResponseData::TransactionResponse {
ref redirection_data,
..
}) if redirection_data.is_none()
) && !matches!(
complete_authorize_router_data.status,
common_enums::AttemptStatus::AuthenticationFailed
| common_enums::AttemptStatus::Failure
);
Ok((complete_authorize_router_data, should_continue))
} else {
Ok((self, true))
}
}
}
fn transform_redirection_response_for_authenticate_flow(
connector: connector_enums::Connector,
response_data: router_response_types::RedirectForm,
) -> errors::CustomResult<
router_response_types::RedirectForm,
ucs_transformers::UnifiedConnectorServiceError,
> {
match (connector, &response_data) {
(
connector_enums::Connector::Cybersource,
router_response_types::RedirectForm::Form {
endpoint,
method: _,
ref form_fields,
},
) => {
let access_token = form_fields.get("access_token").cloned().ok_or(
ucs_transformers::UnifiedConnectorServiceError::MissingRequiredField {
field_name: "access_token",
},
)?;
let step_up_url = form_fields.get("step_up_url").unwrap_or(endpoint).clone();
Ok(
router_response_types::RedirectForm::CybersourceConsumerAuth {
access_token,
step_up_url,
},
)
}
_ => Ok(response_data),
}
}
fn transform_response_for_authenticate_flow(
connector: connector_enums::Connector,
response_data: router_response_types::PaymentsResponseData,
) -> errors::CustomResult<
router_response_types::PaymentsResponseData,
ucs_transformers::UnifiedConnectorServiceError,
> {
match (connector, response_data.clone()) {
(
connector_enums::Connector::Cybersource,
router_response_types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
mandate_reference,
connector_metadata,
network_txn_id,
connector_response_reference_id,
incremental_authorization_allowed,
charges,
},
) => {
let redirection_data = Box::new(
(*redirection_data)
.clone()
.map(|redirection_data| {
transform_redirection_response_for_authenticate_flow(
connector,
redirection_data,
)
})
.transpose()?,
);
Ok(
router_response_types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
mandate_reference,
connector_metadata,
network_txn_id,
connector_response_reference_id,
incremental_authorization_allowed,
charges,
},
)
}
_ => Ok(response_data),
}
}
#[allow(dead_code, clippy::too_many_arguments)]
pub async fn call_unified_connector_service_authenticate(
router_data: &types::RouterData<
api::Authenticate,
types::PaymentsAuthenticateData,
types::PaymentsResponseData,
>,
state: &SessionState,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
platform: &domain::Platform,
connector: connector_enums::Connector,
unified_connector_service_execution_mode: common_enums::ExecutionMode,
merchant_order_reference_id: Option<String>,
) -> errors::CustomResult<
(
types::RouterData<
api::Authenticate,
types::PaymentsAuthenticateData,
types::PaymentsResponseData,
>,
Option<router_request_types::UcsAuthenticationData>,
),
interface_errors::ConnectorError,
> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_authenticate_request =
payments_grpc::PaymentServiceAuthenticateRequest::foreign_try_from(router_data)
.change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata = ucs_core::build_unified_connector_service_auth_metadata(
merchant_connector_account,
platform,
router_data.connector.clone(),
)
.change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.or(merchant_order_reference_id)
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let headers_builder = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
Box::pin(ucs_core::ucs_logging_wrapper_granular(
router_data.clone(),
state,
payment_authenticate_request,
headers_builder,
|mut router_data, payment_authenticate_request, grpc_headers| async move {
let response = client
.payment_authenticate(
payment_authenticate_request,
connector_auth_metadata,
grpc_headers,
)
.await
.attach_printable("Failed to authorize payment")?;
let payment_authenticate_response = response.into_inner();
let (router_data_response, status_code) =
ucs_core::handle_unified_connector_service_response_for_payment_authenticate(
payment_authenticate_response.clone(),
)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
let router_data_response = match router_data_response {
Ok(response) => Ok(transform_response_for_authenticate_flow(
connector, response,
)?),
Err(err) => Err(err),
};
router_data.response = router_data_response;
router_data.raw_connector_response = payment_authenticate_response
.raw_connector_response
.clone()
.map(|raw_connector_response| raw_connector_response.expose().into());
router_data.connector_http_status_code = Some(status_code);
let domain_authentication_data = payment_authenticate_response
.authentication_data
.clone()
.map(|grpc_authentication_data| {
router_request_types::UcsAuthenticationData::foreign_try_from(
grpc_authentication_data,
)
})
.transpose()
.attach_printable("Failed to Convert to domain AuthenticationData")?;
Ok((
router_data,
domain_authentication_data,
payment_authenticate_response,
))
},
))
.await
.change_context(interface_errors::ConnectorError::ResponseHandlingFailed)
}
#[allow(dead_code, clippy::too_many_arguments)]
pub async fn call_unified_connector_service_post_authenticate(
router_data: &types::RouterData<
api::PostAuthenticate,
types::PaymentsPostAuthenticateData,
types::PaymentsResponseData,
>,
state: &SessionState,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
platform: &domain::Platform,
unified_connector_service_execution_mode: common_enums::ExecutionMode,
merchant_order_reference_id: Option<String>,
) -> errors::CustomResult<
(
types::RouterData<
api::PostAuthenticate,
types::PaymentsPostAuthenticateData,
types::PaymentsResponseData,
>,
Option<router_request_types::UcsAuthenticationData>,
),
interface_errors::ConnectorError,
> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_post_authenticate_request =
payments_grpc::PaymentServicePostAuthenticateRequest::foreign_try_from(router_data)
.change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata = ucs_core::build_unified_connector_service_auth_metadata(
merchant_connector_account,
platform,
router_data.connector.clone(),
)
.change_context(interface_errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.or(merchant_order_reference_id)
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let headers_builder = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
Box::pin(ucs_core::ucs_logging_wrapper_granular(
router_data.clone(),
state,
payment_post_authenticate_request,
headers_builder,
|mut router_data, payment_post_authenticate_request, grpc_headers| async move {
let response = client
.payment_post_authenticate(
payment_post_authenticate_request,
connector_auth_metadata,
grpc_headers,
)
.await
.attach_printable("Failed to authorize payment")?;
let payment_post_authenticate_response = response.into_inner();
let (router_data_response, status_code) =
ucs_core::handle_unified_connector_service_response_for_payment_post_authenticate(
payment_post_authenticate_response.clone(),
)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_post_authenticate_response
.raw_connector_response
.clone()
.map(|raw_connector_response| raw_connector_response.expose().into());
router_data.connector_http_status_code = Some(status_code);
let domain_authentication_data = payment_post_authenticate_response
.authentication_data
.clone()
.map(|grpc_authentication_data| {
router_request_types::UcsAuthenticationData::foreign_try_from(
grpc_authentication_data,
)
})
.transpose()
.attach_printable("Failed to Convert to domain AuthenticationData")?;
Ok((
router_data,
domain_authentication_data,
payment_post_authenticate_response,
))
},
))
.await
.change_context(interface_errors::ConnectorError::ResponseHandlingFailed)
}
pub async fn complete_authorize_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
metrics::PREPROCESSING_STEPS_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
),
);
let mut router_data_request = router_data.request.to_owned();
if let Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata, ..
}) = &resp.response
{
connector_metadata.clone_into(&mut router_data_request.connector_meta);
};
let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data_request,
resp.response,
);
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
impl<F>
ForeignTryFrom<types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>>
for types::PaymentsCaptureData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn foreign_try_from(
item: types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: item.connector.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(Self {
amount_to_capture: item.request.amount,
currency: item.request.currency,
connector_transaction_id: types::PaymentsResponseData::get_connector_transaction_id(
&response,
)?,
payment_amount: item.request.amount,
multiple_capture_data: None,
connector_meta: types::PaymentsResponseData::get_connector_metadata(&response)
.map(|secret| secret.expose()),
browser_info: None,
metadata: None,
capture_method: item.request.capture_method,
minor_payment_amount: item.request.minor_amount,
minor_amount_to_capture: item.request.minor_amount,
integrity_object: None,
split_payments: None,
webhook_url: None,
})
}
}
#[allow(clippy::too_many_arguments)]
async fn process_capture_flow(
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/cancel_flow.rs | crates/router/src/core/payments/flows/cancel_flow.rs | use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain},
};
#[cfg(feature = "v1")]
#[async_trait]
impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
for PaymentData<api::Void>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsCancelRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Void,
types::PaymentsCancelData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
for hyperswitch_domain_models::payments::PaymentCancelData<api::Void>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCancelRouterData> {
Box::pin(transformers::construct_router_data_for_cancel(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[async_trait]
impl Feature<api::Void, types::PaymentsCancelData>
for types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
_gateway_context: payments::gateway::context::RouterGatewayContext,
) -> RouterResult<Self> {
metrics::PAYMENT_CANCEL_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Void,
types::PaymentsCancelData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Void,
types::PaymentsCancelData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/post_session_tokens_flow.rs | crates/router/src/core/payments/flows/post_session_tokens_flow.rs | use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
> for PaymentData<api::PostSessionTokens>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsPostSessionTokensRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsPostSessionTokensRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::PostSessionTokens, types::PaymentsPostSessionTokensData>
for types::RouterData<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
_gateway_context: payments::gateway::context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostSessionTokens,
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/cancel_post_capture_flow.rs | crates/router/src/core/payments/flows/cancel_post_capture_flow.rs | use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> for PaymentData<api::PostCaptureVoid>
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_platform: &domain::Platform,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsCancelPostCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[async_trait]
impl Feature<api::PostCaptureVoid, types::PaymentsCancelPostCaptureData>
for types::RouterData<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
_gateway_context: payments::gateway::context::RouterGatewayContext,
) -> RouterResult<Self> {
metrics::PAYMENT_CANCEL_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostCaptureVoid,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/capture_flow.rs | crates/router/src/core/payments/flows/capture_flow.rs | use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
for PaymentData<api::Capture>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Capture,
types::PaymentsCaptureData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
for hyperswitch_domain_models::payments::PaymentCaptureData<api::Capture>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>,
> {
Box::pin(transformers::construct_payment_router_data_for_capture(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[async_trait]
impl Feature<api::Capture, types::PaymentsCaptureData>
for types::RouterData<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
_gateway_context: payments::gateway::context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Capture,
types::PaymentsCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let mut new_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
// Initiating Integrity check
let integrity_result = helpers::check_integrity_based_on_flow(
&new_router_data.request,
&new_router_data.response,
);
new_router_data.integrity_check = integrity_result;
Ok(new_router_data)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Capture,
types::PaymentsCaptureData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/reject_flow.rs | crates/router/src/core/payments/flows/reject_flow.rs | use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::PaymentsResponseData>
for PaymentData<api::Reject>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsRejectRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Reject,
types::PaymentsRejectData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsRejectRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::Reject, types::PaymentsRejectData>
for types::RouterData<api::Reject, types::PaymentsRejectData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
_gateway_context: payments::gateway::context::RouterGatewayContext,
) -> RouterResult<Self> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/incremental_authorization_flow.rs | crates/router/src/core/payments/flows/incremental_authorization_flow.rs | use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> for PaymentData<api::IncrementalAuthorization>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizationData>
for types::RouterData<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
_gateway_context: payments::gateway::context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::IncrementalAuthorization,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/approve_flow.rs | crates/router/src/core/payments/flows/approve_flow.rs | use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{
self, access_token, flows::gateway_context, helpers, transformers, PaymentData,
},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData>
for PaymentData<api::Approve>
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsApproveRouterData> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsApproveRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Approve,
types::PaymentsApproveData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[async_trait]
impl Feature<api::Approve, types::PaymentsApproveData>
for types::RouterData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
_gateway_context: gateway_context::RouterGatewayContext,
) -> RouterResult<Self> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/session_update_flow.rs | crates/router/src/core/payments/flows/session_update_flow.rs | use async_trait::async_trait;
use super::ConstructFlowSpecificData;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, Feature, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> for PaymentData<api::SdkSessionUpdate>
{
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
Box::pin(
transformers::construct_router_data_to_update_calculated_tax::<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
),
)
.await
}
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SdkSessionUpdateRouterData> {
todo!()
}
}
#[async_trait]
impl Feature<api::SdkSessionUpdate, types::SdkPaymentsSessionUpdateData>
for types::RouterData<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
_gateway_context: payments::gateway::context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SdkSessionUpdate,
types::SdkPaymentsSessionUpdateData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/extend_authorization_flow.rs | crates/router/src/core/payments/flows/extend_authorization_flow.rs | use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::{metrics, SessionState},
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> for PaymentData<api::ExtendAuthorization>
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_platform: &domain::Platform,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsExtendAuthorizationRouterData> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsExtendAuthorizationRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[async_trait]
impl Feature<api::ExtendAuthorization, types::PaymentsExtendAuthorizationData>
for types::RouterData<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
>
{
async fn decide_flows<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
_gateway_context: payments::gateway::context::RouterGatewayContext,
) -> RouterResult<Self> {
metrics::PAYMENT_EXTEND_AUTHORIZATION_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::ExtendAuthorization,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/setup_mandate_flow.rs | crates/router/src/core/payments/flows/setup_mandate_flow.rs | use async_trait::async_trait;
use common_enums;
use common_types::payments as common_payments_types;
use hyperswitch_domain_models::payments as domain_payments;
use hyperswitch_interfaces::api::{gateway, ConnectorSpecifications};
use router_env::logger;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, gateway::context as gateway_context, helpers,
session_token, tokenization, transformers, PaymentData,
},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> for PaymentData<api::SetupMandate>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::SetupMandate,
types::SetupMandateRequestData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> for hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(
transformers::construct_payment_router_data_for_setup_mandate(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
),
)
.await
}
}
#[async_trait]
impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::SetupMandateRouterData {
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: domain_payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
gateway_context: gateway_context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
// Change the authentication_type to ThreeDs, for google_pay wallet if card_holder_authenticated or account_verified in assurance_details is false
if let hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(
hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(google_pay_data),
) = &self.request.payment_method_data
{
if let Some(assurance_details) = google_pay_data.info.assurance_details.as_ref() {
// Step up the transaction to 3DS when either assurance_details.card_holder_authenticated or assurance_details.account_verified is false
if !assurance_details.card_holder_authenticated
|| !assurance_details.account_verified
{
logger::info!("Googlepay transaction stepped up to 3DS");
self.auth_type = diesel_models::enums::AuthenticationType::ThreeDs;
}
}
}
let resp = gateway::execute_payment_gateway(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
None,
gateway_context,
)
.await
.to_setup_mandate_failed_response()?;
Ok(resp)
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn add_session_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<()>
where
Self: Sized,
{
self.session_token =
session_token::add_session_token_if_needed(self, state, connector, gateway_context)
.await?;
Ok(())
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::PaymentMethodTokenResult> {
if connector
.connector
.should_call_tokenization_before_setup_mandate()
{
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
gateway_context,
)
.await
} else {
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
})
}
}
async fn create_connector_customer<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self.request.to_owned())?,
gateway_context,
)
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::SetupMandate,
types::SetupMandateRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
}
_ => Ok((None, true)),
}
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
setup_mandate_preprocessing_steps(state, &self, true, connector).await
}
}
impl mandate::MandateBehaviour for types::SetupMandateRequestData {
fn get_amount(&self) -> i64 {
0
}
fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage> {
self.setup_future_usage
}
fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds> {
self.mandate_id.as_ref()
}
fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) {
self.mandate_id = new_mandate_id;
}
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData {
self.payment_method_data.clone()
}
fn get_setup_mandate_details(
&self,
) -> Option<&hyperswitch_domain_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance> {
self.customer_acceptance.clone()
}
}
pub async fn setup_mandate_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>>
{
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.clone())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let mut setup_mandate_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response.clone(),
);
if connector.connector_name == api_models::enums::Connector::Nuvei {
let (enrolled_for_3ds, related_transaction_id) =
match &setup_mandate_router_data.response {
Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse {
enrolled_v2,
related_transaction_id,
}) => (*enrolled_v2, related_transaction_id.clone()),
_ => (false, None),
};
setup_mandate_router_data.request.enrolled_for_3ds = enrolled_for_3ds;
setup_mandate_router_data.request.related_transaction_id = related_transaction_id;
}
Ok(setup_mandate_router_data)
} else {
Ok(router_data.clone())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/psync_flow.rs | crates/router/src/core/payments/flows/psync_flow.rs | use std::collections::HashMap;
use async_trait::async_trait;
use common_enums;
use hyperswitch_domain_models::payments as domain_payments;
use hyperswitch_interfaces::api::gateway;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
connector::utils::RouterData,
core::{
errors::{ApiErrorResponse, ConnectorErrorExt, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::SessionState,
services::{self, api::ConnectorValidation, logger},
types::{self, api, domain},
};
#[cfg(feature = "v1")]
#[async_trait]
impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
for PaymentData<api::PSync>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
> {
Box::pin(transformers::construct_payment_router_data::<
api::PSync,
types::PaymentsSyncData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
None,
None,
))
.await
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
for hyperswitch_domain_models::payments::PaymentStatusData<api::PSync>
{
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
> {
Box::pin(transformers::construct_router_data_for_psync(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[async_trait]
impl Feature<api::PSync, types::PaymentsSyncData>
for types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
gateway_context: payments::flows::gateway_context::RouterGatewayContext,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let capture_sync_method_result = connector_integration
.get_multiple_capture_sync_method()
.to_payment_failed_response();
match (self.request.sync_type.clone(), capture_sync_method_result) {
(
types::SyncRequestType::MultipleCaptureSync(pending_connector_capture_id_list),
Ok(services::CaptureSyncMethod::Individual),
) => {
let mut new_router_data = self
.execute_connector_processing_step_for_each_capture(
state,
pending_connector_capture_id_list,
call_connector_action,
connector_integration,
return_raw_connector_response,
gateway_context,
)
.await?;
// Initiating Integrity checks
let integrity_result = helpers::check_integrity_based_on_flow(
&new_router_data.request,
&new_router_data.response,
);
new_router_data.integrity_check = integrity_result;
Ok(new_router_data)
}
(types::SyncRequestType::MultipleCaptureSync(_), Err(err)) => Err(err),
_ => {
// for bulk sync of captures, above logic needs to be handled at connector end
let mut new_router_data = gateway::execute_payment_gateway(
state,
connector_integration,
&self,
call_connector_action,
connector_request,
return_raw_connector_response,
gateway_context,
)
.await
.to_payment_failed_response()?;
// Initiating Integrity checks
let integrity_result = helpers::check_integrity_based_on_flow(
&new_router_data.request,
&new_router_data.response,
);
new_router_data.integrity_check = integrity_result;
Ok(new_router_data)
}
}
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &payments::gateway::context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
let request = match call_connector_action {
payments::CallConnectorAction::Trigger => {
//validate_psync_reference_id if call_connector_action is trigger
if connector
.connector
.validate_psync_reference_id(
&self.request,
self.is_three_ds(),
self.status,
self.connector_meta_data.clone(),
)
.is_err()
{
logger::warn!(
"validate_psync_reference_id failed, hence skipping call to connector"
);
return Ok((None, false));
}
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?
}
_ => None,
};
Ok((request, true))
}
}
#[async_trait]
pub trait RouterDataPSync
where
Self: Sized,
{
async fn execute_connector_processing_step_for_each_capture(
&self,
state: &SessionState,
pending_connector_capture_id_list: Vec<String>,
call_connector_action: payments::CallConnectorAction,
connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
>,
return_raw_connector_response: Option<bool>,
gateway_context: payments::flows::gateway_context::RouterGatewayContext,
) -> RouterResult<Self>;
}
#[async_trait]
impl RouterDataPSync
for types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
{
async fn execute_connector_processing_step_for_each_capture(
&self,
state: &SessionState,
pending_connector_capture_id_list: Vec<String>,
call_connector_action: payments::CallConnectorAction,
connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PSync,
types::PaymentsSyncData,
types::PaymentsResponseData,
>,
return_raw_connector_response: Option<bool>,
gateway_context: payments::flows::gateway_context::RouterGatewayContext,
) -> RouterResult<Self> {
let mut capture_sync_response_map = HashMap::new();
if let payments::CallConnectorAction::HandleResponse(_) = call_connector_action {
// webhook consume flow, only call connector once. Since there will only be a single event in every webhook
let resp = services::execute_connector_processing_step(
state,
connector_integration,
self,
call_connector_action.clone(),
None,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
Ok(resp)
} else {
// in trigger, call connector for every capture_id
for connector_capture_id in pending_connector_capture_id_list {
// TEMPORARY FIX: remove the clone on router data after removing this function as an impl on trait RouterDataPSync
// TRACKING ISSUE: https://github.com/juspay/hyperswitch/issues/4644
let mut cloned_router_data = self.clone();
cloned_router_data.request.connector_transaction_id =
types::ResponseId::ConnectorTransactionId(connector_capture_id.clone());
let resp = gateway::execute_payment_gateway(
state,
connector_integration.clone_box(),
&cloned_router_data,
call_connector_action.clone(),
None,
return_raw_connector_response,
gateway_context.clone(),
)
.await
.to_payment_failed_response()?;
match resp.response {
Err(err) => {
capture_sync_response_map.insert(connector_capture_id, types::CaptureSyncResponse::Error {
code: err.code,
message: err.message,
reason: err.reason,
status_code: err.status_code,
amount: None,
});
},
Ok(types::PaymentsResponseData::MultipleCaptureResponse { capture_sync_response_list })=> {
capture_sync_response_map.extend(capture_sync_response_list.into_iter());
}
_ => Err(ApiErrorResponse::PreconditionFailed { message: "Response type must be PaymentsResponseData::MultipleCaptureResponse for payment sync".into() })?,
};
}
let mut cloned_router_data = self.clone();
cloned_router_data.response =
Ok(types::PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list: capture_sync_response_map,
});
Ok(cloned_router_data)
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/flows/session_flow.rs | crates/router/src/core/payments/flows/session_flow.rs | use api_models::{admin as admin_types, payments as payment_types};
use async_trait::async_trait;
use common_utils::{
ext_traits::ByteSliceExt,
request::RequestContent,
types::{AmountConvertor, StringMajorUnitForConnector},
};
use error_stack::{Report, ResultExt};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentIntentData;
use hyperswitch_interfaces::api::gateway;
use masking::{ExposeInterface, ExposeOptionInterface};
use super::{ConstructFlowSpecificData, Feature};
use crate::{
consts::PROTOCOL,
core::{
errors::{self, ConnectorErrorExt, RouterResult},
payments::{
self, access_token, customers, gateway::context as gateway_context, helpers,
transformers, PaymentData,
},
},
headers, logger,
routes::{self, app::settings, metrics},
services,
types::{
self,
api::{self, enums},
domain,
},
utils::OptionExt,
};
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for PaymentIntentData<api::Session>
{
async fn construct_router_data<'a>(
&self,
state: &routes::SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data_for_sdk_session(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for PaymentData<api::Session>
{
async fn construct_router_data<'a>(
&self,
state: &routes::SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Session,
types::PaymentsSessionData,
>(
state,
self.clone(),
connector_id,
platform,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
payment_method,
payment_method_type,
))
.await
}
}
#[async_trait]
impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessionRouterData {
async fn decide_flows<'a>(
self,
state: &routes::SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
gateway_context: gateway_context::RouterGatewayContext,
) -> RouterResult<Self> {
metrics::SESSION_TOKEN_CREATED.add(
1,
router_env::metric_attributes!(("connector", connector.connector_name.to_string())),
);
self.decide_flow(
state,
connector,
Some(true),
call_connector_action,
business_profile,
header_payload,
gateway_context,
)
.await
}
async fn add_access_token<'a>(
&self,
state: &routes::SessionState,
connector: &api::ConnectorData,
_platform: &domain::Platform,
creds_identifier: Option<&str>,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
self,
creds_identifier,
gateway_context,
))
.await
}
async fn create_connector_customer<'a>(
&self,
state: &routes::SessionState,
connector: &api::ConnectorData,
gateway_context: &gateway_context::RouterGatewayContext,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self)?,
gateway_context,
)
.await
}
}
/// This function checks if for a given connector, payment_method and payment_method_type,
/// the list of required_field_type is present in dynamic fields
#[cfg(feature = "v1")]
fn is_dynamic_fields_required(
required_fields: &settings::RequiredFields,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
connector: types::Connector,
required_field_type: Vec<enums::FieldType>,
) -> bool {
required_fields
.0
.get(&payment_method)
.and_then(|pm_type| pm_type.0.get(&payment_method_type))
.and_then(|required_fields_for_connector| {
required_fields_for_connector.fields.get(&connector)
})
.map(|required_fields_final| {
required_fields_final
.non_mandate
.iter()
.any(|(_, val)| required_field_type.contains(&val.field_type))
|| required_fields_final
.mandate
.iter()
.any(|(_, val)| required_field_type.contains(&val.field_type))
|| required_fields_final
.common
.iter()
.any(|(_, val)| required_field_type.contains(&val.field_type))
})
.unwrap_or(false)
}
/// This function checks if for a given connector, payment_method and payment_method_type,
/// the list of required_field_type is present in dynamic fields
#[cfg(feature = "v2")]
fn is_dynamic_fields_required(
required_fields: &settings::RequiredFields,
payment_method: enums::PaymentMethod,
payment_method_type: enums::PaymentMethodType,
connector: types::Connector,
required_field_type: Vec<enums::FieldType>,
) -> bool {
required_fields
.0
.get(&payment_method)
.and_then(|pm_type| pm_type.0.get(&payment_method_type))
.and_then(|required_fields_for_connector| {
required_fields_for_connector.fields.get(&connector)
})
.map(|required_fields_final| {
required_fields_final
.non_mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.mandate
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
|| required_fields_final
.common
.iter()
.flatten()
.any(|field_info| required_field_type.contains(&field_info.field_type))
})
.unwrap_or(false)
}
fn build_apple_pay_session_request(
state: &routes::SessionState,
request: payment_types::ApplepaySessionRequest,
apple_pay_merchant_cert: masking::Secret<String>,
apple_pay_merchant_cert_key: masking::Secret<String>,
) -> RouterResult<services::Request> {
let mut url = state.conf.connectors.applepay.base_url.to_owned();
url.push_str("paymentservices/paymentSession");
let session_request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(url.as_str())
.attach_default_headers()
.headers(vec![(
headers::CONTENT_TYPE.to_string(),
"application/json".to_string().into(),
)])
.set_body(RequestContent::Json(Box::new(request)))
.add_certificate(Some(apple_pay_merchant_cert))
.add_certificate_key(Some(apple_pay_merchant_cert_key))
.build();
Ok(session_request)
}
async fn create_applepay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
let delayed_response = is_session_response_delayed(state, connector);
if delayed_response {
let delayed_response_apple_pay_session =
Some(payment_types::ApplePaySessionResponse::NoSessionResponse(
api_models::payments::NullObject,
));
create_apple_pay_session_response(
router_data,
delayed_response_apple_pay_session,
None, // Apple pay payment request will be none for delayed session response
connector.connector_name.to_string(),
delayed_response,
payment_types::NextActionCall::Confirm,
header_payload,
)
} else {
// Get the apple pay metadata
let apple_pay_metadata =
helpers::get_applepay_metadata(router_data.connector_meta_data.clone())
.attach_printable(
"Failed to to fetch apple pay certificates during session call",
)?;
// Get payment request data , apple pay session request and merchant keys
let (
payment_request_data,
apple_pay_session_request_optional,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
apple_pay_merchant_identifier,
merchant_business_country,
merchant_configured_domain_optional,
) = match apple_pay_metadata {
payment_types::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined_metadata,
) => match apple_pay_combined_metadata {
payment_types::ApplePayCombinedMetadata::Simplified {
payment_request_data,
session_token_data,
} => {
logger::info!("Apple pay simplified flow");
let merchant_identifier = state
.conf
.applepay_merchant_configs
.get_inner()
.common_merchant_identifier
.clone()
.expose();
let merchant_business_country = session_token_data.merchant_business_country;
let apple_pay_session_request = get_session_request_for_simplified_apple_pay(
merchant_identifier.clone(),
session_token_data.clone(),
);
let apple_pay_merchant_cert = state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_merchant_cert
.clone();
let apple_pay_merchant_cert_key = state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_merchant_cert_key
.clone();
(
payment_request_data,
Ok(apple_pay_session_request),
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
merchant_identifier,
merchant_business_country,
Some(session_token_data.initiative_context),
)
}
payment_types::ApplePayCombinedMetadata::Manual {
payment_request_data,
session_token_data,
} => {
logger::info!("Apple pay manual flow");
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
session_token_data.clone(),
header_payload.x_merchant_domain.clone(),
);
let merchant_business_country = session_token_data.merchant_business_country;
(
payment_request_data,
apple_pay_session_request,
session_token_data.certificate.clone(),
session_token_data.certificate_keys,
session_token_data.merchant_identifier,
merchant_business_country,
session_token_data.initiative_context,
)
}
},
payment_types::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
logger::info!("Apple pay manual flow");
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
apple_pay_metadata.session_token_data.clone(),
header_payload.x_merchant_domain.clone(),
);
let merchant_business_country = apple_pay_metadata
.session_token_data
.merchant_business_country;
(
apple_pay_metadata.payment_request_data,
apple_pay_session_request,
apple_pay_metadata.session_token_data.certificate.clone(),
apple_pay_metadata
.session_token_data
.certificate_keys
.clone(),
apple_pay_metadata.session_token_data.merchant_identifier,
merchant_business_country,
apple_pay_metadata.session_token_data.initiative_context,
)
}
};
// Get amount info for apple pay
let amount_info = get_apple_pay_amount_info(
payment_request_data.label.as_str(),
router_data.request.to_owned(),
)?;
let required_billing_contact_fields = if business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
Some(payment_types::ApplePayBillingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
]))
} else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
let billing_variants = enums::FieldType::get_billing_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
connector.connector_name,
billing_variants,
)
.then_some(payment_types::ApplePayBillingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
]))
} else {
None
};
let required_shipping_contact_fields = if business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
Some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
connector.connector_name,
shipping_variants,
)
.then_some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::PostalAddress,
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else {
None
};
// If collect_shipping_details_from_wallet_connector is false, we check if
// collect_billing_details_from_wallet_connector is true. If it is, then we pass the Email and Phone in
// ApplePayShippingContactFields as it is a required parameter and ApplePayBillingContactFields
// does not contain Email and Phone.
let required_shipping_contact_fields_updated = if required_billing_contact_fields.is_some()
&& required_shipping_contact_fields.is_none()
{
Some(payment_types::ApplePayShippingContactFields(vec![
payment_types::ApplePayAddressParameters::Phone,
payment_types::ApplePayAddressParameters::Email,
]))
} else {
required_shipping_contact_fields
};
// Get apple pay payment request
let applepay_payment_request = get_apple_pay_payment_request(
amount_info,
payment_request_data,
router_data.request.to_owned(),
apple_pay_merchant_identifier.as_str(),
merchant_business_country,
required_billing_contact_fields,
required_shipping_contact_fields_updated,
)?;
let apple_pay_session_response = match (
header_payload.browser_name.clone(),
header_payload.x_client_platform.clone(),
) {
(Some(common_enums::BrowserName::Safari), Some(common_enums::ClientPlatform::Web))
| (None, None) => {
let apple_pay_session_request = apple_pay_session_request_optional
.attach_printable("Failed to obtain apple pay session request")?;
let applepay_session_request = build_apple_pay_session_request(
state,
apple_pay_session_request.clone(),
apple_pay_merchant_cert.clone(),
apple_pay_merchant_cert_key.clone(),
)?;
let response = services::call_connector_api(
state,
applepay_session_request,
"create_apple_pay_session_token",
)
.await;
let updated_response = match (
response.as_ref().ok(),
header_payload.x_merchant_domain.clone(),
) {
(Some(Err(error)), Some(_)) => {
logger::error!(
"Retry apple pay session call with the merchant configured domain {error:?}"
);
let merchant_configured_domain = merchant_configured_domain_optional
.get_required_value("apple pay domain")
.attach_printable("Failed to get domain for apple pay session call")?;
let apple_pay_retry_session_request =
payment_types::ApplepaySessionRequest {
initiative_context: merchant_configured_domain,
..apple_pay_session_request
};
let applepay_retry_session_request = build_apple_pay_session_request(
state,
apple_pay_retry_session_request,
apple_pay_merchant_cert,
apple_pay_merchant_cert_key,
)?;
services::call_connector_api(
state,
applepay_retry_session_request,
"create_apple_pay_session_token",
)
.await
}
_ => response,
};
// logging the error if present in session call response
log_session_response_if_error(&updated_response);
updated_response
.ok()
.and_then(|apple_pay_res| {
apple_pay_res
.map(|res| {
let response: Result<
payment_types::NoThirdPartySdkSessionResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("NoThirdPartySdkSessionResponse");
// logging the parsing failed error
if let Err(error) = response.as_ref() {
logger::error!(?error);
};
response.ok()
})
.ok()
})
.flatten()
}
_ => {
logger::debug!("Skipping apple pay session call based on the browser name");
None
}
};
let session_response =
apple_pay_session_response.map(payment_types::ApplePaySessionResponse::NoThirdPartySdk);
create_apple_pay_session_response(
router_data,
session_response,
Some(applepay_payment_request),
connector.connector_name.to_string(),
delayed_response,
payment_types::NextActionCall::Confirm,
header_payload,
)
}
}
fn create_paze_session_token(
router_data: &types::PaymentsSessionRouterData,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<types::PaymentsSessionRouterData> {
let paze_wallet_details = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::PazeSessionTokenData>("PazeSessionTokenData")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "paze_metadata_format".to_string(),
})?;
let required_amount_type = StringMajorUnitForConnector;
let transaction_currency_code = router_data.request.currency;
let transaction_amount = required_amount_type
.convert(router_data.request.minor_amount, transaction_currency_code)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for paze".to_string(),
})?;
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::Paze(Box::new(
payment_types::PazeSessionTokenResponse {
client_id: paze_wallet_details.data.client_id,
client_name: paze_wallet_details.data.client_name,
client_profile_id: paze_wallet_details.data.client_profile_id,
transaction_currency_code,
transaction_amount,
email_address: router_data.request.email.clone(),
},
)),
}),
..router_data.clone()
})
}
fn create_samsung_pay_session_token(
state: &routes::SessionState,
router_data: &types::PaymentsSessionRouterData,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
) -> RouterResult<types::PaymentsSessionRouterData> {
let samsung_pay_session_token_data = router_data
.connector_wallets_details
.clone()
.parse_value::<payment_types::SamsungPaySessionTokenData>("SamsungPaySessionTokenData")
.change_context(errors::ConnectorError::NoConnectorWalletDetails)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_wallets_details".to_string(),
expected_format: "samsung_pay_metadata_format".to_string(),
})?;
let required_amount_type = StringMajorUnitForConnector;
let samsung_pay_amount = required_amount_type
.convert(
router_data.request.minor_amount,
router_data.request.currency,
)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for Samsung Pay".to_string(),
})?;
let merchant_domain = match header_payload.x_client_platform {
Some(common_enums::ClientPlatform::Web) => Some(
header_payload
.x_merchant_domain
.get_required_value("samsung pay domain")
.attach_printable("Failed to get domain for samsung pay session call")?,
),
_ => None,
};
let samsung_pay_wallet_details = match samsung_pay_session_token_data.data {
payment_types::SamsungPayCombinedMetadata::MerchantCredentials(
samsung_pay_merchant_credentials,
) => samsung_pay_merchant_credentials,
payment_types::SamsungPayCombinedMetadata::ApplicationCredentials(
_samsung_pay_application_credentials,
) => Err(errors::ApiErrorResponse::NotSupported {
message: "Samsung Pay decryption flow with application credentials is not implemented"
.to_owned(),
})?,
};
let formatted_payment_id = router_data.payment_id.replace("_", "-");
let billing_address_required = is_billing_address_required_to_be_collected_from_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
let shipping_address_required = is_shipping_address_required_to_be_collected_form_wallet(
state,
connector,
business_profile,
enums::PaymentMethodType::SamsungPay,
);
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::SamsungPay(Box::new(
payment_types::SamsungPaySessionTokenResponse {
version: "2".to_string(),
service_id: samsung_pay_wallet_details.service_id,
order_number: formatted_payment_id,
merchant_payment_information:
payment_types::SamsungPayMerchantPaymentInformation {
name: samsung_pay_wallet_details.merchant_display_name,
url: merchant_domain,
country_code: samsung_pay_wallet_details.merchant_business_country,
},
amount: payment_types::SamsungPayAmountDetails {
amount_format: payment_types::SamsungPayAmountFormat::FormatTotalPriceOnly,
currency_code: router_data.request.currency,
total_amount: samsung_pay_amount,
},
protocol: payment_types::SamsungPayProtocolType::Protocol3ds,
allowed_brands: samsung_pay_wallet_details.allowed_brands,
billing_address_required,
shipping_address_required,
},
)),
}),
..router_data.clone()
})
}
/// Function to determine whether the billing address is required to be collected from the wallet,
/// based on business profile settings, the payment method type, and the connector's required fields
/// for the specific payment method.
///
/// If `always_collect_billing_details_from_wallet_connector` is enabled, it indicates that the
/// billing address is always required to be collected from the wallet.
///
/// If only `collect_billing_details_from_wallet_connector` is enabled, the billing address will be
/// collected only if the connector required fields for the specific payment method type contain
/// the billing fields.
fn is_billing_address_required_to_be_collected_from_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_billing_details_from_wallet_connector = business_profile
.always_collect_billing_details_from_wallet_connector
.unwrap_or(false);
if always_collect_billing_details_from_wallet_connector {
always_collect_billing_details_from_wallet_connector
} else if business_profile
.collect_billing_details_from_wallet_connector
.unwrap_or(false)
{
let billing_variants = enums::FieldType::get_billing_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
billing_variants,
)
} else {
false
}
}
/// Function to determine whether the shipping address is required to be collected from the wallet,
/// based on business profile settings, the payment method type, and the connector required fields
/// for the specific payment method type.
///
/// If `always_collect_shipping_details_from_wallet_connector` is enabled, it indicates that the
/// shipping address is always required to be collected from the wallet.
///
/// If only `collect_shipping_details_from_wallet_connector` is enabled, the shipping address will be
/// collected only if the connector required fields for the specific payment method type contain
/// the shipping fields.
fn is_shipping_address_required_to_be_collected_form_wallet(
state: &routes::SessionState,
connector: &api::ConnectorData,
business_profile: &domain::Profile,
payment_method_type: enums::PaymentMethodType,
) -> bool {
let always_collect_shipping_details_from_wallet_connector = business_profile
.always_collect_shipping_details_from_wallet_connector
.unwrap_or(false);
if always_collect_shipping_details_from_wallet_connector {
always_collect_shipping_details_from_wallet_connector
} else if business_profile
.collect_shipping_details_from_wallet_connector
.unwrap_or(false)
{
let shipping_variants = enums::FieldType::get_shipping_variants();
is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
payment_method_type,
connector.connector_name,
shipping_variants,
)
} else {
false
}
}
fn get_session_request_for_simplified_apple_pay(
apple_pay_merchant_identifier: String,
session_token_data: payment_types::SessionTokenForSimplifiedApplePay,
) -> payment_types::ApplepaySessionRequest {
payment_types::ApplepaySessionRequest {
merchant_identifier: apple_pay_merchant_identifier,
display_name: "Apple pay".to_string(),
initiative: "web".to_string(),
initiative_context: session_token_data.initiative_context,
}
}
fn get_session_request_for_manual_apple_pay(
session_token_data: payment_types::SessionTokenInfo,
merchant_domain: Option<String>,
) -> RouterResult<payment_types::ApplepaySessionRequest> {
let initiative_context = merchant_domain
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/gateway/setup_mandate.rs | crates/router/src/core/payments/gateway/setup_mandate.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::{CallConnectorAction, ExecutionPath};
use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};
use error_stack::ResultExt;
use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};
use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
};
use unified_connector_service_client::payments as payments_grpc;
use crate::{
core::{
payments::gateway::context::RouterGatewayContext, unified_connector_service,
unified_connector_service::handle_unified_connector_service_response_for_payment_register,
},
routes::SessionState,
services::logger,
types::{self, transformers::ForeignTryFrom},
};
// =============================================================================
// PaymentGateway Implementation for domain::SetupMandate
// =============================================================================
/// Implementation of PaymentGateway for api::PSync flow
#[async_trait]
impl<RCD>
payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::SetupMandateRequestData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::SetupMandate
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::SetupMandateRequestData, types::PaymentsResponseData>,
{
async fn execute(
self: Box<Self>,
state: &SessionState,
_connector_integration: BoxedConnectorIntegrationInterface<
Self,
RCD,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
router_data: &RouterData<Self, types::SetupMandateRequestData, types::PaymentsResponseData>,
_call_connector_action: CallConnectorAction,
_connector_request: Option<Request>,
_return_raw_connector_response: Option<bool>,
context: RouterGatewayContext,
) -> CustomResult<
RouterData<Self, types::SetupMandateRequestData, types::PaymentsResponseData>,
ConnectorError,
> {
let merchant_connector_account = context.merchant_connector_account;
let platform = context.platform;
let lineage_ids = context.lineage_ids;
let header_payload = context.header_payload;
let unified_connector_service_execution_mode = context.execution_mode;
let merchant_order_reference_id = header_payload.x_reference_id.clone();
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let setup_mandate_request =
payments_grpc::PaymentServiceRegisterRequest::foreign_try_from(router_data)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Get Request")?;
let connector_auth_metadata =
unified_connector_service::build_unified_connector_service_auth_metadata(
merchant_connector_account,
&platform,
router_data.connector.clone(),
)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.or(merchant_order_reference_id)
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let header_payload = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
setup_mandate_request,
header_payload,
|mut router_data, setup_mandate_request, grpc_headers| async move {
let response = Box::pin(client.payment_setup_mandate_granular(
setup_mandate_request,
connector_auth_metadata,
grpc_headers,
))
.await
.attach_printable("Failed to get payment")?;
let setup_mandate_response = response.into_inner();
let ucs_data = handle_unified_connector_service_response_for_payment_register(
setup_mandate_response.clone(),
)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response =
ucs_data.router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.connector_http_status_code = Some(ucs_data.status_code);
// Populate connector_customer_id if present
ucs_data.connector_customer_id.map(|connector_customer_id| {
router_data.connector_customer = Some(connector_customer_id);
});
Ok((router_data, (), setup_mandate_response))
},
))
.await
.map(|(router_data, _)| router_data)
.change_context(ConnectorError::ResponseHandlingFailed)
}
}
/// Implementation of FlowGateway for api::PSync
///
/// This allows the flow to provide its specific gateway based on execution path
impl<RCD>
payment_gateway::FlowGateway<
SessionState,
RCD,
types::SetupMandateRequestData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::SetupMandate
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::SetupMandateRequestData, types::PaymentsResponseData>,
{
fn get_gateway(
execution_path: ExecutionPath,
) -> Box<
dyn payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::SetupMandateRequestData,
types::PaymentsResponseData,
RouterGatewayContext,
>,
> {
match execution_path {
ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
ExecutionPath::UnifiedConnectorService
| ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/gateway/session_token_gateway.rs | crates/router/src/core/payments/gateway/session_token_gateway.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::{CallConnectorAction, ExecutionPath};
use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};
use error_stack::ResultExt;
use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};
use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
};
use unified_connector_service_client::payments as payments_grpc;
use crate::{
core::{
payments::gateway::context::RouterGatewayContext, unified_connector_service,
unified_connector_service::handle_unified_connector_service_response_for_session_token_create,
},
routes::SessionState,
services::logger,
types::{self, transformers::ForeignTryFrom},
};
// =============================================================================
// PaymentGateway Implementation for domain::AuthorizeSessionToken
// =============================================================================
/// Implementation of PaymentGateway for api::PSync flow
#[async_trait]
impl<RCD>
payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::AuthorizeSessionToken
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::AuthorizeSessionTokenData, types::PaymentsResponseData>,
{
async fn execute(
self: Box<Self>,
state: &SessionState,
_connector_integration: BoxedConnectorIntegrationInterface<
Self,
RCD,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
>,
router_data: &RouterData<
Self,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
>,
_call_connector_action: CallConnectorAction,
_connector_request: Option<Request>,
_return_raw_connector_response: Option<bool>,
context: RouterGatewayContext,
) -> CustomResult<
RouterData<Self, types::AuthorizeSessionTokenData, types::PaymentsResponseData>,
ConnectorError,
> {
let merchant_connector_account = context.merchant_connector_account;
let platform = context.platform;
let lineage_ids = context.lineage_ids;
let header_payload = context.header_payload;
let unified_connector_service_execution_mode = context.execution_mode;
let merchant_order_reference_id = header_payload.x_reference_id.clone();
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let authorize_session_token_request =
payments_grpc::PaymentServiceCreateSessionTokenRequest::foreign_try_from(router_data)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Session Create Request")?;
let connector_auth_metadata =
unified_connector_service::build_unified_connector_service_auth_metadata(
merchant_connector_account,
&platform,
router_data.connector.clone(),
)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.or(merchant_order_reference_id)
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let header_payload = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
authorize_session_token_request,
header_payload,
|mut router_data, authorize_session_token_request, grpc_headers| async move {
let response = client
.payment_session_token_create(
authorize_session_token_request,
connector_auth_metadata,
grpc_headers,
)
.await
.attach_printable("Failed to get payment")?;
let payment_session_token_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_session_token_create(
payment_session_token_response.clone(),
)
.attach_printable("Failed to deserialize UCS response")?;
router_data.response = router_data_response;
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, (), payment_session_token_response))
},
))
.await
.map(|(router_data, _)| router_data)
.change_context(ConnectorError::ResponseHandlingFailed)
}
}
/// Implementation of FlowGateway for api::PSync
///
/// This allows the flow to provide its specific gateway based on execution path
impl<RCD>
payment_gateway::FlowGateway<
SessionState,
RCD,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::AuthorizeSessionToken
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::AuthorizeSessionTokenData, types::PaymentsResponseData>,
{
fn get_gateway(
execution_path: ExecutionPath,
) -> Box<
dyn payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
RouterGatewayContext,
>,
> {
match execution_path {
ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
ExecutionPath::UnifiedConnectorService
| ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/gateway/authenticate_gateway.rs | crates/router/src/core/payments/gateway/authenticate_gateway.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::{CallConnectorAction, ExecutionPath};
use common_utils::{errors::CustomResult, request::Request};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::RouterData, router_flow_types as domain, router_request_types,
};
use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
};
use crate::{
core::payments::{flows::complete_authorize_flow, gateway::context::RouterGatewayContext},
routes::SessionState,
types,
};
// =============================================================================
// PaymentGateway Implementation for domain::Authenticate
// =============================================================================
/// Implementation of PaymentGateway for api::Authenticate flow
#[async_trait]
impl<RCD>
payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::PaymentsAuthenticateData,
types::PaymentsResponseData,
RouterGatewayContext,
(
RouterData<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
Option<router_request_types::UcsAuthenticationData>,
),
> for domain::Authenticate
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
{
async fn execute(
self: Box<Self>,
state: &SessionState,
_connector_integration: BoxedConnectorIntegrationInterface<
Self,
RCD,
types::PaymentsAuthenticateData,
types::PaymentsResponseData,
>,
router_data: &RouterData<
Self,
types::PaymentsAuthenticateData,
types::PaymentsResponseData,
>,
_call_connector_action: CallConnectorAction,
_connector_request: Option<Request>,
_return_raw_connector_response: Option<bool>,
context: RouterGatewayContext,
) -> CustomResult<
(
RouterData<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
Option<router_request_types::UcsAuthenticationData>,
),
ConnectorError,
> {
let merchant_connector_account = context.merchant_connector_account;
let platform = context.platform;
let lineage_ids = context.lineage_ids;
let header_payload = context.header_payload;
let unified_connector_service_execution_mode = context.execution_mode;
let merchant_order_reference_id = header_payload.x_reference_id.clone();
let connector_enum =
common_enums::connector_enums::Connector::from_str(&router_data.connector)
.change_context(ConnectorError::InvalidConnectorName)
.attach_printable("Invalid connector name")?;
complete_authorize_flow::call_unified_connector_service_authenticate(
router_data,
state,
&header_payload,
lineage_ids,
merchant_connector_account,
&platform,
connector_enum,
unified_connector_service_execution_mode,
merchant_order_reference_id,
)
.await
}
}
/// Implementation of FlowGateway for api::PSync
///
/// This allows the flow to provide its specific gateway based on execution path
impl<RCD>
payment_gateway::FlowGateway<
SessionState,
RCD,
types::PaymentsAuthenticateData,
types::PaymentsResponseData,
RouterGatewayContext,
(
RouterData<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
Option<router_request_types::UcsAuthenticationData>,
),
> for domain::Authenticate
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
{
fn get_gateway(
execution_path: ExecutionPath,
) -> Box<
dyn payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::PaymentsAuthenticateData,
types::PaymentsResponseData,
RouterGatewayContext,
(
RouterData<Self, types::PaymentsAuthenticateData, types::PaymentsResponseData>,
Option<router_request_types::UcsAuthenticationData>,
),
>,
> {
match execution_path {
ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
ExecutionPath::UnifiedConnectorService
| ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/gateway/create_customer_gateway.rs | crates/router/src/core/payments/gateway/create_customer_gateway.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::{CallConnectorAction, ExecutionPath};
use common_utils::{errors::CustomResult, request::Request};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::RouterData, router_flow_types as domain,
router_request_types::ConnectorCustomerData,
};
use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
};
use unified_connector_service_client::payments as payments_grpc;
use crate::{
core::{
payments::gateway::context::RouterGatewayContext, unified_connector_service,
unified_connector_service::handle_unified_connector_service_response_for_create_connector_customer,
},
routes::SessionState,
types::{self, transformers::ForeignTryFrom},
};
// =============================================================================
// PaymentGateway Implementation for domain::CreateConnectorCustomer
// =============================================================================
/// Implementation of PaymentGateway for CreateConnectorCustomer flow
#[async_trait]
impl<RCD>
payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
ConnectorCustomerData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::CreateConnectorCustomer
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, ConnectorCustomerData, types::PaymentsResponseData>,
{
async fn execute(
self: Box<Self>,
state: &SessionState,
_connector_integration: BoxedConnectorIntegrationInterface<
Self,
RCD,
ConnectorCustomerData,
types::PaymentsResponseData,
>,
router_data: &RouterData<Self, ConnectorCustomerData, types::PaymentsResponseData>,
call_connector_action: CallConnectorAction,
_connector_request: Option<Request>,
_return_raw_connector_response: Option<bool>,
context: RouterGatewayContext,
) -> CustomResult<
RouterData<Self, ConnectorCustomerData, types::PaymentsResponseData>,
ConnectorError,
> {
let connector_name = router_data.connector.clone();
let _connector_enum = common_enums::connector_enums::Connector::from_str(&connector_name)
.change_context(ConnectorError::InvalidConnectorName)?;
let merchant_connector_account = context.merchant_connector_account;
let platform = context.platform;
let lineage_ids = context.lineage_ids;
let unified_connector_service_execution_mode = context.execution_mode;
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let create_connector_customer_request =
payments_grpc::PaymentServiceCreateConnectorCustomerRequest::foreign_try_from((
router_data,
call_connector_action,
))
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Create Connector Customer Request")?;
let connector_auth_metadata =
unified_connector_service::build_unified_connector_service_auth_metadata(
merchant_connector_account,
&platform,
router_data.connector.clone(),
)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let grpc_headers = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(None)
.lineage_ids(lineage_ids);
Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
create_connector_customer_request,
grpc_headers,
|mut router_data, create_connector_customer_request, grpc_headers| async move {
let response = Box::pin(client.create_connector_customer(
create_connector_customer_request,
connector_auth_metadata,
grpc_headers,
))
.await
.attach_printable("Failed to create connector customer")?;
let create_connector_customer_response = response.into_inner();
let (connector_customer_result, status_code) =
handle_unified_connector_service_response_for_create_connector_customer(
create_connector_customer_response.clone(),
)
.attach_printable("Failed to deserialize UCS response")?;
router_data.response = connector_customer_result;
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, (), create_connector_customer_response))
},
))
.await
.map(|(router_data, _)| router_data)
.change_context(ConnectorError::ResponseHandlingFailed)
}
}
/// Implementation of FlowGateway for CreateConnectorCustomer
///
/// This allows the flow to provide its specific gateway based on execution path
impl<RCD>
payment_gateway::FlowGateway<
SessionState,
RCD,
ConnectorCustomerData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::CreateConnectorCustomer
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, ConnectorCustomerData, types::PaymentsResponseData>,
{
fn get_gateway(
execution_path: ExecutionPath,
) -> Box<
dyn payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
ConnectorCustomerData,
types::PaymentsResponseData,
RouterGatewayContext,
>,
> {
match execution_path {
ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
ExecutionPath::UnifiedConnectorService
| ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs | crates/router/src/core/payments/gateway/payment_method_token_create_gateway.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::{CallConnectorAction, ExecutionPath};
use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};
use error_stack::ResultExt;
use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};
use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
};
use unified_connector_service_client::payments as payments_grpc;
use crate::{
core::{
payments::gateway::context::RouterGatewayContext, unified_connector_service,
unified_connector_service::handle_unified_connector_service_response_for_payment_method_token_create,
},
routes::SessionState,
services::logger,
types::{self, transformers::ForeignTryFrom},
};
// =============================================================================
// PaymentGateway Implementation for domain::PaymentMethodToken
// =============================================================================
/// Implementation of PaymentGateway for api::PaymentMethodToken flow
#[async_trait]
impl<RCD>
payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::PaymentMethodToken
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<
Self,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
>,
{
async fn execute(
self: Box<Self>,
state: &SessionState,
_connector_integration: BoxedConnectorIntegrationInterface<
Self,
RCD,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
>,
router_data: &RouterData<
Self,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
>,
_call_connector_action: CallConnectorAction,
_connector_request: Option<Request>,
_return_raw_connector_response: Option<bool>,
context: RouterGatewayContext,
) -> CustomResult<
RouterData<Self, types::PaymentMethodTokenizationData, types::PaymentsResponseData>,
ConnectorError,
> {
let merchant_connector_account = context.merchant_connector_account;
let platform = context.platform;
let lineage_ids = context.lineage_ids;
let header_payload = context.header_payload;
let unified_connector_service_execution_mode = context.execution_mode;
let merchant_order_reference_id = header_payload.x_reference_id.clone();
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let pm_token_create_request =
payments_grpc::PaymentServiceCreatePaymentMethodTokenRequest::foreign_try_from(
router_data,
)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Get Request")?;
let connector_auth_metadata =
unified_connector_service::build_unified_connector_service_auth_metadata(
merchant_connector_account,
&platform,
router_data.connector.clone(),
)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.or(merchant_order_reference_id)
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let header_payload = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
pm_token_create_request,
header_payload,
|mut router_data, pm_token_create_request, grpc_headers| async move {
let response = Box::pin(client.payment_method_token_create(
pm_token_create_request,
connector_auth_metadata,
grpc_headers,
))
.await
.attach_printable("Failed to get payment")?;
let pm_token_create_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_method_token_create(
pm_token_create_response.clone(),
)
.attach_printable("Failed to deserialize UCS response")?;
router_data.response = router_data_response;
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, (), pm_token_create_response))
},
))
.await
.map(|(router_data, _)| router_data)
.change_context(ConnectorError::ResponseHandlingFailed)
}
}
/// Implementation of FlowGateway for api::PaymentMethodToken
///
/// This allows the flow to provide its specific gateway based on execution path
impl<RCD>
payment_gateway::FlowGateway<
SessionState,
RCD,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::PaymentMethodToken
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<
Self,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
>,
{
fn get_gateway(
execution_path: ExecutionPath,
) -> Box<
dyn payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
RouterGatewayContext,
>,
> {
match execution_path {
ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
ExecutionPath::UnifiedConnectorService
| ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/gateway/access_token_gateway.rs | crates/router/src/core/payments/gateway/access_token_gateway.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::{CallConnectorAction, ExecutionPath};
use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::RouterData, router_flow_types as domain,
router_request_types::AccessTokenRequestData,
};
use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
};
use unified_connector_service_client::payments as payments_grpc;
use crate::{
core::{payments::gateway::context::RouterGatewayContext, unified_connector_service},
routes::SessionState,
services::logger,
types::transformers::ForeignTryFrom,
};
// =============================================================================
// PaymentGateway Implementation for domain::AccessTokenAuth
// =============================================================================
/// Implementation of PaymentGateway for AccessTokenAuth flow
#[async_trait]
impl<RCD>
payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
AccessTokenRequestData,
hyperswitch_domain_models::router_data::AccessToken,
RouterGatewayContext,
> for domain::access_token_auth::AccessTokenAuth
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<
Self,
AccessTokenRequestData,
hyperswitch_domain_models::router_data::AccessToken,
>,
{
async fn execute(
self: Box<Self>,
state: &SessionState,
_connector_integration: BoxedConnectorIntegrationInterface<
Self,
RCD,
AccessTokenRequestData,
hyperswitch_domain_models::router_data::AccessToken,
>,
router_data: &RouterData<
Self,
AccessTokenRequestData,
hyperswitch_domain_models::router_data::AccessToken,
>,
call_connector_action: CallConnectorAction,
_connector_request: Option<Request>,
_return_raw_connector_response: Option<bool>,
context: RouterGatewayContext,
) -> CustomResult<
RouterData<
Self,
AccessTokenRequestData,
hyperswitch_domain_models::router_data::AccessToken,
>,
ConnectorError,
> {
let merchant_connector_account = context.merchant_connector_account;
let platform = context.platform;
let lineage_ids = context.lineage_ids;
let header_payload = context.header_payload;
let unified_connector_service_execution_mode = context.execution_mode;
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let create_access_token_request =
payments_grpc::PaymentServiceCreateAccessTokenRequest::foreign_try_from((
router_data,
call_connector_action,
))
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Create Access Token Request")?;
let connector_auth_metadata =
unified_connector_service::build_unified_connector_service_auth_metadata(
merchant_connector_account.clone(),
&platform,
router_data.connector.clone(),
)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let header_payload = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
create_access_token_request,
header_payload,
|mut router_data, create_access_token_request, grpc_headers| async move {
let response = client
.create_access_token(
create_access_token_request,
connector_auth_metadata,
grpc_headers,
)
.await
.attach_printable("Failed to create access token")?;
let create_access_token_response = response.into_inner();
let (access_token_result, status_code) =
unified_connector_service::handle_unified_connector_service_response_for_create_access_token(
create_access_token_response.clone(),
)
.attach_printable("Failed to deserialize UCS response")?;
router_data.response = access_token_result;
router_data.connector_http_status_code = Some(status_code);
Ok((router_data,(), create_access_token_response))
},
))
.await
.map(|(router_data, _)| router_data)
.change_context(ConnectorError::ResponseHandlingFailed)
}
}
/// Implementation of FlowGateway for AccessTokenAuth
///
/// This allows the flow to provide its specific gateway based on execution path
impl<RCD>
payment_gateway::FlowGateway<
SessionState,
RCD,
AccessTokenRequestData,
hyperswitch_domain_models::router_data::AccessToken,
RouterGatewayContext,
> for domain::access_token_auth::AccessTokenAuth
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<
Self,
AccessTokenRequestData,
hyperswitch_domain_models::router_data::AccessToken,
>,
{
fn get_gateway(
execution_path: ExecutionPath,
) -> Box<
dyn payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
AccessTokenRequestData,
hyperswitch_domain_models::router_data::AccessToken,
RouterGatewayContext,
>,
> {
match execution_path {
ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
ExecutionPath::UnifiedConnectorService
| ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/gateway/pre_authenticate_gateway.rs | crates/router/src/core/payments/gateway/pre_authenticate_gateway.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::{CallConnectorAction, ExecutionPath};
use common_utils::{errors::CustomResult, request::Request};
use error_stack::ResultExt;
use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};
use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
};
use crate::{
core::payments::{flows::authorize_flow, gateway::context::RouterGatewayContext},
routes::SessionState,
types,
};
// =============================================================================
// PaymentGateway Implementation for domain::PreAuthenticate
// =============================================================================
/// Implementation of PaymentGateway for api::PSync flow
#[async_trait]
impl<RCD>
payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::PaymentsPreAuthenticateData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::PreAuthenticate
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::PaymentsPreAuthenticateData, types::PaymentsResponseData>,
{
async fn execute(
self: Box<Self>,
state: &SessionState,
_connector_integration: BoxedConnectorIntegrationInterface<
Self,
RCD,
types::PaymentsPreAuthenticateData,
types::PaymentsResponseData,
>,
router_data: &RouterData<
Self,
types::PaymentsPreAuthenticateData,
types::PaymentsResponseData,
>,
_call_connector_action: CallConnectorAction,
_connector_request: Option<Request>,
_return_raw_connector_response: Option<bool>,
context: RouterGatewayContext,
) -> CustomResult<
RouterData<Self, types::PaymentsPreAuthenticateData, types::PaymentsResponseData>,
ConnectorError,
> {
let merchant_connector_account = context.merchant_connector_account;
let platform = context.platform;
let lineage_ids = context.lineage_ids;
let header_payload = context.header_payload;
let unified_connector_service_execution_mode = context.execution_mode;
let merchant_order_reference_id = header_payload.x_reference_id.clone();
let connector_enum =
common_enums::connector_enums::Connector::from_str(&router_data.connector)
.change_context(ConnectorError::InvalidConnectorName)
.attach_printable("Invalid connector name")?;
authorize_flow::call_unified_connector_service_pre_authenticate(
router_data,
state,
&header_payload,
lineage_ids,
merchant_connector_account,
&platform,
connector_enum,
unified_connector_service_execution_mode,
merchant_order_reference_id,
)
.await
.map(|(router_data, _)| router_data)
}
}
/// Implementation of FlowGateway for api::PSync
///
/// This allows the flow to provide its specific gateway based on execution path
impl<RCD>
payment_gateway::FlowGateway<
SessionState,
RCD,
types::PaymentsPreAuthenticateData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::PreAuthenticate
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::PaymentsPreAuthenticateData, types::PaymentsResponseData>,
{
fn get_gateway(
execution_path: ExecutionPath,
) -> Box<
dyn payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::PaymentsPreAuthenticateData,
types::PaymentsResponseData,
RouterGatewayContext,
>,
> {
match execution_path {
ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
ExecutionPath::UnifiedConnectorService
| ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/payments/gateway/authorize_gateway.rs | crates/router/src/core/payments/gateway/authorize_gateway.rs | use std::str::FromStr;
use async_trait::async_trait;
use common_enums::{CallConnectorAction, ExecutionPath};
use common_utils::{errors::CustomResult, id_type, request::Request, ucs_types};
use error_stack::ResultExt;
use hyperswitch_domain_models::{router_data::RouterData, router_flow_types as domain};
use hyperswitch_interfaces::{
api::gateway as payment_gateway,
connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},
errors::ConnectorError,
};
use unified_connector_service_client::payments as payments_grpc;
use unified_connector_service_masking::ExposeInterface as UcsMaskingExposeInterface;
use crate::{
core::{
payments::gateway::context::RouterGatewayContext,
unified_connector_service::{
self, handle_unified_connector_service_response_for_payment_authorize,
handle_unified_connector_service_response_for_payment_repeat,
},
},
routes::SessionState,
services::logger,
types::{self, transformers::ForeignTryFrom, MinorUnit},
};
// =============================================================================
// PaymentGateway Implementation for domain::Authorize
// =============================================================================
/// Implementation of PaymentGateway for api::PSync flow
#[async_trait]
impl<RCD>
payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::Authorize
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
{
async fn execute(
self: Box<Self>,
state: &SessionState,
_connector_integration: BoxedConnectorIntegrationInterface<
Self,
RCD,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
router_data: &RouterData<Self, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
call_connector_action: CallConnectorAction,
_connector_request: Option<Request>,
_return_raw_connector_response: Option<bool>,
context: RouterGatewayContext,
) -> CustomResult<
RouterData<Self, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
ConnectorError,
> {
let merchant_connector_account = context.merchant_connector_account;
let platform = context.platform;
let lineage_ids = context.lineage_ids;
let header_payload = context.header_payload;
let unified_connector_service_execution_mode = context.execution_mode;
let merchant_order_reference_id = header_payload.x_reference_id.clone();
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to fetch Unified Connector Service client")?;
// Check if this is a repeat payment (MIT with mandate_id or MandatePayment)
let is_repeat_payment = router_data.request.mandate_id.is_some()
|| matches!(
router_data.request.payment_method_data,
hyperswitch_domain_models::payment_method_data::PaymentMethodData::MandatePayment
);
let connector_auth_metadata =
unified_connector_service::build_unified_connector_service_auth_metadata(
merchant_connector_account,
&platform,
router_data.connector.clone(),
)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct request metadata")?;
let merchant_reference_id = header_payload
.x_reference_id
.clone()
.or(merchant_order_reference_id)
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let grpc_headers = state
.get_grpc_headers_ucs(unified_connector_service_execution_mode)
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = if is_repeat_payment {
logger::info!(
"Granular Gateway: Detected repeat payment, calling UCS RepeatPayment endpoint"
);
let payment_repeat_request =
payments_grpc::PaymentServiceRepeatEverythingRequest::foreign_try_from(router_data)
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Repeat Request")?;
Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
payment_repeat_request,
grpc_headers,
|mut router_data, payment_repeat_request, grpc_headers| async move {
logger::debug!("Calling UCS payment_repeat gRPC method");
let response = Box::pin(client.payment_repeat(
payment_repeat_request,
connector_auth_metadata,
grpc_headers,
))
.await
.attach_printable("Failed to repeat payment")?;
let payment_repeat_response = response.into_inner();
let ucs_data = handle_unified_connector_service_response_for_payment_repeat(
payment_repeat_response.clone(),
)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response =
ucs_data.router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.amount_captured = payment_repeat_response.captured_amount;
router_data.minor_amount_captured = payment_repeat_response
.minor_captured_amount
.map(MinorUnit::new);
router_data.raw_connector_response = payment_repeat_response
.raw_connector_response
.clone()
.map(|raw_connector_response| raw_connector_response.expose().into());
router_data.connector_http_status_code = Some(ucs_data.status_code);
ucs_data.connector_customer_id.map(|connector_customer_id| {
router_data.connector_customer = Some(connector_customer_id);
});
ucs_data.connector_response.map(|connector_response| {
router_data.connector_response = Some(connector_response);
});
Ok((router_data, (), payment_repeat_response))
},
))
.await
.map(|(router_data, _)| router_data)
.change_context(ConnectorError::ResponseHandlingFailed)?
} else {
logger::debug!("Granular Gateway: Regular authorize flow");
let granular_authorize_request =
payments_grpc::PaymentServiceAuthorizeOnlyRequest::foreign_try_from((
router_data,
call_connector_action,
))
.change_context(ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to construct Payment Get Request")?;
Box::pin(unified_connector_service::ucs_logging_wrapper_granular(
router_data.clone(),
state,
granular_authorize_request,
grpc_headers,
|mut router_data, granular_authorize_request, grpc_headers| async move {
let response = Box::pin(client.payment_authorize_granular(
granular_authorize_request,
connector_auth_metadata,
grpc_headers,
))
.await
.attach_printable("Failed to get payment")?;
let payment_authorize_response = response.into_inner();
let ucs_data = handle_unified_connector_service_response_for_payment_authorize(
payment_authorize_response.clone(),
)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response =
ucs_data.router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.amount_captured = payment_authorize_response.captured_amount;
router_data.minor_amount_captured = payment_authorize_response
.minor_captured_amount
.map(MinorUnit::new);
router_data.minor_amount_capturable = payment_authorize_response
.minor_capturable_amount
.map(MinorUnit::new);
router_data.raw_connector_response = payment_authorize_response
.raw_connector_response
.clone()
.map(|raw_connector_response| raw_connector_response.expose().into());
router_data.connector_http_status_code = Some(ucs_data.status_code);
ucs_data.connector_response.map(|customer_response| {
router_data.connector_response = Some(customer_response);
});
Ok((router_data, (), payment_authorize_response))
},
))
.await
.map(|(router_data, _)| router_data)
.change_context(ConnectorError::ResponseHandlingFailed)?
};
Ok(updated_router_data)
}
}
/// Implementation of FlowGateway for api::PSync
///
/// This allows the flow to provide its specific gateway based on execution path
impl<RCD>
payment_gateway::FlowGateway<
SessionState,
RCD,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
RouterGatewayContext,
> for domain::Authorize
where
RCD: Clone
+ Send
+ Sync
+ 'static
+ RouterDataConversion<Self, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
{
fn get_gateway(
execution_path: ExecutionPath,
) -> Box<
dyn payment_gateway::PaymentGateway<
SessionState,
RCD,
Self,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
RouterGatewayContext,
>,
> {
match execution_path {
ExecutionPath::Direct => Box::new(payment_gateway::DirectGateway),
ExecutionPath::UnifiedConnectorService
| ExecutionPath::ShadowUnifiedConnectorService => Box::new(Self),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.