text stringlengths 81 477k | file_path stringlengths 22 92 | module stringlengths 13 87 | token_count int64 24 94.8k | has_source_code bool 1 class |
|---|---|---|---|---|
// File: crates/router/src/types/domain/user/decision_manager.rs
// Module: router::src::types::domain::user::decision_manager
use common_enums::TokenPurpose;
use common_utils::{id_type, types::user::LineageContext};
use diesel_models::{
enums::{UserRoleVersion, UserStatus},
user_role::UserRole,
};
use error_stack::ResultExt;
use masking::Secret;
use router_env::logger;
use super::UserFromStorage;
use crate::{
core::errors::{UserErrors, UserResult},
db::user_role::ListUserRolesByUserIdPayload,
routes::SessionState,
services::authentication as auth,
utils,
};
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum UserFlow {
SPTFlow(SPTFlow),
JWTFlow(JWTFlow),
}
impl UserFlow {
async fn is_required(
&self,
user: &UserFromStorage,
path: &[TokenPurpose],
state: &SessionState,
user_tenant_id: &id_type::TenantId,
) -> UserResult<bool> {
match self {
Self::SPTFlow(flow) => flow.is_required(user, path, state, user_tenant_id).await,
Self::JWTFlow(flow) => flow.is_required(user, state).await,
}
}
}
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum SPTFlow {
AuthSelect,
SSO,
TOTP,
VerifyEmail,
AcceptInvitationFromEmail,
ForceSetPassword,
MerchantSelect,
ResetPassword,
}
impl SPTFlow {
async fn is_required(
&self,
user: &UserFromStorage,
path: &[TokenPurpose],
state: &SessionState,
user_tenant_id: &id_type::TenantId,
) -> UserResult<bool> {
match self {
// Auth
Self::AuthSelect => Ok(true),
Self::SSO => Ok(true),
// TOTP
Self::TOTP => Ok(!path.contains(&TokenPurpose::SSO)),
// Main email APIs
Self::AcceptInvitationFromEmail | Self::ResetPassword => Ok(true),
Self::VerifyEmail => Ok(true),
// Final Checks
Self::ForceSetPassword => user
.is_password_rotate_required(state)
.map(|rotate_required| rotate_required && !path.contains(&TokenPurpose::SSO)),
Self::MerchantSelect => Ok(state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user.get_user_id(),
tenant_id: user_tenant_id,
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)?
.is_empty()),
}
}
pub async fn generate_spt(
self,
state: &SessionState,
next_flow: &NextFlow,
) -> UserResult<Secret<String>> {
auth::SinglePurposeToken::new_token(
next_flow.user.get_user_id().to_string(),
self.into(),
next_flow.origin.clone(),
&state.conf,
next_flow.path.to_vec(),
Some(state.tenant.tenant_id.clone()),
)
.await
.map(|token| token.into())
}
}
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum JWTFlow {
UserInfo,
}
impl JWTFlow {
async fn is_required(
&self,
_user: &UserFromStorage,
_state: &SessionState,
) -> UserResult<bool> {
Ok(true)
}
pub async fn generate_jwt(
self,
state: &SessionState,
next_flow: &NextFlow,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
let user_id = next_flow.user.get_user_id();
// Fetch lineage context from DB
let lineage_context_from_db = state
.global_store
.find_user_by_id(user_id)
.await
.inspect_err(|e| {
logger::error!(
"Failed to fetch lineage context from DB for user {}: {:?}",
user_id,
e
)
})
.ok()
.and_then(|user| user.lineage_context);
let new_lineage_context = match lineage_context_from_db {
Some(ctx) => {
let tenant_id = ctx.tenant_id.clone();
let user_role_match_v2 = state
.global_store
.find_user_role_by_user_id_and_lineage(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V2,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V2 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v2 {
ctx
} else {
let user_role_match_v1 = state
.global_store
.find_user_role_by_user_id_and_lineage(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V1,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V1 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v1 {
ctx
} else {
// fallback to default lineage if cached context is invalid
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
}
}
None =>
// no cached context found
{
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
};
utils::user::spawn_async_lineage_context_update_to_db(
state,
user_id,
new_lineage_context.clone(),
);
auth::AuthToken::new_token(
new_lineage_context.user_id,
new_lineage_context.merchant_id,
new_lineage_context.role_id,
&state.conf,
new_lineage_context.org_id,
new_lineage_context.profile_id,
Some(new_lineage_context.tenant_id),
)
.await
.map(|token| token.into())
}
pub async fn resolve_lineage_from_user_role(
state: &SessionState,
user_role: &UserRole,
user_id: &str,
) -> UserResult<LineageContext> {
let org_id = utils::user_role::get_single_org_id(state, user_role).await?;
let merchant_id =
utils::user_role::get_single_merchant_id(state, user_role, &org_id).await?;
let profile_id =
utils::user_role::get_single_profile_id(state, user_role, &merchant_id).await?;
Ok(LineageContext {
user_id: user_id.to_string(),
org_id,
merchant_id,
profile_id,
role_id: user_role.role_id.clone(),
tenant_id: user_role.tenant_id.clone(),
})
}
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum Origin {
#[serde(rename = "sign_in_with_sso")]
SignInWithSSO,
SignIn,
SignUp,
MagicLink,
VerifyEmail,
AcceptInvitationFromEmail,
ResetPassword,
}
impl Origin {
fn get_flows(&self) -> &'static [UserFlow] {
match self {
Self::SignInWithSSO => &SIGNIN_WITH_SSO_FLOW,
Self::SignIn => &SIGNIN_FLOW,
Self::SignUp => &SIGNUP_FLOW,
Self::VerifyEmail => &VERIFY_EMAIL_FLOW,
Self::MagicLink => &MAGIC_LINK_FLOW,
Self::AcceptInvitationFromEmail => &ACCEPT_INVITATION_FROM_EMAIL_FLOW,
Self::ResetPassword => &RESET_PASSWORD_FLOW,
}
}
}
const SIGNIN_WITH_SSO_FLOW: [UserFlow; 2] = [
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const SIGNIN_FLOW: [UserFlow; 4] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const SIGNUP_FLOW: [UserFlow; 4] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const MAGIC_LINK_FLOW: [UserFlow; 5] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::VerifyEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const VERIFY_EMAIL_FLOW: [UserFlow; 5] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::VerifyEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::SPTFlow(SPTFlow::MerchantSelect),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const ACCEPT_INVITATION_FROM_EMAIL_FLOW: [UserFlow; 6] = [
UserFlow::SPTFlow(SPTFlow::AuthSelect),
UserFlow::SPTFlow(SPTFlow::SSO),
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::AcceptInvitationFromEmail),
UserFlow::SPTFlow(SPTFlow::ForceSetPassword),
UserFlow::JWTFlow(JWTFlow::UserInfo),
];
const RESET_PASSWORD_FLOW: [UserFlow; 2] = [
UserFlow::SPTFlow(SPTFlow::TOTP),
UserFlow::SPTFlow(SPTFlow::ResetPassword),
];
pub struct CurrentFlow {
origin: Origin,
current_flow_index: usize,
path: Vec<TokenPurpose>,
tenant_id: Option<id_type::TenantId>,
}
impl CurrentFlow {
pub fn new(
token: auth::UserFromSinglePurposeToken,
current_flow: UserFlow,
) -> UserResult<Self> {
let flows = token.origin.get_flows();
let index = flows
.iter()
.position(|flow| flow == ¤t_flow)
.ok_or(UserErrors::InternalServerError)?;
let mut path = token.path;
path.push(current_flow.into());
Ok(Self {
origin: token.origin,
current_flow_index: index,
path,
tenant_id: token.tenant_id,
})
}
pub async fn next(self, user: UserFromStorage, state: &SessionState) -> UserResult<NextFlow> {
let flows = self.origin.get_flows();
let remaining_flows = flows.iter().skip(self.current_flow_index + 1);
for flow in remaining_flows {
if flow
.is_required(
&user,
&self.path,
state,
self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id),
)
.await?
{
return Ok(NextFlow {
origin: self.origin.clone(),
next_flow: *flow,
user,
path: self.path,
tenant_id: self.tenant_id,
});
}
}
Err(UserErrors::InternalServerError.into())
}
}
pub struct NextFlow {
origin: Origin,
next_flow: UserFlow,
user: UserFromStorage,
path: Vec<TokenPurpose>,
tenant_id: Option<id_type::TenantId>,
}
impl NextFlow {
pub async fn from_origin(
origin: Origin,
user: UserFromStorage,
state: &SessionState,
) -> UserResult<Self> {
let flows = origin.get_flows();
let path = vec![];
for flow in flows {
if flow
.is_required(&user, &path, state, &state.tenant.tenant_id)
.await?
{
return Ok(Self {
origin,
next_flow: *flow,
user,
path,
tenant_id: Some(state.tenant.tenant_id.clone()),
});
}
}
Err(UserErrors::InternalServerError.into())
}
pub fn get_flow(&self) -> UserFlow {
self.next_flow
}
pub async fn get_token(&self, state: &SessionState) -> UserResult<Secret<String>> {
match self.next_flow {
UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await,
UserFlow::JWTFlow(jwt_flow) => {
#[cfg(feature = "email")]
{
self.user.get_verification_days_left(state)?;
}
let user_role = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: self.user.get_user_id(),
tenant_id: self.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: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)?
.pop()
.ok_or(UserErrors::InternalServerError)?;
utils::user_role::set_role_info_in_cache_by_user_role(state, &user_role).await;
jwt_flow.generate_jwt(state, self, &user_role).await
}
}
}
pub async fn get_token_with_user_role(
&self,
state: &SessionState,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
match self.next_flow {
UserFlow::SPTFlow(spt_flow) => spt_flow.generate_spt(state, self).await,
UserFlow::JWTFlow(jwt_flow) => {
#[cfg(feature = "email")]
{
self.user.get_verification_days_left(state)?;
}
utils::user_role::set_role_info_in_cache_by_user_role(state, user_role).await;
jwt_flow.generate_jwt(state, self, user_role).await
}
}
}
pub async fn skip(self, user: UserFromStorage, state: &SessionState) -> UserResult<Self> {
let flows = self.origin.get_flows();
let index = flows
.iter()
.position(|flow| flow == &self.get_flow())
.ok_or(UserErrors::InternalServerError)?;
let remaining_flows = flows.iter().skip(index + 1);
for flow in remaining_flows {
if flow
.is_required(&user, &self.path, state, &state.tenant.tenant_id)
.await?
{
return Ok(Self {
origin: self.origin.clone(),
next_flow: *flow,
user,
path: self.path,
tenant_id: Some(state.tenant.tenant_id.clone()),
});
}
}
Err(UserErrors::InternalServerError.into())
}
}
impl From<UserFlow> for TokenPurpose {
fn from(value: UserFlow) -> Self {
match value {
UserFlow::SPTFlow(flow) => flow.into(),
UserFlow::JWTFlow(flow) => flow.into(),
}
}
}
impl From<SPTFlow> for TokenPurpose {
fn from(value: SPTFlow) -> Self {
match value {
SPTFlow::AuthSelect => Self::AuthSelect,
SPTFlow::SSO => Self::SSO,
SPTFlow::TOTP => Self::TOTP,
SPTFlow::VerifyEmail => Self::VerifyEmail,
SPTFlow::AcceptInvitationFromEmail => Self::AcceptInvitationFromEmail,
SPTFlow::MerchantSelect => Self::AcceptInvite,
SPTFlow::ResetPassword => Self::ResetPassword,
SPTFlow::ForceSetPassword => Self::ForceSetPassword,
}
}
}
impl From<JWTFlow> for TokenPurpose {
fn from(value: JWTFlow) -> Self {
match value {
JWTFlow::UserInfo => Self::UserInfo,
}
}
}
impl From<SPTFlow> for UserFlow {
fn from(value: SPTFlow) -> Self {
Self::SPTFlow(value)
}
}
impl From<JWTFlow> for UserFlow {
fn from(value: JWTFlow) -> Self {
Self::JWTFlow(value)
}
}
| crates/router/src/types/domain/user/decision_manager.rs | router::src::types::domain::user::decision_manager | 3,693 | true |
// File: crates/router/src/types/domain/user/user_authentication_method.rs
// Module: router::src::types::domain::user::user_authentication_method
use std::sync::LazyLock;
use common_enums::{Owner, UserAuthType};
use diesel_models::UserAuthenticationMethod;
pub static DEFAULT_USER_AUTH_METHOD: LazyLock<UserAuthenticationMethod> =
LazyLock::new(|| UserAuthenticationMethod {
id: String::from("hyperswitch_default"),
auth_id: String::from("hyperswitch"),
owner_id: String::from("hyperswitch"),
owner_type: Owner::Tenant,
auth_type: UserAuthType::Password,
private_config: None,
public_config: None,
allow_signup: true,
created_at: common_utils::date_time::now(),
last_modified_at: common_utils::date_time::now(),
email_domain: String::from("hyperswitch"),
});
| crates/router/src/types/domain/user/user_authentication_method.rs | router::src::types::domain::user::user_authentication_method | 193 | true |
// File: crates/router/src/core/tokenization.rs
// Module: router::src::core::tokenization
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
use api_models;
#[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 hyperswitch_domain_models;
#[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,
merchant_account: &domain::MerchantAccount,
merchant_key_store: &domain::MerchantKeyStore,
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 key_manager_state = &(&state).into();
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: merchant_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,
&(merchant_key_store.clone()),
key_manager_state,
)
.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,
merchant_context: domain::MerchantContext,
token_id: &id_type::GlobalTokenId,
payload: api_models::tokenization::DeleteTokenDataRequest,
) -> RouterResponse<api_models::tokenization::DeleteTokenDataResponse> {
let db = &*state.store;
let key_manager_state = &(&state).into();
// Retrieve the tokenization record
let tokenization_record = db
.get_entity_id_vault_id_by_token_id(
token_id,
merchant_context.get_merchant_key_store(),
key_manager_state,
)
.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,
&merchant_context,
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,
merchant_context.get_merchant_key_store(),
key_manager_state,
)
.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 key_manager_state = &(&state).into();
let tokenization_record = db
.get_entity_id_vault_id_by_token_id(
&query,
&(merchant_key_store.clone()),
key_manager_state,
)
.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)
}
| crates/router/src/core/tokenization.rs | router::src::core::tokenization | 1,882 | true |
// File: crates/router/src/core/cache.rs
// Module: router::src::core::cache
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"))
}
}
| crates/router/src/core/cache.rs | router::src::core::cache | 236 | true |
// File: crates/router/src/core/locker_migration.rs
// Module: router::src::core::locker_migration
use ::payment_methods::controller::PaymentMethodsController;
#[cfg(feature = "v1")]
use api_models::enums as api_enums;
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_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
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(key_manager_state, 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(key_manager_state, merchant_id, &key_store, constraints)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let mut customers_moved = 0;
let mut cards_moved = 0;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
for customer in domain_customers {
let result = db
.find_payment_method_by_customer_id_merchant_id_list(
key_manager_state,
&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,
&merchant_context,
)
})
.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,
merchant_context: &domain::MerchantContext,
) -> 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,
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_issuing_country: 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,
merchant_context,
}.add_card_hs(
pm_create,
&card_details,
customer_id,
api_enums::LockerChoice::HyperswitchCardVault,
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,
_merchant_context: &domain::MerchantContext,
) -> CustomResult<usize, errors::ApiErrorResponse> {
todo!()
}
| crates/router/src/core/locker_migration.rs | router::src::core::locker_migration | 1,579 | true |
// File: crates/router/src/core/payment_methods.rs
// Module: router::src::core::payment_methods
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::Encryptable,
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};
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,
merchant_context: domain::MerchantContext,
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,
&merchant_context,
&req,
)
.await?;
// Create DB entry
let pm_collect_link = create_pm_collect_db_entry(
&state,
&merchant_context,
&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,
merchant_context: &domain::MerchantContext,
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: merchant_context.get_merchant_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,
_merchant_context: domain::MerchantContext,
_req: payment_methods::PaymentMethodCollectLinkRenderRequest,
) -> RouterResponse<services::GenericLinkFormData> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn render_pm_collect_link(
state: SessionState,
merchant_context: domain::MerchantContext,
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(
&(&state).into(),
&customer_id,
&req.merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(
merchant_context
.get_merchant_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,
) -> 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,
)
.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,
},
};
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: id_type::GlobalCustomerId,
billing_address: Option<&api_models::payments::Address>,
payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>,
) -> 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: customer_id.clone(),
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()),
};
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_network: card_network.clone(),
card_issuer: card.card_issuer.clone(),
card_type: card.card_type.clone(),
};
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,
};
Ok(payment_method_request)
}
_ => {
let payment_method_request = payment_methods::PaymentMethodCreate {
payment_method: Some(payment_method),
payment_method_type,
payment_method_issuer: None,
payment_method_issuer_code: None,
#[cfg(feature = "payouts")]
bank_transfer: None,
#[cfg(feature = "payouts")]
wallet: None,
card: None,
metadata: None,
customer_id: customer_id.clone(),
card_network: None,
client_secret: None,
payment_method_data: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
};
Ok(payment_method_request)
}
},
None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_type"
})
.attach_printable("PaymentMethodType Required")),
},
None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_data"
})
.attach_printable("PaymentMethodData required Or Card is already saved")),
}
}
/// Determines the appropriate card network to to be stored.
///
/// If the provided card network is a US local network, this function attempts to
/// override it with the first global network from the co-badged card data, if available.
/// Otherwise, it returns the original card network as-is.
///
fn get_card_network_with_us_local_debit_network_override(
card_network: Option<common_enums::CardNetwork>,
co_badged_card_data: Option<&payment_methods::CoBadgedCardData>,
) -> Option<common_enums::CardNetwork> {
if let Some(true) = card_network
.as_ref()
.map(|network| network.is_us_local_network())
{
services::logger::debug!("Card network is a US local network, checking for global network in co-badged card data");
let info: Option<api_models::open_router::CoBadgedCardNetworksInfo> = co_badged_card_data
.and_then(|data| {
data.co_badged_card_networks_info
.0
.iter()
.find(|info| info.network.is_signature_network())
.cloned()
});
info.map(|data| data.network)
} else {
card_network
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn create_payment_method(
state: &SessionState,
request_state: &routes::app::ReqState,
req: api::PaymentMethodCreate,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> RouterResponse<api::PaymentMethodResponse> {
// payment_method is for internal use, can never be populated in response
let (response, _payment_method) = Box::pin(create_payment_method_core(
state,
request_state,
req,
merchant_context,
profile,
))
.await?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn create_payment_method_core(
state: &SessionState,
_request_state: &routes::app::ReqState,
req: api::PaymentMethodCreate,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {
use common_utils::ext_traits::ValueExt;
req.validate()?;
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = req.customer_id.to_owned();
let key_manager_state = &(state).into();
db.find_customer_by_global_id(
key_manager_state,
&customer_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Customer not found for the payment method")?;
let payment_method_billing_address = req
.billing
.clone()
.async_map(|billing| {
cards::create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
billing,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?
.map(|encoded_address| {
encoded_address.deserialize_inner_value(|value| value.parse_value("address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse Payment method billing address")?;
let payment_method_id =
id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
match &req.payment_method_data {
api::PaymentMethodCreateData::Card(_) => {
Box::pin(create_payment_method_card_core(
state,
req,
merchant_context,
profile,
merchant_id,
&customer_id,
payment_method_id,
payment_method_billing_address,
))
.await
}
api::PaymentMethodCreateData::ProxyCard(_) => {
create_payment_method_proxy_card_core(
state,
req,
merchant_context,
profile,
merchant_id,
&customer_id,
payment_method_id,
payment_method_billing_address,
)
.await
}
}
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn create_payment_method_card_core(
state: &SessionState,
req: api::PaymentMethodCreate,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::GlobalCustomerId,
payment_method_id: id_type::GlobalPaymentMethodId,
payment_method_billing_address: Option<
Encryptable<hyperswitch_domain_models::address::Address>,
>,
) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {
let db = &*state.store;
let payment_method = create_payment_method_for_intent(
state,
req.metadata.clone(),
customer_id,
payment_method_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
payment_method_billing_address,
)
.await
.attach_printable("failed to add payment method to db")?;
let payment_method_data = domain::PaymentMethodVaultingData::try_from(req.payment_method_data)?
.populate_bin_details_for_payment_method(state)
.await;
let vaulting_result = vault_payment_method(
state,
&payment_method_data,
merchant_context,
profile,
None,
customer_id,
)
.await;
let network_tokenization_resp = network_tokenize_and_vault_the_pmd(
state,
&payment_method_data,
merchant_context,
req.network_tokenization.clone(),
profile.is_network_tokenization_enabled,
customer_id,
)
.await;
let (response, payment_method) = match vaulting_result {
Ok((
pm_types::AddVaultResponse {
vault_id,
fingerprint_id,
..
},
external_vault_source,
)) => {
let pm_update = create_pm_additional_data_update(
Some(&payment_method_data),
state,
merchant_context.get_merchant_key_store(),
Some(vault_id.get_string_repr().clone()),
fingerprint_id,
&payment_method,
None,
network_tokenization_resp,
Some(req.payment_method_type),
Some(req.payment_method_subtype),
external_vault_source,
)
.await
.attach_printable("unable to create payment method data")?;
let payment_method = db
.update_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?;
Ok((resp, payment_method))
}
Err(e) => {
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
Err(e)
}
}?;
Ok((response, payment_method))
}
// network tokenization and vaulting to locker is not required for proxy card since the card is already tokenized
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn create_payment_method_proxy_card_core(
state: &SessionState,
req: api::PaymentMethodCreate,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::GlobalCustomerId,
payment_method_id: id_type::GlobalPaymentMethodId,
payment_method_billing_address: Option<
Encryptable<hyperswitch_domain_models::address::Address>,
>,
) -> RouterResult<(api::PaymentMethodResponse, domain::PaymentMethod)> {
use crate::core::payment_methods::vault::Vault;
let key_manager_state = &(state).into();
let external_vault_source = profile
.external_vault_connector_details
.clone()
.map(|details| details.vault_connector_id);
let additional_payment_method_data = Some(
req.payment_method_data
.populate_bin_details_for_payment_method(state)
.await
.convert_to_additional_payment_method_data()?,
);
let encrypted_payment_method_data = additional_payment_method_data
.async_map(|payment_method_data| {
cards::create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method_data,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method data")?
.map(|encoded_pmd| {
encoded_pmd.deserialize_inner_value(|value| value.parse_value("PaymentMethodsData"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse Payment method data")?;
let external_vault_token_data = req.payment_method_data.get_external_vault_token_data();
let encrypted_external_vault_token_data = external_vault_token_data
.async_map(|external_vault_token_data| {
cards::create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
external_vault_token_data,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt External vault token data")?
.map(|encoded_data| {
encoded_data
.deserialize_inner_value(|value| value.parse_value("ExternalVaultTokenData"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse External vault token data")?;
let vault_type = external_vault_source
.is_some()
.then_some(common_enums::VaultType::External);
let payment_method = create_payment_method_for_confirm(
state,
customer_id,
payment_method_id,
external_vault_source,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
req.payment_method_type,
req.payment_method_subtype,
payment_method_billing_address,
encrypted_payment_method_data,
encrypted_external_vault_token_data,
vault_type,
)
.await?;
let payment_method_response =
pm_transforms::generate_payment_method_response(&payment_method, &None)?;
Ok((payment_method_response, payment_method))
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct NetworkTokenPaymentMethodDetails {
network_token_requestor_reference_id: String,
network_token_locker_id: String,
network_token_pmd: Encryptable<Secret<serde_json::Value>>,
}
#[cfg(feature = "v2")]
pub async fn network_tokenize_and_vault_the_pmd(
state: &SessionState,
payment_method_data: &domain::PaymentMethodVaultingData,
merchant_context: &domain::MerchantContext,
network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
network_tokenization_enabled_for_profile: bool,
customer_id: &id_type::GlobalCustomerId,
) -> Option<NetworkTokenPaymentMethodDetails> {
let network_token_pm_details_result: CustomResult<
NetworkTokenPaymentMethodDetails,
errors::NetworkTokenizationError,
> = async {
when(!network_tokenization_enabled_for_profile, || {
Err(report!(
errors::NetworkTokenizationError::NetworkTokenizationNotEnabledForProfile
))
})?;
let is_network_tokenization_enabled_for_pm = network_tokenization
.as_ref()
.map(|nt| matches!(nt.enable, common_enums::NetworkTokenizationToggle::Enable))
.unwrap_or(false);
let card_data = payment_method_data
.get_card()
.and_then(|card| is_network_tokenization_enabled_for_pm.then_some(card))
.ok_or_else(|| {
report!(errors::NetworkTokenizationError::NotSupported {
message: "Payment method".to_string(),
})
})?;
let (resp, network_token_req_ref_id) =
network_tokenization::make_card_network_tokenization_request(
state,
card_data,
customer_id,
)
.await?;
let network_token_vaulting_data = domain::PaymentMethodVaultingData::NetworkToken(resp);
let vaulting_resp = vault::add_payment_method_to_vault(
state,
merchant_context,
&network_token_vaulting_data,
None,
customer_id,
)
.await
.change_context(errors::NetworkTokenizationError::SaveNetworkTokenFailed)
.attach_printable("Failed to vault network token")?;
let key_manager_state = &(state).into();
let network_token_pmd = cards::create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
network_token_vaulting_data.get_payment_methods_data(),
)
.await
.change_context(errors::NetworkTokenizationError::NetworkTokenDetailsEncryptionFailed)
.attach_printable("Failed to encrypt PaymentMethodsData")?;
Ok(NetworkTokenPaymentMethodDetails {
network_token_requestor_reference_id: network_token_req_ref_id,
network_token_locker_id: vaulting_resp.vault_id.get_string_repr().clone(),
network_token_pmd,
})
}
.await;
network_token_pm_details_result.ok()
}
#[cfg(feature = "v2")]
pub async fn populate_bin_details_for_payment_method(
state: &SessionState,
payment_method_data: &domain::PaymentMethodVaultingData,
) -> domain::PaymentMethodVaultingData {
match payment_method_data {
domain::PaymentMethodVaultingData::Card(card) => {
let card_isin = card.card_number.get_card_isin();
if card.card_issuer.is_some()
&& card.card_network.is_some()
&& card.card_type.is_some()
&& card.card_issuing_country.is_some()
{
domain::PaymentMethodVaultingData::Card(card.clone())
} else {
let card_info = state
.store
.get_card_info(&card_isin)
.await
.map_err(|error| services::logger::error!(card_info_error=?error))
.ok()
.flatten();
domain::PaymentMethodVaultingData::Card(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_info.as_ref().and_then(|val| {
val.card_issuing_country
.as_ref()
.map(|c| api_enums::CountryAlpha2::from_str(c))
.transpose()
.ok()
.flatten()
}),
card_network: card_info.as_ref().and_then(|val| val.card_network.clone()),
card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()),
card_type: card_info.as_ref().and_then(|val| {
val.card_type
.as_ref()
.map(|c| payment_methods::CardType::from_str(c))
.transpose()
.ok()
.flatten()
}),
card_cvc: card.card_cvc.clone(),
})
}
}
_ => payment_method_data.clone(),
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
pub trait PaymentMethodExt {
async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self;
// convert to data format compatible to save in payment method table
fn convert_to_additional_payment_method_data(
&self,
) -> RouterResult<payment_methods::PaymentMethodsData>;
// get tokens generated from external vault
fn get_external_vault_token_data(&self) -> Option<payment_methods::ExternalVaultTokenData>;
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl PaymentMethodExt for domain::PaymentMethodVaultingData {
async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self {
match self {
Self::Card(card) => {
let card_isin = card.card_number.get_card_isin();
if card.card_issuer.is_some()
&& card.card_network.is_some()
&& card.card_type.is_some()
&& card.card_issuing_country.is_some()
{
Self::Card(card.clone())
} else {
let card_info = state
.store
.get_card_info(&card_isin)
.await
.map_err(|error| services::logger::error!(card_info_error=?error))
.ok()
.flatten();
Self::Card(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_info.as_ref().and_then(|val| {
val.card_issuing_country
.as_ref()
.map(|c| api_enums::CountryAlpha2::from_str(c))
.transpose()
.ok()
.flatten()
}),
card_network: card_info.as_ref().and_then(|val| val.card_network.clone()),
card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()),
card_type: card_info.as_ref().and_then(|val| {
val.card_type
.as_ref()
.map(|c| payment_methods::CardType::from_str(c))
.transpose()
.ok()
.flatten()
}),
card_cvc: card.card_cvc.clone(),
})
}
}
_ => self.clone(),
}
}
// Not implement because it is saved in locker and not in payment method table
fn convert_to_additional_payment_method_data(
&self,
) -> RouterResult<payment_methods::PaymentMethodsData> {
Err(report!(errors::ApiErrorResponse::UnprocessableEntity {
message: "Payment method data is not supported".to_string()
})
.attach_printable("Payment method data is not supported"))
}
fn get_external_vault_token_data(&self) -> Option<payment_methods::ExternalVaultTokenData> {
None
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl PaymentMethodExt for payment_methods::PaymentMethodCreateData {
async fn populate_bin_details_for_payment_method(&self, state: &SessionState) -> Self {
match self {
Self::ProxyCard(card) => {
let card_isin = card.bin_number.clone();
if card.card_issuer.is_some()
&& card.card_network.is_some()
&& card.card_type.is_some()
&& card.card_issuing_country.is_some()
{
Self::ProxyCard(card.clone())
} else if let Some(card_isin) = card_isin {
let card_info = state
.store
.get_card_info(&card_isin)
.await
.map_err(|error| services::logger::error!(card_info_error=?error))
.ok()
.flatten();
Self::ProxyCard(payment_methods::ProxyCardDetails {
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(),
bin_number: card.bin_number.clone(),
last_four: card.last_four.clone(),
nick_name: card.nick_name.clone(),
card_issuing_country: card_info
.as_ref()
.and_then(|val| val.card_issuing_country.clone()),
card_network: card_info.as_ref().and_then(|val| val.card_network.clone()),
card_issuer: card_info.as_ref().and_then(|val| val.card_issuer.clone()),
card_type: card_info.as_ref().and_then(|val| val.card_type.clone()),
card_cvc: card.card_cvc.clone(),
})
} else {
Self::ProxyCard(card.clone())
}
}
_ => self.clone(),
}
}
fn convert_to_additional_payment_method_data(
&self,
) -> RouterResult<payment_methods::PaymentMethodsData> {
match self.clone() {
Self::ProxyCard(card_details) => Ok(payment_methods::PaymentMethodsData::Card(
payment_methods::CardDetailsPaymentMethod {
last4_digits: card_details.last_four,
expiry_month: Some(card_details.card_exp_month),
expiry_year: Some(card_details.card_exp_year),
card_holder_name: card_details.card_holder_name,
nick_name: card_details.nick_name,
issuer_country: card_details.card_issuing_country,
card_network: card_details.card_network,
card_issuer: card_details.card_issuer,
card_type: card_details.card_type,
card_isin: card_details.bin_number,
saved_to_locker: false,
co_badged_card_data: None,
},
)),
Self::Card(card_details) => Ok(payment_methods::PaymentMethodsData::Card(
payment_methods::CardDetailsPaymentMethod {
expiry_month: Some(card_details.card_exp_month),
expiry_year: Some(card_details.card_exp_year),
card_holder_name: card_details.card_holder_name,
nick_name: card_details.nick_name,
issuer_country: card_details
.card_issuing_country
.map(|country| country.to_string()),
card_network: card_details.card_network,
card_issuer: card_details.card_issuer,
card_type: card_details
.card_type
.map(|card_type| card_type.to_string()),
saved_to_locker: false,
card_isin: None,
last4_digits: None,
co_badged_card_data: None,
},
)),
}
}
fn get_external_vault_token_data(&self) -> Option<payment_methods::ExternalVaultTokenData> {
match self.clone() {
Self::ProxyCard(card_details) => Some(payment_methods::ExternalVaultTokenData {
tokenized_card_number: card_details.card_number,
}),
Self::Card(_) => None,
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn payment_method_intent_create(
state: &SessionState,
req: api::PaymentMethodIntentCreate,
merchant_context: &domain::MerchantContext,
) -> RouterResponse<api::PaymentMethodResponse> {
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = req.customer_id.to_owned();
let key_manager_state = &(state).into();
db.find_customer_by_global_id(
key_manager_state,
&customer_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Customer not found for the payment method")?;
let payment_method_billing_address = req
.billing
.clone()
.async_map(|billing| {
cards::create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
billing,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?
.map(|encoded_address| {
encoded_address.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse Payment method billing address")?;
// create pm entry
let payment_method_id =
id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method = create_payment_method_for_intent(
state,
req.metadata.clone(),
&customer_id,
payment_method_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
payment_method_billing_address,
)
.await
.attach_printable("Failed to add Payment method to DB")?;
let resp = pm_transforms::generate_payment_method_response(&payment_method, &None)?;
Ok(services::ApplicationResponse::Json(resp))
}
#[cfg(feature = "v2")]
trait PerformFilteringOnEnabledPaymentMethods {
fn perform_filtering(self) -> FilteredPaymentMethodsEnabled;
}
#[cfg(feature = "v2")]
impl PerformFilteringOnEnabledPaymentMethods
for hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled
{
fn perform_filtering(self) -> FilteredPaymentMethodsEnabled {
FilteredPaymentMethodsEnabled(self.payment_methods_enabled)
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn list_payment_methods_for_session(
state: SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
) -> RouterResponse<api::PaymentMethodListResponseForSession> {
let key_manager_state = &(&state).into();
let db = &*state.store;
let payment_method_session = db
.get_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?;
let payment_connector_accounts = db
.list_enabled_connector_accounts_by_profile_id(
key_manager_state,
profile.get_id(),
merchant_context.get_merchant_key_store(),
common_enums::ConnectorType::PaymentProcessor,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error when fetching merchant connector accounts")?;
let customer_payment_methods = list_customer_payment_methods_core(
&state,
&merchant_context,
&payment_method_session.customer_id,
)
.await?;
let response =
hyperswitch_domain_models::merchant_connector_account::FlattenedPaymentMethodsEnabled::from_payment_connectors_list(payment_connector_accounts)
.perform_filtering()
.get_required_fields(RequiredFieldsInput::new(state.conf.required_fields.clone()))
.generate_response_for_session(customer_payment_methods);
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
pub async fn list_saved_payment_methods_for_customer(
state: SessionState,
merchant_context: domain::MerchantContext,
customer_id: id_type::GlobalCustomerId,
) -> RouterResponse<payment_methods::CustomerPaymentMethodsListResponse> {
let customer_payment_methods =
list_payment_methods_core(&state, &merchant_context, &customer_id).await?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
customer_payment_methods,
))
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
pub async fn get_token_data_for_payment_method(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
profile: domain::Profile,
request: payment_methods::GetTokenDataRequest,
payment_method_id: id_type::GlobalPaymentMethodId,
) -> RouterResponse<api::TokenDataResponse> {
let key_manager_state = &(&state).into();
let db = &*state.store;
let payment_method = db
.find_payment_method(
key_manager_state,
&key_store,
&payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let token_data_response =
generate_token_data_response(&state, request, profile, &payment_method).await?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
token_data_response,
))
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
pub async fn generate_token_data_response(
state: &SessionState,
request: payment_methods::GetTokenDataRequest,
profile: domain::Profile,
payment_method: &domain::PaymentMethod,
) -> RouterResult<api::TokenDataResponse> {
let token_details = match request.token_type {
common_enums::TokenDataType::NetworkToken => {
let is_network_tokenization_enabled = profile.is_network_tokenization_enabled;
if !is_network_tokenization_enabled {
return Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "Network tokenization is not enabled for this profile".to_string(),
}
.into());
}
let network_token_requestor_ref_id = payment_method
.network_token_requestor_reference_id
.clone()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "NetworkTokenRequestorReferenceId is not present".to_string(),
})?;
let network_token = network_tokenization::get_token_from_tokenization_service(
state,
network_token_requestor_ref_id,
payment_method,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch network token data from tokenization service")?;
api::TokenDetailsResponse::NetworkTokenDetails(api::NetworkTokenDetailsResponse {
network_token: network_token.network_token,
network_token_exp_month: network_token.network_token_exp_month,
network_token_exp_year: network_token.network_token_exp_year,
cryptogram: network_token.cryptogram,
card_issuer: network_token.card_issuer,
card_network: network_token.card_network,
card_type: network_token.card_type,
card_issuing_country: network_token.card_issuing_country,
bank_code: network_token.bank_code,
card_holder_name: network_token.card_holder_name,
nick_name: network_token.nick_name,
eci: network_token.eci,
})
}
common_enums::TokenDataType::SingleUseToken
| common_enums::TokenDataType::MultiUseToken => {
return Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "Token type not supported".to_string(),
}
.into());
}
};
Ok(api::TokenDataResponse {
payment_method_id: payment_method.id.clone(),
token_type: request.token_type,
token_details,
})
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
pub async fn get_total_saved_payment_methods_for_merchant(
state: SessionState,
merchant_context: domain::MerchantContext,
) -> RouterResponse<api::TotalPaymentMethodCountResponse> {
let total_payment_method_count =
get_total_payment_method_count_core(&state, &merchant_context).await?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
total_payment_method_count,
))
}
#[cfg(feature = "v2")]
/// Container for the inputs required for the required fields
struct RequiredFieldsInput {
required_fields_config: settings::RequiredFields,
}
#[cfg(feature = "v2")]
impl RequiredFieldsInput {
fn new(required_fields_config: settings::RequiredFields) -> Self {
Self {
required_fields_config,
}
}
}
#[cfg(feature = "v2")]
/// Container for the filtered payment methods
struct FilteredPaymentMethodsEnabled(
Vec<hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector>,
);
#[cfg(feature = "v2")]
trait GetRequiredFields {
fn get_required_fields(
&self,
payment_method_enabled: &hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
) -> Option<&settings::RequiredFieldFinal>;
}
#[cfg(feature = "v2")]
impl GetRequiredFields for settings::RequiredFields {
fn get_required_fields(
&self,
payment_method_enabled: &hyperswitch_domain_models::merchant_connector_account::PaymentMethodsEnabledForConnector,
) -> Option<&settings::RequiredFieldFinal> {
self.0
.get(&payment_method_enabled.payment_method)
.and_then(|required_fields_for_payment_method| {
required_fields_for_payment_method.0.get(
&payment_method_enabled
.payment_methods_enabled
.payment_method_subtype,
)
})
.map(|connector_fields| &connector_fields.fields)
.and_then(|connector_hashmap| connector_hashmap.get(&payment_method_enabled.connector))
}
}
#[cfg(feature = "v2")]
impl FilteredPaymentMethodsEnabled {
fn get_required_fields(
self,
input: RequiredFieldsInput,
) -> RequiredFieldsForEnabledPaymentMethodTypes {
let required_fields_config = input.required_fields_config;
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);
// Combine both common and mandate required fields
common_required_fields
.chain(mandate_required_fields)
.collect::<Vec<_>>()
})
.unwrap_or_default();
RequiredFieldsForEnabledPaymentMethod {
required_fields,
payment_method_type: payment_methods_enabled.payment_method,
payment_method_subtype: payment_methods_enabled
.payment_methods_enabled
.payment_method_subtype,
}
})
.collect();
RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info)
}
}
#[cfg(feature = "v2")]
/// Element container to hold the filtered payment methods with required fields
struct RequiredFieldsForEnabledPaymentMethod {
required_fields: Vec<payment_methods::RequiredFieldInfo>,
payment_method_subtype: common_enums::PaymentMethodType,
payment_method_type: common_enums::PaymentMethod,
}
#[cfg(feature = "v2")]
/// Container to hold the filtered payment methods enabled with required fields
struct RequiredFieldsForEnabledPaymentMethodTypes(Vec<RequiredFieldsForEnabledPaymentMethod>);
#[cfg(feature = "v2")]
impl RequiredFieldsForEnabledPaymentMethodTypes {
fn generate_response_for_session(
self,
customer_payment_methods: Vec<payment_methods::CustomerPaymentMethodResponseItem>,
) -> payment_methods::PaymentMethodListResponseForSession {
let response_payment_methods = self
.0
.into_iter()
.map(
|payment_methods_enabled| payment_methods::ResponsePaymentMethodTypes {
payment_method_type: payment_methods_enabled.payment_method_type,
payment_method_subtype: payment_methods_enabled.payment_method_subtype,
required_fields: payment_methods_enabled.required_fields,
extra_information: None,
},
)
.collect();
payment_methods::PaymentMethodListResponseForSession {
payment_methods_enabled: response_payment_methods,
customer_payment_methods,
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn create_payment_method_for_intent(
state: &SessionState,
metadata: Option<common_utils::pii::SecretSerdeValue>,
customer_id: &id_type::GlobalCustomerId,
payment_method_id: id_type::GlobalPaymentMethodId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
payment_method_billing_address: Option<
Encryptable<hyperswitch_domain_models::address::Address>,
>,
) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
use josekit::jwe::zip::deflate::DeflateJweCompression::Def;
let db = &*state.store;
let current_time = common_utils::date_time::now();
let response = db
.insert_payment_method(
&state.into(),
key_store,
domain::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
id: payment_method_id,
locker_id: None,
payment_method_type: None,
payment_method_subtype: None,
payment_method_data: None,
connector_mandate_details: None,
customer_acceptance: None,
client_secret: None,
status: enums::PaymentMethodStatus::AwaitingData,
network_transaction_id: None,
created_at: current_time,
last_modified: current_time,
last_used_at: current_time,
payment_method_billing_address,
updated_by: None,
version: common_types::consts::API_VERSION,
locker_fingerprint_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
network_token_requestor_reference_id: None,
external_vault_source: None,
external_vault_token_data: None,
vault_type: None,
},
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
Ok(response)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn create_payment_method_for_confirm(
state: &SessionState,
customer_id: &id_type::GlobalCustomerId,
payment_method_id: id_type::GlobalPaymentMethodId,
external_vault_source: Option<id_type::MerchantConnectorAccountId>,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
payment_method_type: storage_enums::PaymentMethod,
payment_method_subtype: storage_enums::PaymentMethodType,
encrypted_payment_method_billing_address: Option<
Encryptable<hyperswitch_domain_models::address::Address>,
>,
encrypted_payment_method_data: Option<Encryptable<payment_methods::PaymentMethodsData>>,
encrypted_external_vault_token_data: Option<
Encryptable<payment_methods::ExternalVaultTokenData>,
>,
vault_type: Option<common_enums::VaultType>,
) -> CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
let db = &*state.store;
let key_manager_state = &state.into();
let current_time = common_utils::date_time::now();
let response = db
.insert_payment_method(
key_manager_state,
key_store,
domain::PaymentMethod {
customer_id: customer_id.to_owned(),
merchant_id: merchant_id.to_owned(),
id: payment_method_id,
locker_id: None,
payment_method_type: Some(payment_method_type),
payment_method_subtype: Some(payment_method_subtype),
payment_method_data: encrypted_payment_method_data,
connector_mandate_details: None,
customer_acceptance: None,
client_secret: None,
status: enums::PaymentMethodStatus::Inactive,
network_transaction_id: None,
created_at: current_time,
last_modified: current_time,
last_used_at: current_time,
payment_method_billing_address: encrypted_payment_method_billing_address,
updated_by: None,
version: common_types::consts::API_VERSION,
locker_fingerprint_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
network_token_requestor_reference_id: None,
external_vault_source,
external_vault_token_data: encrypted_external_vault_token_data,
vault_type,
},
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
Ok(response)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn get_external_vault_token(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
payment_token: String,
vault_token: domain::VaultToken,
payment_method_type: &storage_enums::PaymentMethod,
) -> CustomResult<domain::ExternalVaultPaymentMethodData, errors::ApiErrorResponse> {
let db = &*state.store;
let pm_token_data =
utils::retrieve_payment_token_data(state, payment_token, Some(payment_method_type)).await?;
let payment_method_id = match pm_token_data {
storage::PaymentTokenData::PermanentCard(card_token_data) => {
card_token_data.payment_method_id
}
storage::PaymentTokenData::TemporaryGeneric(_) => {
Err(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"TemporaryGeneric Token not implemented".to_string(),
),
})?
}
storage::PaymentTokenData::AuthBankDebit(_) => {
Err(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"AuthBankDebit Token not implemented".to_string(),
),
})?
}
};
let payment_method = db
.find_payment_method(&state.into(), key_store, &payment_method_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Payment method not found")?;
let external_vault_token_data = payment_method
.external_vault_token_data
.clone()
.map(Encryptable::into_inner)
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing vault token data")?;
let decrypted_addtional_payment_method_data = payment_method
.payment_method_data
.clone()
.map(Encryptable::into_inner)
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert payment method data")?;
convert_from_saved_payment_method_data(
decrypted_addtional_payment_method_data,
external_vault_token_data,
vault_token,
)
.attach_printable("Failed to convert payment method data")
}
#[cfg(feature = "v2")]
fn convert_from_saved_payment_method_data(
vault_additional_data: payment_methods::PaymentMethodsData,
external_vault_token_data: payment_methods::ExternalVaultTokenData,
vault_token: domain::VaultToken,
) -> RouterResult<domain::ExternalVaultPaymentMethodData> {
match vault_additional_data {
payment_methods::PaymentMethodsData::Card(card_details) => {
Ok(domain::ExternalVaultPaymentMethodData::Card(Box::new(
domain::ExternalVaultCard {
card_number: external_vault_token_data.tokenized_card_number,
card_exp_month: card_details.expiry_month.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "card_details.expiry_month",
},
)?,
card_exp_year: card_details.expiry_year.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "card_details.expiry_year",
},
)?,
card_holder_name: card_details.card_holder_name,
bin_number: card_details.card_isin,
last_four: card_details.last4_digits,
nick_name: card_details.nick_name,
card_issuing_country: card_details.issuer_country,
card_network: card_details.card_network,
card_issuer: card_details.card_issuer,
card_type: card_details.card_type,
card_cvc: vault_token.card_cvc,
co_badged_card_data: None, // Co-badged data is not supported in external vault
bank_code: None, // Bank code is not stored in external vault
},
)))
}
payment_methods::PaymentMethodsData::BankDetails(_)
| payment_methods::PaymentMethodsData::WalletDetails(_) => {
Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "External vaulting is not supported for this payment method type"
.to_string(),
}
.into())
}
}
}
#[cfg(feature = "v2")]
/// Update the connector_mandate_details of the payment method with
/// new token details for the payment
fn create_connector_token_details_update(
token_details: payment_methods::ConnectorTokenDetails,
payment_method: &domain::PaymentMethod,
) -> hyperswitch_domain_models::mandates::CommonMandateReference {
let connector_id = token_details.connector_id.clone();
let reference_record =
hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord::foreign_from(
token_details,
);
let connector_token_details = payment_method.connector_mandate_details.clone();
match connector_token_details {
Some(mut connector_mandate_reference) => {
connector_mandate_reference
.insert_payment_token_reference_record(&connector_id, reference_record);
connector_mandate_reference
}
None => {
let reference_record_hash_map =
std::collections::HashMap::from([(connector_id, reference_record)]);
let payments_mandate_reference =
hyperswitch_domain_models::mandates::PaymentsTokenReference(
reference_record_hash_map,
);
hyperswitch_domain_models::mandates::CommonMandateReference {
payments: Some(payments_mandate_reference),
payouts: None,
}
}
}
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn create_pm_additional_data_update(
pmd: Option<&domain::PaymentMethodVaultingData>,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
vault_id: Option<String>,
vault_fingerprint_id: Option<String>,
payment_method: &domain::PaymentMethod,
connector_token_details: Option<payment_methods::ConnectorTokenDetails>,
nt_data: Option<NetworkTokenPaymentMethodDetails>,
payment_method_type: Option<common_enums::PaymentMethod>,
payment_method_subtype: Option<common_enums::PaymentMethodType>,
external_vault_source: Option<id_type::MerchantConnectorAccountId>,
) -> RouterResult<storage::PaymentMethodUpdate> {
let encrypted_payment_method_data = pmd
.map(|payment_method_vaulting_data| payment_method_vaulting_data.get_payment_methods_data())
.async_map(|payment_method_details| async {
let key_manager_state = &(state).into();
cards::create_encrypted_data(key_manager_state, key_store, payment_method_details)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method data")
})
.await
.transpose()?
.map(From::from);
let connector_mandate_details_update = connector_token_details
.map(|connector_token| {
create_connector_token_details_update(connector_token, payment_method)
})
.map(From::from);
let pm_update = storage::PaymentMethodUpdate::GenericUpdate {
// A new payment method is created with inactive state
// It will be marked active after payment succeeds
status: Some(enums::PaymentMethodStatus::Inactive),
locker_id: vault_id,
payment_method_type_v2: payment_method_type,
payment_method_subtype,
payment_method_data: encrypted_payment_method_data,
network_token_requestor_reference_id: nt_data
.clone()
.map(|data| data.network_token_requestor_reference_id),
network_token_locker_id: nt_data.clone().map(|data| data.network_token_locker_id),
network_token_payment_method_data: nt_data.map(|data| data.network_token_pmd.into()),
connector_mandate_details: connector_mandate_details_update,
locker_fingerprint_id: vault_fingerprint_id,
external_vault_source,
};
Ok(pm_update)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn vault_payment_method_internal(
state: &SessionState,
pmd: &domain::PaymentMethodVaultingData,
merchant_context: &domain::MerchantContext,
existing_vault_id: Option<domain::VaultId>,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<pm_types::AddVaultResponse> {
let db = &*state.store;
// get fingerprint_id from vault
let fingerprint_id_from_vault =
vault::get_fingerprint_id_from_vault(state, pmd, customer_id.get_string_repr().to_owned())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get fingerprint_id from vault")?;
// throw back error if payment method is duplicated
when(
db.find_payment_method_by_fingerprint_id(
&(state.into()),
merchant_context.get_merchant_key_store(),
&fingerprint_id_from_vault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find payment method by fingerprint_id")
.inspect_err(|e| logger::error!("Vault Fingerprint_id error: {:?}", e))
.is_ok(),
|| {
Err(report!(errors::ApiErrorResponse::DuplicatePaymentMethod)
.attach_printable("Cannot vault duplicate payment method"))
},
)?;
let mut resp_from_vault = vault::add_payment_method_to_vault(
state,
merchant_context,
pmd,
existing_vault_id,
customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in vault")?;
// add fingerprint_id to the response
resp_from_vault.fingerprint_id = Some(fingerprint_id_from_vault);
Ok(resp_from_vault)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn vault_payment_method_external(
state: &SessionState,
pmd: &domain::PaymentMethodVaultingData,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
) -> RouterResult<pm_types::AddVaultResponse> {
let merchant_connector_account = match &merchant_connector_account {
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 router_data = core_utils::construct_vault_router_data(
state,
merchant_account.get_id(),
merchant_connector_account,
Some(pmd.clone()),
None,
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 insert api call",
)?;
let connector_name = merchant_connector_account.get_connector_name_as_string(); // always get the connector name from this call
let connector_data = api::ConnectorData::get_external_vault_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultInsertFlow,
types::VaultRequestData,
types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
payments_core::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()?;
get_vault_response_for_insert_payment_method_data(router_data_resp)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn vault_payment_method_external_v1(
state: &SessionState,
pmd: &hyperswitch_domain_models::vault::PaymentMethodVaultingData,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
) -> RouterResult<pm_types::AddVaultResponse> {
let router_data = core_utils::construct_vault_router_data(
state,
merchant_account.get_id(),
&merchant_connector_account,
Some(pmd.clone()),
None,
None,
)
.await?;
let 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 insert api call",
)?;
let connector_name = merchant_connector_account.get_connector_name_as_string();
let connector_data = api::ConnectorData::get_external_vault_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultInsertFlow,
types::VaultRequestData,
types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
payments_core::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()?;
get_vault_response_for_insert_payment_method_data(router_data_resp)
}
pub fn get_vault_response_for_insert_payment_method_data<F>(
router_data: VaultRouterData<F>,
) -> RouterResult<pm_types::AddVaultResponse> {
match router_data.response {
Ok(response) => match response {
types::VaultResponseData::ExternalVaultInsertResponse {
connector_vault_id,
fingerprint_id,
} => {
#[cfg(feature = "v2")]
let vault_id = domain::VaultId::generate(connector_vault_id);
#[cfg(not(feature = "v2"))]
let vault_id = connector_vault_id;
Ok(pm_types::AddVaultResponse {
vault_id,
fingerprint_id: Some(fingerprint_id),
entity_id: None,
})
}
types::VaultResponseData::ExternalVaultRetrieveResponse { .. }
| types::VaultResponseData::ExternalVaultDeleteResponse { .. }
| types::VaultResponseData::ExternalVaultCreateResponse { .. } => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Vault Response"))
}
},
Err(err) => {
logger::error!("Error vaulting payment method: {:?}", err);
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to vault payment method"))
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn vault_payment_method(
state: &SessionState,
pmd: &domain::PaymentMethodVaultingData,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
existing_vault_id: Option<domain::VaultId>,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<(
pm_types::AddVaultResponse,
Option<id_type::MerchantConnectorAccountId>,
)> {
let is_external_vault_enabled = profile.is_external_vault_enabled();
match is_external_vault_enabled {
true => {
let external_vault_source: id_type::MerchantConnectorAccountId = profile
.external_vault_connector_details
.clone()
.map(|connector_details| connector_details.vault_connector_id.clone())
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("mca_id not present for external vault")?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
payments_core::helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
Some(&external_vault_source),
)
.await
.attach_printable(
"failed to fetch merchant connector account for external vault insert",
)?,
));
vault_payment_method_external(
state,
pmd,
merchant_context.get_merchant_account(),
merchant_connector_account,
)
.await
.map(|value| (value, Some(external_vault_source)))
}
false => vault_payment_method_internal(
state,
pmd,
merchant_context,
existing_vault_id,
customer_id,
)
.await
.map(|value| (value, None)),
}
}
#[cfg(feature = "v2")]
fn get_pm_list_context(
payment_method_type: enums::PaymentMethod,
payment_method: &domain::PaymentMethod,
is_payment_associated: bool,
) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
let payment_method_data = payment_method
.payment_method_data
.clone()
.map(|payment_method_data| payment_method_data.into_inner());
let payment_method_retrieval_context = match payment_method_data {
Some(payment_methods::PaymentMethodsData::Card(card)) => {
Some(PaymentMethodListContext::Card {
card_details: api::CardDetailFromLocker::from(card),
token_data: is_payment_associated.then_some(
storage::PaymentTokenData::permanent_card(
payment_method.get_id().clone(),
payment_method
.locker_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.or_else(|| Some(payment_method.get_id().get_string_repr().to_owned())),
payment_method
.locker_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.unwrap_or_else(|| {
payment_method.get_id().get_string_repr().to_owned()
}),
),
),
})
}
Some(payment_methods::PaymentMethodsData::BankDetails(bank_details)) => {
let get_bank_account_token_data =
|| -> CustomResult<payment_methods::BankAccountTokenData,errors::ApiErrorResponse> {
let connector_details = bank_details
.connector_details
.first()
.cloned()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain bank account connector details")?;
let payment_method_subtype = payment_method
.get_payment_method_subtype()
.get_required_value("payment_method_subtype")
.attach_printable("PaymentMethodType not found")?;
Ok(payment_methods::BankAccountTokenData {
payment_method_type: payment_method_subtype,
payment_method: payment_method_type,
connector_details,
})
};
// Retrieve the pm_auth connector details so that it can be tokenized
let bank_account_token_data = get_bank_account_token_data()
.inspect_err(|error| logger::error!(?error))
.ok();
bank_account_token_data.map(|data| {
let token_data = storage::PaymentTokenData::AuthBankDebit(data);
PaymentMethodListContext::Bank {
token_data: is_payment_associated.then_some(token_data),
}
})
}
Some(payment_methods::PaymentMethodsData::WalletDetails(_)) | None => {
Some(PaymentMethodListContext::TemporaryToken {
token_data: is_payment_associated.then_some(
storage::PaymentTokenData::temporary_generic(generate_id(
consts::ID_LENGTH,
"token",
)),
),
})
}
};
Ok(payment_method_retrieval_context)
}
#[cfg(feature = "v2")]
fn get_pm_list_token_data(
payment_method_type: enums::PaymentMethod,
payment_method: &domain::PaymentMethod,
) -> Result<Option<storage::PaymentTokenData>, error_stack::Report<errors::ApiErrorResponse>> {
let pm_list_context = get_pm_list_context(payment_method_type, payment_method, true)?
.get_required_value("PaymentMethodListContext")?;
match pm_list_context {
PaymentMethodListContext::Card {
card_details: _,
token_data,
} => Ok(token_data),
PaymentMethodListContext::Bank { token_data } => Ok(token_data),
PaymentMethodListContext::BankTransfer {
bank_transfer_details: _,
token_data,
} => Ok(token_data),
PaymentMethodListContext::TemporaryToken { token_data } => Ok(token_data),
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
pub async fn list_payment_methods_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<payment_methods::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
let key_manager_state = &(state).into();
let saved_payment_methods = db
.find_payment_method_by_global_customer_id_merchant_id_status(
key_manager_state,
merchant_context.get_merchant_key_store(),
customer_id,
merchant_context.get_merchant_account().get_id(),
common_enums::PaymentMethodStatus::Active,
None,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let customer_payment_methods = saved_payment_methods
.into_iter()
.map(ForeignTryFrom::foreign_try_from)
.collect::<Result<Vec<payment_methods::PaymentMethodResponseItem>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = payment_methods::CustomerPaymentMethodsListResponse {
customer_payment_methods,
};
Ok(response)
}
#[cfg(all(feature = "v2", feature = "oltp"))]
pub async fn list_customer_payment_methods_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<Vec<payment_methods::CustomerPaymentMethodResponseItem>> {
let db = &*state.store;
let key_manager_state = &(state).into();
let saved_payment_methods = db
.find_payment_method_by_global_customer_id_merchant_id_status(
key_manager_state,
merchant_context.get_merchant_key_store(),
customer_id,
merchant_context.get_merchant_account().get_id(),
common_enums::PaymentMethodStatus::Active,
None,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let mut customer_payment_methods = Vec::new();
let payment_method_results: Result<Vec<_>, error_stack::Report<errors::ApiErrorResponse>> =
saved_payment_methods
.into_iter()
.map(|pm| async move {
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
// For payment methods that are active we should always have the payment method type
let payment_method_type = pm
.payment_method_type
.get_required_value("payment_method_type")?;
let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;
let token_data = get_pm_list_token_data(payment_method_type, &pm)?;
if let Some(token_data) = token_data {
pm_routes::ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
payment_method_type,
))
.insert(intent_fulfillment_time, token_data, state)
.await?;
let final_pm = api::CustomerPaymentMethodResponseItem::foreign_try_from((
pm,
parent_payment_method_token,
))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert payment method to response format")?;
Ok(Some(final_pm))
} else {
Ok(None)
}
})
.collect::<futures::stream::FuturesUnordered<_>>()
.try_collect::<Vec<_>>()
.await;
customer_payment_methods.extend(payment_method_results?.into_iter().flatten());
Ok(customer_payment_methods)
}
#[cfg(all(feature = "v2", feature = "olap"))]
pub async fn get_total_payment_method_count_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
) -> RouterResult<api::TotalPaymentMethodCountResponse> {
let db = &*state.store;
let total_count = db
.get_payment_method_count_by_merchant_id_status(
merchant_context.get_merchant_account().get_id(),
common_enums::PaymentMethodStatus::Active,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to get total payment method count")?;
let response = api::TotalPaymentMethodCountResponse { total_count };
Ok(response)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method(
state: SessionState,
pm: api::PaymentMethodId,
merchant_context: domain::MerchantContext,
) -> RouterResponse<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm.payment_method_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method = db
.find_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
&pm_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let single_use_token_in_cache = get_single_use_token_from_store(
&state.clone(),
domain::SingleUseTokenKey::store_key(&pm_id.clone()),
)
.await
.unwrap_or_default();
transformers::generate_payment_method_response(&payment_method, &single_use_token_in_cache)
.map(services::ApplicationResponse::Json)
}
// TODO: When we separate out microservices, this function will be an endpoint in payment_methods
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn update_payment_method_status_internal(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
status: enums::PaymentMethodStatus,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResult<domain::PaymentMethod> {
let db = &*state.store;
let key_manager_state = &state.into();
let payment_method = db
.find_payment_method(
&((state).into()),
key_store,
payment_method_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(status),
};
let updated_pm = db
.update_payment_method(
key_manager_state,
key_store,
payment_method.clone(),
pm_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
Ok(updated_pm)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn update_payment_method(
state: SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
req: api::PaymentMethodUpdate,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResponse<api::PaymentMethodResponse> {
let response =
update_payment_method_core(&state, &merchant_context, &profile, req, payment_method_id)
.await?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn update_payment_method_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
request: api::PaymentMethodUpdate,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResult<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let payment_method = db
.find_payment_method(
&((state).into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let current_vault_id = payment_method.locker_id.clone();
when(
payment_method.status == enums::PaymentMethodStatus::AwaitingData,
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "This Payment method is awaiting data and hence cannot be updated"
.to_string(),
})
},
)?;
let pmd: domain::PaymentMethodVaultingData = vault::retrieve_payment_method_from_vault(
state,
merchant_context,
profile,
&payment_method,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from vault")?
.data;
let vault_request_data = request.payment_method_data.map(|payment_method_data| {
pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, payment_method_data)
});
let vaulting_response = match vault_request_data {
// cannot use async map because of problems related to lifetimes
// to overcome this, we will have to use a move closure and add some clones
Some(ref vault_request_data) => {
let (vault_response, _) = vault_payment_method(
state,
vault_request_data,
merchant_context,
profile,
// using current vault_id for now,
// will have to refactor this to generate new one on each vaulting later on
current_vault_id,
&payment_method.customer_id,
)
.await
.attach_printable("Failed to add payment method in vault")?;
Some(vault_response)
}
None => None,
};
let (vault_id, fingerprint_id) = match vaulting_response {
Some(vaulting_response) => {
let vault_id = vaulting_response.vault_id.get_string_repr().to_owned();
(Some(vault_id), vaulting_response.fingerprint_id)
}
None => (None, None),
};
let pm_update = create_pm_additional_data_update(
vault_request_data.as_ref(),
state,
merchant_context.get_merchant_key_store(),
vault_id,
fingerprint_id,
&payment_method,
request.connector_token_details,
None,
None,
None,
None,
)
.await
.attach_printable("Unable to create Payment method data")?;
let payment_method = db
.update_payment_method(
&((state).into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
let response = pm_transforms::generate_payment_method_response(&payment_method, &None)?;
// Add a PT task to handle payment_method delete from vault
Ok(response)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_payment_method(
state: SessionState,
pm_id: api::PaymentMethodId,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
) -> RouterResponse<api::PaymentMethodDeleteResponse> {
let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let response = delete_payment_method_core(&state, pm_id, &merchant_context, &profile).await?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_payment_method_core(
state: &SessionState,
pm_id: id_type::GlobalPaymentMethodId,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> RouterResult<api::PaymentMethodDeleteResponse> {
let db = state.store.as_ref();
let key_manager_state = &(state).into();
let payment_method = db
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
&pm_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
when(
payment_method.status == enums::PaymentMethodStatus::Inactive,
|| Err(errors::ApiErrorResponse::PaymentMethodNotFound),
)?;
let _customer = db
.find_customer_by_global_id(
key_manager_state,
&payment_method.customer_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Customer not found for the payment method")?;
// Soft delete
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method.clone(),
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
vault::delete_payment_method_data_from_vault(state, merchant_context, profile, &payment_method)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete payment method from vault")?;
let response = api::PaymentMethodDeleteResponse { id: pm_id };
Ok(response)
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
trait EncryptableData {
type Output;
async fn encrypt_data(
&self,
key_manager_state: &common_utils::types::keymanager::KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Self::Output>;
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl EncryptableData for payment_methods::PaymentMethodSessionRequest {
type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodSession;
async fn encrypt_data(
&self,
key_manager_state: &common_utils::types::keymanager::KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Self::Output> {
use common_utils::types::keymanager::ToEncryptable;
let encrypted_billing_address = self
.billing
.clone()
.map(|address| address.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode billing address")?
.map(Secret::new);
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payment_methods::PaymentMethodSession),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::to_encryptable(
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession {
billing: encrypted_billing_address,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment methods session details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::from_encryptable(
batch_encrypted_data,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment methods session detailss")?;
Ok(encrypted_data)
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl EncryptableData for payment_methods::PaymentMethodsSessionUpdateRequest {
type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodSession;
async fn encrypt_data(
&self,
key_manager_state: &common_utils::types::keymanager::KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Self::Output> {
use common_utils::types::keymanager::ToEncryptable;
let encrypted_billing_address = self
.billing
.clone()
.map(|address| address.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode billing address")?
.map(Secret::new);
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payment_methods::PaymentMethodSession),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::to_encryptable(
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession {
billing: encrypted_billing_address,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment methods session details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::from_encryptable(
batch_encrypted_data,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment methods session detailss")?;
Ok(encrypted_data)
}
}
#[cfg(feature = "v2")]
pub async fn payment_methods_session_create(
state: SessionState,
merchant_context: domain::MerchantContext,
request: payment_methods::PaymentMethodSessionRequest,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
db.find_customer_by_global_id(
key_manager_state,
&request.customer_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let payment_methods_session_id =
id_type::GlobalPaymentMethodSessionId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodSessionId")?;
let encrypted_data = request
.encrypt_data(key_manager_state, merchant_context.get_merchant_key_store())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt payment methods session data")?;
let billing = encrypted_data
.billing
.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")?;
// If not passed in the request, use the default value from constants
let expires_in = request
.expires_in
.unwrap_or(consts::DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY)
.into();
let expires_at = common_utils::date_time::now().saturating_add(Duration::seconds(expires_in));
let client_secret = payment_helpers::create_client_secret(
&state,
merchant_context.get_merchant_account().get_id(),
util_types::authentication::ResourceId::PaymentMethodSession(
payment_methods_session_id.clone(),
),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create client secret")?;
let payment_method_session_domain_model =
hyperswitch_domain_models::payment_methods::PaymentMethodSession {
id: payment_methods_session_id,
customer_id: request.customer_id,
billing,
psp_tokenization: request.psp_tokenization,
network_tokenization: request.network_tokenization,
tokenization_data: request.tokenization_data,
expires_at,
return_url: request.return_url,
associated_payment_methods: None,
associated_payment: None,
associated_token_id: None,
};
db.insert_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method_session_domain_model.clone(),
expires_in,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert payment methods session in db")?;
let response = transformers::generate_payment_method_session_response(
payment_method_session_domain_model,
client_secret.secret,
None,
None,
);
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn payment_methods_session_update(
state: SessionState,
merchant_context: domain::MerchantContext,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
request: payment_methods::PaymentMethodsSessionUpdateRequest,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let existing_payment_method_session_state = db
.get_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to retrieve payment methods session from db")?;
let encrypted_data = request
.encrypt_data(key_manager_state, merchant_context.get_merchant_key_store())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt payment methods session data")?;
let billing = encrypted_data
.billing
.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 payment_method_session_domain_model =
hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::GeneralUpdate{
billing: Box::new(billing),
psp_tokenization: request.psp_tokenization,
network_tokenization: request.network_tokenization,
tokenization_data: request.tokenization_data,
};
let update_state_change = db
.update_payment_method_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
payment_method_session_domain_model,
existing_payment_method_session_state.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment methods session in db")?;
let response = transformers::generate_payment_method_session_response(
update_state_change,
Secret::new("CLIENT_SECRET_REDACTED".to_string()),
None, // TODO: send associated payments response based on the expandable param
None,
);
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn payment_methods_session_retrieve(
state: SessionState,
merchant_context: domain::MerchantContext,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let payment_method_session_domain_model = db
.get_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to retrieve payment methods session from db")?;
let response = transformers::generate_payment_method_session_response(
payment_method_session_domain_model,
Secret::new("CLIENT_SECRET_REDACTED".to_string()),
None, // TODO: send associated payments response based on the expandable param
None,
);
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn payment_methods_session_update_payment_method(
state: SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
request: payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod,
) -> RouterResponse<payment_methods::PaymentMethodResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
// Validate if the session still exists
db.get_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to retrieve payment methods session from db")?;
let payment_method_update_request = request.payment_method_update_request;
let updated_payment_method = update_payment_method_core(
&state,
&merchant_context,
&profile,
payment_method_update_request,
&request.payment_method_id,
)
.await
.attach_printable("Failed to update saved payment method")?;
Ok(services::ApplicationResponse::Json(updated_payment_method))
}
#[cfg(feature = "v2")]
pub async fn payment_methods_session_delete_payment_method(
state: SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
pm_id: id_type::GlobalPaymentMethodId,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
) -> RouterResponse<api::PaymentMethodDeleteResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
// Validate if the session still exists
db.get_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to retrieve payment methods session from db")?;
let response = delete_payment_method_core(&state, pm_id, &merchant_context, &profile)
.await
.attach_printable("Failed to delete saved payment method")?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
fn construct_zero_auth_payments_request(
confirm_request: &payment_methods::PaymentMethodSessionConfirmRequest,
payment_method_session: &hyperswitch_domain_models::payment_methods::PaymentMethodSession,
payment_method: &payment_methods::PaymentMethodResponse,
) -> RouterResult<api_models::payments::PaymentsRequest> {
use api_models::payments;
Ok(payments::PaymentsRequest {
amount_details: payments::AmountDetails::new_for_zero_auth_payment(
common_enums::Currency::USD,
),
payment_method_data: confirm_request.payment_method_data.clone(),
payment_method_type: confirm_request.payment_method_type,
payment_method_subtype: confirm_request.payment_method_subtype,
customer_id: Some(payment_method_session.customer_id.clone()),
customer_present: Some(enums::PresenceOfCustomerDuringPayment::Present),
setup_future_usage: Some(common_enums::FutureUsage::OffSession),
payment_method_id: Some(payment_method.id.clone()),
merchant_reference_id: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
// We have already passed payment method billing address
billing: None,
shipping: None,
description: None,
return_url: payment_method_session.return_url.clone(),
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
payment_link_enabled: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
customer_acceptance: None,
browser_info: None,
force_3ds_challenge: None,
is_iframe_redirection_enabled: None,
merchant_connector_details: None,
return_raw_connector_response: None,
enable_partial_authorization: None,
webhook_url: None,
})
}
#[cfg(feature = "v2")]
async fn create_zero_auth_payment(
state: SessionState,
req_state: routes::app::ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
request: api_models::payments::PaymentsRequest,
) -> RouterResult<api_models::payments::PaymentsResponse> {
let response = Box::pin(payments_core::payments_create_and_confirm_intent(
state,
req_state,
merchant_context,
profile,
request,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await?;
logger::info!(associated_payments_response=?response);
response
.get_json_body()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response from payments core")
}
#[cfg(feature = "v2")]
pub async fn payment_methods_session_confirm(
state: SessionState,
req_state: routes::app::ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
request: payment_methods::PaymentMethodSessionConfirmRequest,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db: &dyn StorageInterface = state.store.as_ref();
let key_manager_state = &(&state).into();
// Validate if the session still exists
let payment_method_session = db
.get_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to retrieve payment methods session from db")?;
let payment_method_session_billing = payment_method_session
.billing
.clone()
.map(|billing| billing.into_inner())
.map(From::from);
// Unify the billing address that we receive from the session and from the confirm request
let unified_billing_address = request
.payment_method_data
.billing
.clone()
.map(|payment_method_billing| {
payment_method_billing.unify_address(payment_method_session_billing.as_ref())
})
.or_else(|| payment_method_session_billing.clone());
let customer_id = payment_method_session.customer_id.clone();
let create_payment_method_request = get_payment_method_create_request(
request
.payment_method_data
.payment_method_data
.as_ref()
.get_required_value("payment_method_data")?,
request.payment_method_type,
request.payment_method_subtype,
customer_id.clone(),
unified_billing_address.as_ref(),
Some(&payment_method_session),
)
.attach_printable("Failed to create payment method request")?;
let (payment_method_response, payment_method) = Box::pin(create_payment_method_core(
&state,
&req_state,
create_payment_method_request.clone(),
&merchant_context,
&profile,
))
.await?;
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
let token_data = get_pm_list_token_data(request.payment_method_type, &payment_method)?;
let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;
// insert the token data into redis
if let Some(token_data) = token_data {
pm_routes::ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
request.payment_method_type,
))
.insert(intent_fulfillment_time, token_data, &state)
.await?;
};
let update_payment_method_session = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods {
associated_payment_methods: Some(vec![parent_payment_method_token.clone()])
};
vault::insert_cvc_using_payment_token(
&state,
&parent_payment_method_token,
create_payment_method_request.payment_method_data.clone(),
request.payment_method_type,
intent_fulfillment_time,
merchant_context.get_merchant_key_store().key.get_inner(),
)
.await?;
let payment_method_session = db
.update_payment_method_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
update_payment_method_session,
payment_method_session,
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to update payment methods session from db")?;
let payments_response = match &payment_method_session.psp_tokenization {
Some(common_types::payment_methods::PspTokenization {
tokenization_type: common_enums::TokenizationType::MultiUse,
..
}) => {
let zero_auth_request = construct_zero_auth_payments_request(
&request,
&payment_method_session,
&payment_method_response,
)?;
let payments_response = Box::pin(create_zero_auth_payment(
state.clone(),
req_state,
merchant_context.clone(),
profile.clone(),
zero_auth_request,
))
.await?;
Some(payments_response)
}
Some(common_types::payment_methods::PspTokenization {
tokenization_type: common_enums::TokenizationType::SingleUse,
..
}) => {
Box::pin(create_single_use_tokenization_flow(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
&create_payment_method_request.clone(),
&payment_method_response,
&payment_method_session,
))
.await?;
None
}
None => None,
};
let tokenization_response = match payment_method_session.tokenization_data.clone() {
Some(tokenization_data) => {
let tokenization_response = tokenization_core::create_vault_token_core(
state.clone(),
&merchant_context.get_merchant_account().clone(),
&merchant_context.get_merchant_key_store().clone(),
api_models::tokenization::GenericTokenizationRequest {
customer_id: customer_id.clone(),
token_request: tokenization_data,
},
)
.await?;
let token = match tokenization_response {
services::ApplicationResponse::Json(response) => Some(response),
_ => None,
};
Some(token)
}
None => None,
};
logger::debug!(?tokenization_response, "Tokenization response");
//TODO: update the payment method session with the payment id and payment method id
let payment_method_session_response = transformers::generate_payment_method_session_response(
payment_method_session,
Secret::new("CLIENT_SECRET_REDACTED".to_string()),
payments_response,
(tokenization_response.flatten()),
);
Ok(services::ApplicationResponse::Json(
payment_method_session_response,
))
}
#[cfg(feature = "v2")]
impl pm_types::SavedPMLPaymentsInfo {
pub async fn form_payments_info(
payment_intent: PaymentIntent,
merchant_context: &domain::MerchantContext,
profile: domain::Profile,
db: &dyn StorageInterface,
key_manager_state: &util_types::keymanager::KeyManagerState,
) -> RouterResult<Self> {
let collect_cvv_during_payment = profile.should_collect_cvv_during_payment;
let off_session_payment_flag = matches!(
payment_intent.setup_future_usage,
common_enums::FutureUsage::OffSession
);
let is_connector_agnostic_mit_enabled =
profile.is_connector_agnostic_mit_enabled.unwrap_or(false);
Ok(Self {
payment_intent,
profile,
collect_cvv_during_payment,
off_session_payment_flag,
is_connector_agnostic_mit_enabled,
})
}
pub async fn perform_payment_ops(
&self,
state: &SessionState,
parent_payment_method_token: Option<String>,
pma: &api::CustomerPaymentMethodResponseItem,
pm_list_context: PaymentMethodListContext,
) -> RouterResult<()> {
let token = parent_payment_method_token
.as_ref()
.get_required_value("parent_payment_method_token")?;
let token_data = pm_list_context
.get_token_data()
.get_required_value("PaymentTokenData")?;
let intent_fulfillment_time = self
.profile
.get_order_fulfillment_time()
.unwrap_or(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME);
pm_routes::ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method_type))
.insert(intent_fulfillment_time, token_data, state)
.await?;
Ok(())
}
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn create_single_use_tokenization_flow(
state: SessionState,
req_state: routes::app::ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
payment_method_create_request: &payment_methods::PaymentMethodCreate,
payment_method: &api::PaymentMethodResponse,
payment_method_session: &domain::payment_methods::PaymentMethodSession,
) -> RouterResult<()> {
let customer_id = payment_method_create_request.customer_id.to_owned();
let connector_id = payment_method_create_request
.get_tokenize_connector_id()
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "psp_tokenization.connector_id",
})
.attach_printable("Failed to get tokenize connector id")?;
let db = &state.store;
let merchant_connector_account_details = db
.find_merchant_connector_account_by_id(
&(&state).into(),
&connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: connector_id.get_string_repr().to_owned(),
})
.attach_printable("error while fetching merchant_connector_account from connector_id")?;
let auth_type = merchant_connector_account_details
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let payment_method_data_request = types::PaymentMethodTokenizationData {
payment_method_data: domain::PaymentMethodData::try_from(
payment_method_create_request.payment_method_data.clone(),
)
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "card_cvc",
})
.attach_printable(
"Failed to convert type from Payment Method Create Data to Payment Method Data",
)?,
browser_info: None,
currency: api_models::enums::Currency::default(),
amount: None,
split_payments: None,
mandate_id: None,
setup_future_usage: None,
customer_acceptance: None,
setup_mandate_details: None,
};
let payment_method_session_address = types::PaymentAddress::new(
None,
payment_method_session
.billing
.clone()
.map(|address| address.into_inner()),
None,
None,
);
let mut router_data =
types::RouterData::<api::PaymentMethodToken, _, types::PaymentsResponseData> {
flow: std::marker::PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id: None,
connector_customer: None,
connector: merchant_connector_account_details
.connector_name
.to_string(),
payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_string(), //Static
attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(), //Static
tenant_id: state.tenant.tenant_id.clone(),
status: common_enums::enums::AttemptStatus::default(),
payment_method: common_enums::enums::PaymentMethod::Card,
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address: payment_method_session_address,
auth_type: common_enums::enums::AuthenticationType::default(),
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
request: payment_method_data_request.clone(),
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
connector_request_reference_id: payment_method_session.id.get_string_repr().to_string(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
connector_response: None,
payment_method_status: None,
minor_amount_captured: 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,
};
let payment_method_token_response = Box::pin(tokenization::add_token_for_payment_method(
&mut router_data,
payment_method_data_request.clone(),
state.clone(),
&merchant_connector_account_details.clone(),
))
.await?;
let token_response = payment_method_token_response.token.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: (merchant_connector_account_details.clone())
.connector_name
.to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
let value = domain::SingleUsePaymentMethodToken::get_single_use_token_from_payment_method_token(
token_response.clone().into(),
connector_id.clone(),
);
let key = domain::SingleUseTokenKey::store_key(&payment_method.id);
add_single_use_token_to_store(&state, key, value)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to store single use token")?;
Ok(())
}
#[cfg(feature = "v2")]
async fn add_single_use_token_to_store(
state: &SessionState,
key: domain::SingleUseTokenKey,
value: domain::SingleUsePaymentMethodToken,
) -> CustomResult<(), errors::StorageError> {
let redis_connection = state
.store
.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?;
redis_connection
.serialize_and_set_key_with_expiry(
&domain::SingleUseTokenKey::get_store_key(&key).into(),
value,
consts::DEFAULT_PAYMENT_METHOD_STORE_TTL,
)
.await
.change_context(errors::StorageError::KVError)
.attach_printable("Failed to insert payment method token to redis")?;
Ok(())
}
#[cfg(feature = "v2")]
async fn get_single_use_token_from_store(
state: &SessionState,
key: domain::SingleUseTokenKey,
) -> CustomResult<Option<domain::SingleUsePaymentMethodToken>, errors::StorageError> {
let redis_connection = state
.store
.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?;
redis_connection
.get_and_deserialize_key::<Option<domain::SingleUsePaymentMethodToken>>(
&domain::SingleUseTokenKey::get_store_key(&key).into(),
"SingleUsePaymentMethodToken",
)
.await
.change_context(errors::StorageError::KVError)
.attach_printable("Failed to get payment method token from redis")
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn fetch_payment_method(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResult<domain::PaymentMethod> {
let db = &state.store;
let key_manager_state = &state.into();
let merchant_account = merchant_context.get_merchant_account();
let key_store = merchant_context.get_merchant_key_store();
db.find_payment_method(
key_manager_state,
key_store,
payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Payment method not found for network token status check")
}
#[cfg(feature = "v2")]
pub async fn check_network_token_status(
state: SessionState,
merchant_context: domain::MerchantContext,
payment_method_id: id_type::GlobalPaymentMethodId,
) -> RouterResponse<payment_methods::NetworkTokenStatusCheckResponse> {
// Retrieve the payment method from the database
let payment_method =
fetch_payment_method(&state, &merchant_context, &payment_method_id).await?;
// Call the network token status check function
let network_token_status_check_response = if payment_method.status
== common_enums::PaymentMethodStatus::Active
{
// Check if the payment method has network token data
when(
payment_method
.network_token_requestor_reference_id
.is_none(),
|| {
Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_method_id",
})
},
)?;
match network_tokenization::do_status_check_for_network_token(&state, &payment_method).await
{
Ok(network_token_details) => {
let status = match network_token_details.token_status {
pm_types::TokenStatus::Active => api_enums::TokenStatus::Active,
pm_types::TokenStatus::Suspended => api_enums::TokenStatus::Suspended,
pm_types::TokenStatus::Deactivated => api_enums::TokenStatus::Deactivated,
};
payment_methods::NetworkTokenStatusCheckResponse::SuccessResponse(
payment_methods::NetworkTokenStatusCheckSuccessResponse {
status,
token_expiry_month: network_token_details.token_expiry_month,
token_expiry_year: network_token_details.token_expiry_year,
card_last_four: network_token_details.card_last_4,
card_expiry: network_token_details.card_expiry,
token_last_four: network_token_details.token_last_4,
payment_method_id,
customer_id: payment_method.customer_id,
},
)
}
Err(e) => {
let err_message = e.current_context().to_string();
logger::debug!("Network token status check failed: {:?}", e);
payment_methods::NetworkTokenStatusCheckResponse::FailureResponse(
payment_methods::NetworkTokenStatusCheckFailureResponse {
error_message: err_message,
},
)
}
}
} else {
let err_message = "Payment Method is not active".to_string();
logger::debug!("Payment Method is not active");
payment_methods::NetworkTokenStatusCheckResponse::FailureResponse(
payment_methods::NetworkTokenStatusCheckFailureResponse {
error_message: err_message,
},
)
};
Ok(services::ApplicationResponse::Json(
network_token_status_check_response,
))
}
| crates/router/src/core/payment_methods.rs | router::src::core::payment_methods | 30,081 | true |
// File: crates/router/src/core/proxy.rs
// Module: router::src::core::proxy
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,
merchant_context: domain::MerchantContext,
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,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let vault_data = proxy_record
.get_vault_data(&state, merchant_context)
.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,
})
}
}
| crates/router/src/core/proxy.rs | router::src::core::proxy | 1,069 | true |
// File: crates/router/src/core/refunds.rs
// Module: router::src::core::refunds
#[cfg(feature = "olap")]
use std::collections::HashMap;
#[cfg(feature = "olap")]
use api_models::admin::MerchantConnectorInfo;
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};
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, helpers},
refunds::transformers::SplitRefundInput,
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,
merchant_context: domain::MerchantContext,
_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 = merchant_context.get_merchant_account().get_id();
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
&req.payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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,
merchant_context.get_merchant_account().storage_scheme,
)
.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, merchant_id, mcd).await
})
.await
.transpose()?;
Box::pin(validate_and_create_refund(
&state,
&merchant_context,
&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,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<diesel_refund::Refund> {
let routed_through = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve connector from payment attempt")?;
let storage_scheme = merchant_context.get_merchant_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)?;
let mut router_data = core_utils::construct_refund_router_data(
state,
&routed_through,
merchant_context,
(payment_attempt.get_total_amount(), currency),
payment_intent,
payment_attempt,
refund,
creds_identifier.clone(),
split_refunds,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
creds_identifier.as_deref(),
))
.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 router_data_res = if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
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,
None,
)
.await;
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::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
if let Some(refund_error_update) = option_refund_error_update {
state
.store
.update_refund(
refund.to_owned(),
refund_error_update,
merchant_context.get_merchant_account().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()?;
// Initiating 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;
refund_router_data_res
} else {
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.to_string(),
)
.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::AUTHORIZE_FLOW_STR.to_string(),
)
.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",
merchant_context.get_merchant_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,
merchant_context.get_merchant_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,
merchant_context,
&response,
payment_attempt.profile_id.clone(),
)
.await
.map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))
.ok();
Ok(response)
}
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,
merchant_context: domain::MerchantContext,
profile_id: Option<common_utils::id_type::ProfileId>,
request: Req,
f: F,
) -> RouterResponse<refunds::RefundResponse>
where
F: Fn(
SessionState,
domain::MerchantContext,
Option<common_utils::id_type::ProfileId>,
Req,
) -> Fut,
Fut: futures::Future<Output = RouterResult<T>>,
T: ForeignInto<refunds::RefundResponse>,
{
Ok(services::ApplicationResponse::Json(
f(state, merchant_context, profile_id, request)
.await?
.foreign_into(),
))
}
#[instrument(skip_all)]
pub async fn refund_retrieve_core(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: Option<common_utils::id_type::ProfileId>,
request: refunds::RefundsRetrieveRequest,
refund: diesel_refund::Refund,
) -> RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_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(
&(&state).into(),
payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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,
merchant_context.get_merchant_account().storage_scheme,
)
.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, merchant_id, 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 = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) {
Box::pin(sync_refund_with_gateway(
&state,
&merchant_context,
&payment_attempt,
&payment_intent,
&refund,
creds_identifier,
split_refunds_req,
))
.await
} else {
Ok(refund)
}?;
Ok(response)
}
fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: 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 = 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,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &diesel_refund::Refund,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<diesel_refund::Refund> {
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 = merchant_context.get_merchant_account().storage_scheme;
let currency = payment_attempt.currency.get_required_value("currency")?;
let mut router_data = core_utils::construct_refund_router_data::<api::RSync>(
state,
&connector_id,
merchant_context,
(payment_attempt.get_total_amount(), currency),
payment_intent,
payment_attempt,
refund,
creds_identifier.clone(),
split_refunds,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
creds_identifier.as_deref(),
))
.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 router_data_res = if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
api::RSync,
types::RefundsData,
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
let mut refund_sync_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_refund_failed_response()?;
// Initiating connector integrity checks
let integrity_result = check_refund_integrity(
&refund_sync_router_data.request,
&refund_sync_router_data.response,
);
refund_sync_router_data.integrity_check = integrity_result;
refund_sync_router_data
} else {
router_data
};
let refund_update = match router_data_res.response {
Err(error_message) => {
let refund_status = match error_message.status_code {
// marking failure for 2xx because this is genuine refund failure
200..=299 => Some(enums::RefundStatus::Failure),
_ => None,
};
diesel_refund::RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message: error_message.reason.or(Some(error_message.message)),
refund_error_code: Some(error_message.code),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: error_message.network_decline_code,
issuer_error_message: error_message.network_error_message,
}
}
Ok(response) => match router_data_res.integrity_check.clone() {
Err(err) => {
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
(
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
),
),
);
let (refund_connector_transaction_id, processor_refund_data) = err
.connector_transaction_id
.map_or((None, None), |refund_id| {
let (refund_id, refund_data) =
ConnectorTransactionId::form_id_and_data(refund_id);
(Some(refund_id), refund_data)
});
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(()) => {
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,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)
.attach_printable_lazy(|| {
format!(
"Unable to update refund with refund_id: {}",
refund.refund_id
)
})?;
utils::trigger_refund_outgoing_webhook(
state,
merchant_context,
&response,
payment_attempt.profile_id.clone(),
)
.await
.map_err(|error| logger::warn!(refunds_outgoing_webhook_error=?error))
.ok();
Ok(response)
}
// ********************************************** REFUND UPDATE **********************************************
pub async fn refund_update_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: refunds::RefundUpdateRequest,
) -> RouterResponse<refunds::RefundResponse> {
let db = state.store.as_ref();
let refund = db
.find_refund_by_merchant_id_refund_id(
merchant_context.get_merchant_account().get_id(),
&req.refund_id,
merchant_context.get_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_context
.get_merchant_account()
.storage_scheme
.to_string(),
},
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("Unable to update refund with refund_id: {}", req.refund_id)
})?;
Ok(services::ApplicationResponse::Json(response.foreign_into()))
}
// ********************************************** VALIDATIONS **********************************************
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn validate_and_create_refund(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund_amount: MinorUnit,
req: refunds::RefundRequest,
creds_identifier: Option<String>,
) -> RouterResult<refunds::RefundResponse> {
let db = &*state.store;
let split_refunds = 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: req.split_refunds.clone(),
})?;
// Only for initial dev and testing
let refund_type = req.refund_type.unwrap_or_default();
// If Refund Id not passed in request Generate one.
let refund_id = core_utils::get_or_generate_id("refund_id", &req.refund_id, "ref")?;
let predicate = req
.merchant_id
.as_ref()
.map(|merchant_id| merchant_id != merchant_context.get_merchant_account().get_id());
utils::when(predicate.unwrap_or(false), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string()
})
.attach_printable("invalid merchant_id in request"))
})?;
let connector_transaction_id = payment_attempt.clone().connector_transaction_id.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.")
})?;
let all_refunds = db
.find_refund_by_merchant_id_connector_transaction_id(
merchant_context.get_merchant_account().get_id(),
&connector_transaction_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let currency = payment_attempt.currency.get_required_value("currency")?;
//[#249]: Add Connector Based Validation here.
validator::validate_payment_order_age(&payment_intent.created_at, state.conf.refund.max_age)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "created_at".to_string(),
expected_format: format!(
"created_at not older than {} days",
state.conf.refund.max_age,
),
})?;
let total_amount_captured = payment_intent
.amount_captured
.unwrap_or(payment_attempt.get_total_amount());
validator::validate_refund_amount(
total_amount_captured.get_amount_as_i64(),
&all_refunds,
refund_amount.get_amount_as_i64(),
)
.change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
validator::validate_maximum_refund_against_payment_attempt(
&all_refunds,
state.conf.refund.max_attempts,
)
.change_context(errors::ApiErrorResponse::MaximumRefundCount)?;
let connector = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
let (connector_transaction_id, processor_transaction_data) =
ConnectorTransactionId::form_id_and_data(connector_transaction_id);
let refund_create_req = diesel_refund::RefundNew {
refund_id: refund_id.to_string(),
internal_reference_id: utils::generate_id(consts::ID_LENGTH, "refid"),
external_reference_id: Some(refund_id.clone()),
payment_id: req.payment_id,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector_transaction_id,
connector,
refund_type: req.refund_type.unwrap_or_default().foreign_into(),
total_amount: payment_attempt.get_total_amount(),
refund_amount,
currency,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
refund_status: enums::RefundStatus::Pending,
metadata: req.metadata,
description: req.reason.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
refund_reason: req.reason,
profile_id: payment_intent.profile_id.clone(),
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
split_refunds: req.split_refunds,
connector_refund_id: None,
sent_to_gateway: Default::default(),
refund_arn: None,
updated_by: Default::default(),
organization_id: merchant_context
.get_merchant_account()
.organization_id
.clone(),
processor_transaction_data,
processor_refund_data: None,
};
let refund = match db
.insert_refund(
refund_create_req,
merchant_context.get_merchant_account().storage_scheme,
)
.await
{
Ok(refund) => {
Box::pin(schedule_refund_execution(
state,
refund.clone(),
refund_type,
merchant_context,
payment_attempt,
payment_intent,
creds_identifier,
split_refunds,
))
.await?
}
Err(err) => {
if err.current_context().is_db_unique_violation() {
Err(errors::ApiErrorResponse::DuplicateRefundRequest)?
} else {
return Err(err)
.change_context(errors::ApiErrorResponse::RefundNotFound)
.attach_printable("Inserting Refund failed");
}
}
};
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
};
Ok(refund.foreign_into())
}
// ********************************************** Refund list **********************************************
/// If payment-id is provided, lists all the refunds associated with that particular payment-id
/// If payment-id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default
#[instrument(skip_all)]
#[cfg(feature = "olap")]
pub async fn refund_list(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
req: api_models::refunds::RefundListRequest,
) -> RouterResponse<api_models::refunds::RefundListResponse> {
let db = state.store;
let limit = validator::validate_refund_list(req.limit)?;
let offset = req.offset.unwrap_or_default();
let refund_list = db
.filter_refund_by_constraints(
merchant_context.get_merchant_account().get_id(),
&(req.clone(), profile_id_list.clone()).try_into()?,
merchant_context.get_merchant_account().storage_scheme,
limit,
offset,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let data: Vec<refunds::RefundResponse> = refund_list
.into_iter()
.map(ForeignInto::foreign_into)
.collect();
let total_count = db
.get_total_count_of_refunds(
merchant_context.get_merchant_account().get_id(),
&(req, profile_id_list).try_into()?,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
Ok(services::ApplicationResponse::Json(
api_models::refunds::RefundListResponse {
count: data.len(),
total_count,
data,
},
))
}
#[instrument(skip_all)]
#[cfg(feature = "olap")]
pub async fn refund_filter_list(
state: SessionState,
merchant_context: domain::MerchantContext,
req: common_utils::types::TimeRange,
) -> RouterResponse<api_models::refunds::RefundListMetaData> {
let db = state.store;
let filter_list = db
.filter_refund_by_meta_constraints(
merchant_context.get_merchant_account().get_id(),
&req,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
Ok(services::ApplicationResponse::Json(filter_list))
}
#[instrument(skip_all)]
pub async fn refund_retrieve_core_with_internal_reference_id(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: Option<common_utils::id_type::ProfileId>,
refund_internal_request_id: String,
force_sync: Option<bool>,
) -> RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
let refund = db
.find_refund_by_internal_reference_id_merchant_id(
&refund_internal_request_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let request = refunds::RefundsRetrieveRequest {
refund_id: refund.refund_id.clone(),
force_sync,
merchant_connector_details: None,
};
Box::pin(refund_retrieve_core(
state.clone(),
merchant_context,
profile_id,
request,
refund,
))
.await
}
#[instrument(skip_all)]
pub async fn refund_retrieve_core_with_refund_id(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: Option<common_utils::id_type::ProfileId>,
request: refunds::RefundsRetrieveRequest,
) -> RouterResult<diesel_refund::Refund> {
let refund_id = request.refund_id.clone();
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
let refund = db
.find_refund_by_merchant_id_refund_id(
merchant_id,
refund_id.as_str(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
Box::pin(refund_retrieve_core(
state.clone(),
merchant_context,
profile_id,
request,
refund,
))
.await
}
#[instrument(skip_all)]
#[cfg(feature = "olap")]
pub async fn refund_manual_update(
state: SessionState,
req: api_models::refunds::RefundManualUpdateRequest,
) -> RouterResponse<serde_json::Value> {
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&req.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the key store by merchant_id")?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the merchant_account by merchant_id")?;
let refund = state
.store
.find_refund_by_merchant_id_refund_id(
merchant_account.get_id(),
&req.refund_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let refund_update = diesel_refund::RefundUpdate::ManualUpdate {
refund_status: req.status.map(common_enums::RefundStatus::from),
refund_error_message: req.error_message,
refund_error_code: req.error_code,
updated_by: merchant_account.storage_scheme.to_string(),
};
state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.refund_id
)
})?;
Ok(services::ApplicationResponse::StatusOk)
}
#[instrument(skip_all)]
#[cfg(feature = "olap")]
pub async fn get_filters_for_refunds(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
) -> RouterResponse<api_models::refunds::RefundListFilters> {
let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
super::admin::list_payment_connectors(
state,
merchant_context.get_merchant_account().get_id().to_owned(),
profile_id_list,
)
.await?
{
data
} else {
return Err(errors::ApiErrorResponse::InternalServerError.into());
};
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::refunds::RefundListFilters {
connector: connector_map,
currency: enums::Currency::iter().collect(),
refund_status: enums::RefundStatus::iter().collect(),
},
))
}
#[instrument(skip_all)]
#[cfg(feature = "olap")]
pub async fn get_aggregates_for_refunds(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: common_utils::types::TimeRange,
) -> RouterResponse<api_models::refunds::RefundAggregateResponse> {
let db = state.store.as_ref();
let refund_status_with_count = db
.get_refund_status_with_count(
merchant_context.get_merchant_account().get_id(),
profile_id_list,
&time_range,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find status count")?;
let mut status_map: HashMap<enums::RefundStatus, i64> =
refund_status_with_count.into_iter().collect();
for status in enums::RefundStatus::iter() {
status_map.entry(status).or_default();
}
Ok(services::ApplicationResponse::Json(
api_models::refunds::RefundAggregateResponse {
status_with_count: status_map,
},
))
}
impl ForeignFrom<diesel_refund::Refund> for api::RefundResponse {
fn foreign_from(refund: diesel_refund::Refund) -> Self {
let refund = refund;
Self {
payment_id: refund.payment_id,
refund_id: refund.refund_id,
amount: refund.refund_amount,
currency: refund.currency.to_string(),
reason: refund.refund_reason,
status: refund.refund_status.foreign_into(),
profile_id: refund.profile_id,
metadata: refund.metadata,
error_message: refund.refund_error_message,
error_code: refund.refund_error_code,
created_at: Some(refund.created_at),
updated_at: Some(refund.modified_at),
connector: refund.connector,
merchant_connector_id: refund.merchant_connector_id,
split_refunds: refund.split_refunds,
unified_code: refund.unified_code,
unified_message: refund.unified_message,
issuer_error_code: refund.issuer_error_code,
issuer_error_message: refund.issuer_error_message,
}
}
}
// ********************************************** PROCESS TRACKER **********************************************
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn schedule_refund_execution(
state: &SessionState,
refund: diesel_refund::Refund,
refund_type: api_models::refunds::RefundType,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
creds_identifier: Option<String>,
split_refunds: Option<SplitRefundsRequest>,
) -> RouterResult<diesel_refund::Refund> {
// refunds::RefundResponse> {
let db = &*state.store;
let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter;
let task = "EXECUTE_REFUND";
let task_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
let refund_process = db
.find_process_by_id(&task_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find the process id")?;
let result = match refund.refund_status {
enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => {
match (refund.sent_to_gateway, refund_process) {
(false, None) => {
// Execute the refund task based on refund_type
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_execute_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.refund_id))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
let update_refund = Box::pin(trigger_refund_to_gateway(
state,
&refund,
merchant_context,
payment_attempt,
payment_intent,
creds_identifier,
split_refunds,
))
.await;
match update_refund {
Ok(updated_refund_data) => {
add_refund_sync_task(db, &updated_refund_data, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!(
"Failed while pushing refund sync task in scheduler: refund_id: {}",
refund.refund_id
))?;
Ok(updated_refund_data)
}
Err(err) => Err(err),
}
}
}
}
_ => {
// Sync the refund for status check
//[#300]: return refund status response
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_sync_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.refund_id))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
// [#255]: This is not possible in schedule_refund_execution as it will always be scheduled
// sync_refund_with_gateway(data, &refund).await
Ok(refund)
}
}
}
}
}
// [#255]: This is not allowed to be otherwise or all
_ => Ok(refund),
}?;
Ok(result)
}
#[instrument(skip_all)]
pub async fn sync_refund_with_gateway_workflow(
state: &SessionState,
refund_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let key_manager_state = &state.into();
let refund_core = serde_json::from_value::<diesel_refund::RefundCoreWorkflow>(
refund_tracker.tracking_data.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"unable to convert into refund_core {:?}",
refund_tracker.tracking_data
)
})?;
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&refund_core.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
&refund_core.merchant_id,
&key_store,
)
.await?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
let response = Box::pin(refund_retrieve_core_with_internal_reference_id(
state.clone(),
merchant_context,
None,
refund_core.refund_internal_reference_id,
Some(true),
))
.await?;
let terminal_status = [
enums::RefundStatus::Success,
enums::RefundStatus::Failure,
enums::RefundStatus::TransactionFailure,
];
match response.refund_status {
status if terminal_status.contains(&status) => {
state
.store
.as_scheduler()
.finish_process_with_business_status(
refund_tracker.clone(),
business_status::COMPLETED_BY_PT,
)
.await?
}
_ => {
_ = retry_refund_sync_task(
&*state.store,
response.connector,
response.merchant_id,
refund_tracker.to_owned(),
)
.await?;
}
}
Ok(())
}
/// Schedule the task for refund retry
///
/// Returns bool which indicates whether this was the last refund retry or not
pub async fn retry_refund_sync_task(
db: &dyn db::StorageInterface,
connector: String,
merchant_id: common_utils::id_type::MerchantId,
pt: storage::ProcessTracker,
) -> Result<bool, sch_errors::ProcessTrackerError> {
let schedule_time =
get_refund_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1)
.await?;
match schedule_time {
Some(s_time) => {
db.as_scheduler().retry_process(pt, s_time).await?;
Ok(false)
}
None => {
db.as_scheduler()
.finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
.await?;
Ok(true)
}
}
}
#[instrument(skip_all)]
pub async fn start_refund_workflow(
state: &SessionState,
refund_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
match refund_tracker.name.as_deref() {
Some("EXECUTE_REFUND") => {
Box::pin(trigger_refund_execute_workflow(state, refund_tracker)).await
}
Some("SYNC_REFUND") => {
Box::pin(sync_refund_with_gateway_workflow(state, refund_tracker)).await
}
_ => Err(errors::ProcessTrackerError::JobNotFound),
}
}
#[instrument(skip_all)]
pub async fn trigger_refund_execute_workflow(
state: &SessionState,
refund_tracker: &storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
let refund_core = serde_json::from_value::<diesel_refund::RefundCoreWorkflow>(
refund_tracker.tracking_data.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"unable to convert into refund_core {:?}",
refund_tracker.tracking_data
)
})?;
let key_manager_state = &state.into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&refund_core.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&refund_core.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
let refund = db
.find_refund_by_internal_reference_id_merchant_id(
&refund_core.refund_internal_reference_id,
&refund_core.merchant_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
match (&refund.sent_to_gateway, &refund.refund_status) {
(false, enums::RefundStatus::Pending) => {
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&refund.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&refund.connector_transaction_id,
&refund_core.payment_id,
&refund.merchant_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(state.into()),
&payment_attempt.payment_id,
&refund.merchant_id,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let split_refunds = 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(),
})?;
//trigger refund request to gateway
let updated_refund = Box::pin(trigger_refund_to_gateway(
state,
&refund,
&merchant_context,
&payment_attempt,
&payment_intent,
None,
split_refunds,
))
.await?;
add_refund_sync_task(
db,
&updated_refund,
storage::ProcessTrackerRunner::RefundWorkflowRouter,
)
.await?;
}
(true, enums::RefundStatus::Pending) => {
// create sync task
add_refund_sync_task(
db,
&refund,
storage::ProcessTrackerRunner::RefundWorkflowRouter,
)
.await?;
}
(_, _) => {
//mark task as finished
db.as_scheduler()
.finish_process_with_business_status(
refund_tracker.clone(),
business_status::COMPLETED_BY_PT,
)
.await?;
}
};
Ok(())
}
#[instrument]
pub fn refund_to_refund_core_workflow_model(
refund: &diesel_refund::Refund,
) -> diesel_refund::RefundCoreWorkflow {
diesel_refund::RefundCoreWorkflow {
refund_internal_reference_id: refund.internal_reference_id.clone(),
connector_transaction_id: refund.connector_transaction_id.clone(),
merchant_id: refund.merchant_id.clone(),
payment_id: refund.payment_id.clone(),
processor_transaction_data: refund.processor_transaction_data.clone(),
}
}
#[instrument(skip_all)]
pub async fn add_refund_sync_task(
db: &dyn db::StorageInterface,
refund: &diesel_refund::Refund,
runner: storage::ProcessTrackerRunner,
) -> RouterResult<storage::ProcessTracker> {
let task = "SYNC_REFUND";
let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
let schedule_time =
get_refund_sync_process_schedule_time(db, &refund.connector, &refund.merchant_id, 0)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch schedule time for refund sync process")?
.unwrap_or_else(common_utils::date_time::now);
let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund);
let tag = ["REFUND"];
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
refund_workflow_tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct refund sync process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)
.attach_printable_lazy(|| {
format!(
"Failed while inserting task in process_tracker: refund_id: {}",
refund.refund_id
)
})?;
metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund")));
Ok(response)
}
#[instrument(skip_all)]
pub async fn add_refund_execute_task(
db: &dyn db::StorageInterface,
refund: &diesel_refund::Refund,
runner: storage::ProcessTrackerRunner,
) -> RouterResult<storage::ProcessTracker> {
let task = "EXECUTE_REFUND";
let process_tracker_id = format!("{runner}_{task}_{}", refund.internal_reference_id);
let tag = ["REFUND"];
let schedule_time = common_utils::date_time::now();
let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
refund_workflow_tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct refund execute process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)
.attach_printable_lazy(|| {
format!(
"Failed while inserting task in process_tracker: refund_id: {}",
refund.refund_id
)
})?;
Ok(response)
}
pub async fn get_refund_sync_process_schedule_time(
db: &dyn db::StorageInterface,
connector: &str,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mapping: common_utils::errors::CustomResult<
process_data::ConnectorPTMapping,
errors::StorageError,
> = db
.find_config_by_key(&format!("pt_mapping_refund_sync_{connector}"))
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("ConnectorPTMapping")
.change_context(errors::StorageError::DeserializationFailed)
});
let mapping = match mapping {
Ok(x) => x,
Err(err) => {
logger::error!("Error: while getting connector mapping: {err:?}");
process_data::ConnectorPTMapping::default()
}
};
let time_delta = process_tracker_utils::get_schedule_time(mapping, merchant_id, retry_count);
Ok(process_tracker_utils::get_time_from_delta(time_delta))
}
| crates/router/src/core/refunds.rs | router::src::core::refunds | 12,643 | true |
// File: crates/router/src/core/conditional_config.rs
// Module: router::src::core::conditional_config
#[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_manager_state,
&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,
merchant_context: domain::MerchantContext,
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 = merchant_context
.get_merchant_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 = merchant_context
.get_merchant_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,
merchant_context.get_merchant_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,
merchant_context.get_merchant_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,
_merchant_context: domain::MerchantContext,
) -> RouterResponse<()> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn delete_conditional_config(
state: SessionState,
merchant_context: domain::MerchantContext,
) -> 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 = merchant_context
.get_merchant_account()
.get_id()
.get_payment_config_routing_id();
let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_context
.get_merchant_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,
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
) -> RouterResponse<DecisionManagerResponse> {
let db = state.store.as_ref();
let algorithm_id = merchant_context
.get_merchant_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))
}
| crates/router/src/core/conditional_config.rs | router::src::core::conditional_config | 2,404 | true |
// File: crates/router/src/core/payouts.rs
// Module: router::src::core::payouts
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,
};
#[cfg(feature = "olap")]
use api_models::payments as payment_enums;
use api_models::{self, enums as api_enums, payouts::PayoutLinkResponse};
#[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 serde_json;
use time::Duration;
#[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,
merchant_context: &domain::MerchantContext,
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,
merchant_context,
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,
merchant_context,
None,
&mut routing_data,
payout_data,
eligible_routable_connectors,
)
.await
}
}
}
#[instrument(skip_all)]
pub async fn make_connector_decision(
state: &SessionState,
merchant_context: &domain::MerchantContext,
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,
merchant_context,
&routing_data.connector_data,
payout_data,
))
.await?;
#[cfg(feature = "payout_retry")]
{
let config_bool = retry::config_should_call_gsm_payout(
&*state.store,
merchant_context.get_merchant_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,
merchant_context,
))
.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,
merchant_context,
&connector_data,
payout_data,
))
.await?;
#[cfg(feature = "payout_retry")]
{
let config_multiple_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
merchant_context.get_merchant_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,
merchant_context,
))
.await?;
}
let config_single_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
merchant_context.get_merchant_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,
merchant_context,
))
.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,
merchant_context: &domain::MerchantContext,
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,
merchant_context,
payout_attempt.connector.clone(),
routing_algorithm,
payout_data,
eligible_connectors,
)
.await?;
// Call connector steps
Box::pin(make_connector_decision(
state,
merchant_context,
connector_call_type,
payout_data,
))
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn payouts_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
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,
merchant_context: domain::MerchantContext,
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, &merchant_context, &req).await?;
// Create DB entries
let mut payout_data = payout_create_db_entries(
&state,
&merchant_context,
&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,
merchant_context.get_merchant_key_store(),
Some(&mut payout_data),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
}
if let Some(true) = payout_data.payouts.confirm {
payouts_core(
&state,
&merchant_context,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
)
.await?
};
trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await
}
#[instrument(skip_all)]
pub async fn payouts_confirm_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: payouts::PayoutCreateRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
&state,
&merchant_context,
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, &merchant_context, &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,
&merchant_context,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
)
.await?;
trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await
}
pub async fn payouts_update_core(
state: SessionState,
merchant_context: domain::MerchantContext,
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,
&merchant_context,
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, &merchant_context, &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,
merchant_context.get_merchant_key_store(),
Some(&mut payout_data),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
}
if let Some(true) = payout_data.payouts.confirm {
payouts_core(
&state,
&merchant_context,
&mut payout_data,
req.routing.clone(),
req.connector.clone(),
)
.await?;
}
trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await
}
#[cfg(all(feature = "payouts", feature = "v1"))]
#[instrument(skip_all)]
pub async fn payouts_retrieve_core(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: Option<id_type::ProfileId>,
req: payouts::PayoutRetrieveRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
&state,
&merchant_context,
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,
&merchant_context,
payout_attempt.connector.clone(),
None,
&mut payout_data,
None,
)
.await?;
Box::pin(complete_payout_retrieve(
&state,
&merchant_context,
connector_call_type,
&mut payout_data,
))
.await?;
}
Ok(services::ApplicationResponse::Json(
response_handler(&state, &merchant_context, &payout_data).await?,
))
}
#[instrument(skip_all)]
pub async fn payouts_cancel_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: payouts::PayoutActionRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
&state,
&merchant_context,
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,
merchant_context.get_merchant_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,
merchant_context.get_merchant_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,
&merchant_context,
&connector_data,
&mut payout_data,
))
.await
.attach_printable("Payout cancellation failed for given Payout request")?;
}
Ok(services::ApplicationResponse::Json(
response_handler(&state, &merchant_context, &payout_data).await?,
))
}
#[instrument(skip_all)]
pub async fn payouts_fulfill_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: payouts::PayoutActionRequest,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let mut payout_data = Box::pin(make_payout_data(
&state,
&merchant_context,
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, &merchant_context)
.await?;
Box::pin(fulfill_payout(
&state,
&merchant_context,
&connector_data,
&mut payout_data,
))
.await
.attach_printable("Payout fulfillment failed for given Payout request")?;
trigger_webhook_and_handle_response(&state, &merchant_context, &payout_data).await
}
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn payouts_list_core(
_state: SessionState,
_merchant_context: domain::MerchantContext,
_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,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: payouts::PayoutListConstraints,
) -> RouterResponse<payouts::PayoutListResponse> {
validator::validate_payout_list_request(&constraints)?;
let merchant_id = merchant_context.get_merchant_account().get_id();
let db = state.store.as_ref();
let payouts = helpers::filter_by_constraints(
db,
&constraints,
merchant_id,
merchant_context.get_merchant_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(
&(&state).into(),
&customer_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(),
merchant_context.get_merchant_key_store(),
&payout_id_as_payment_id_type,
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_account().get_id(),
&constraints,
merchant_context.get_merchant_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,
&(merchant_context.get_merchant_key_store().clone()).key,
merchant_context
.get_merchant_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,
&(merchant_context.get_merchant_key_store().clone()).key,
merchant_context
.get_merchant_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(
merchant_context.get_merchant_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(
merchant_context.get_merchant_account().get_id(),
&active_payout_ids,
filters.connector.clone(),
filters.currency.clone(),
filters.status.clone(),
filters.payout_method.clone(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed to fetch total count of filtered payouts for the given constraints - {filters:?}",
)
})?;
Ok(services::ApplicationResponse::Json(
api::PayoutListResponse {
size: data.len(),
data,
total_count: Some(total_count),
},
))
}
#[cfg(feature = "olap")]
pub async fn payouts_list_available_filters_core(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<id_type::ProfileId>>,
time_range: common_utils::types::TimeRange,
) -> RouterResponse<api::PayoutListFilters> {
let db = state.store.as_ref();
let payouts = db
.filter_payouts_by_time_range_constraints(
merchant_context.get_merchant_account().get_id(),
&time_range,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts);
let filters = db
.get_filters_for_payouts(
payouts.as_slice(),
merchant_context.get_merchant_account().get_id(),
storage_enums::MerchantStorageScheme::PostgresOnly,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
Ok(services::ApplicationResponse::Json(
api::PayoutListFilters {
connector: filters.connector,
currency: filters.currency,
status: filters.status,
payout_method: filters.payout_method,
},
))
}
// ********************************************** HELPERS **********************************************
pub async fn call_connector_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt.to_owned();
let payouts = &payout_data.payouts.to_owned();
// fetch merchant connector account if not present
if payout_data.merchant_connector_account.is_none()
|| payout_data.payout_attempt.merchant_connector_id.is_none()
{
let merchant_connector_account = get_mca_from_profile_id(
state,
merchant_context,
&payout_data.profile_id,
&connector_data.connector_name.to_string(),
payout_attempt
.merchant_connector_id
.clone()
.or(connector_data.merchant_connector_id.clone())
.as_ref(),
)
.await?;
payout_data.payout_attempt.merchant_connector_id = merchant_connector_account.get_mca_id();
payout_data.merchant_connector_account = Some(merchant_connector_account);
}
// update connector_name
if payout_data.payout_attempt.connector.is_none()
|| payout_data.payout_attempt.connector != Some(connector_data.connector_name.to_string())
{
payout_data.payout_attempt.connector = Some(connector_data.connector_name.to_string());
let updated_payout_attempt = storage::PayoutAttemptUpdate::UpdateRouting {
connector: connector_data.connector_name.to_string(),
routing_info: payout_data.payout_attempt.routing_info.clone(),
merchant_connector_id: payout_data.payout_attempt.merchant_connector_id.clone(),
};
let db = &*state.store;
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating routing info in payout_attempt")?;
};
// Fetch / store payout_method_data
if payout_data.payout_method_data.is_none() || payout_attempt.payout_token.is_none() {
helpers::fetch_payout_method_data(state, payout_data, connector_data, merchant_context)
.await?;
}
// Eligibility flow
Box::pin(complete_payout_eligibility(
state,
merchant_context,
connector_data,
payout_data,
))
.await?;
// Create customer flow
Box::pin(complete_create_recipient(
state,
merchant_context,
connector_data,
payout_data,
))
.await?;
// Create customer's disbursement account flow
Box::pin(complete_create_recipient_disburse_account(
state,
merchant_context,
connector_data,
payout_data,
))
.await?;
// Payout creation flow
Box::pin(complete_create_payout(
state,
merchant_context,
connector_data,
payout_data,
))
.await?;
// Auto fulfillment flow
let status = payout_data.payout_attempt.status;
if payouts.auto_fulfill && status == storage_enums::PayoutStatus::RequiresFulfillment {
Box::pin(fulfill_payout(
state,
merchant_context,
connector_data,
payout_data,
))
.await
.attach_printable("Payout fulfillment failed for given Payout request")?;
}
Ok(())
}
pub async fn complete_create_recipient(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
if !payout_data.should_terminate
&& matches!(
payout_data.payout_attempt.status,
common_enums::PayoutStatus::RequiresCreation
| common_enums::PayoutStatus::RequiresConfirmation
| common_enums::PayoutStatus::RequiresPayoutMethodData
)
&& connector_data
.connector_name
.supports_create_recipient(payout_data.payouts.payout_type)
{
Box::pin(create_recipient(
state,
merchant_context,
connector_data,
payout_data,
))
.await
.attach_printable("Creation of customer failed")?;
}
Ok(())
}
#[cfg(feature = "v1")]
pub async fn create_recipient(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let customer_details = payout_data.customer_details.to_owned();
let connector_name = connector_data.connector_name.to_string();
// Create the connector label using {profile_id}_{connector_name}
let connector_label = format!(
"{}_{}",
payout_data.profile_id.get_string_repr(),
connector_name
);
let (should_call_connector, _connector_customer_id) =
helpers::should_call_payout_connector_create_customer(
state,
connector_data,
&customer_details,
&connector_label,
);
if should_call_connector {
// 1. Form router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoRecipient,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
match router_resp.response {
Ok(recipient_create_data) => {
let db = &*state.store;
if let Some(customer) = customer_details {
if let Some(updated_customer) =
customers::update_connector_customer_in_customers(
&connector_label,
Some(&customer),
recipient_create_data.connector_payout_id.clone(),
)
.await
{
#[cfg(feature = "v1")]
{
let customer_id = customer.customer_id.to_owned();
payout_data.customer_details = Some(
db.update_customer_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_context.get_merchant_account().get_id().to_owned(),
customer,
updated_customer,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating customers in db")?,
);
}
#[cfg(feature = "v2")]
{
let customer_id = customer.get_id().clone();
payout_data.customer_details = Some(
db.update_customer_by_global_id(
&state.into(),
&customer_id,
customer,
updated_customer,
key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating customers in db")?,
);
}
}
}
// Add next step to ProcessTracker
if recipient_create_data.should_add_next_step_to_process_tracker {
add_external_account_addition_task(
&*state.store,
payout_data,
common_utils::date_time::now().saturating_add(Duration::seconds(consts::STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while adding attach_payout_account_workflow workflow to process tracker")?;
// Update payout status in DB
let status = recipient_create_data
.status
.unwrap_or(api_enums::PayoutStatus::RequiresVendorAccountCreation);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data
.payout_attempt
.connector_payout_id
.to_owned(),
status,
error_code: None,
error_message: None,
is_eligible: recipient_create_data.payout_eligible,
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_data
.payout_attempt
.payout_connector_metadata
.to_owned(),
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
// Helps callee functions skip the execution
payout_data.should_terminate = true;
} else if let Some(status) = recipient_create_data.status {
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data
.payout_attempt
.connector_payout_id
.to_owned(),
status,
error_code: None,
error_message: None,
is_eligible: recipient_create_data.payout_eligible,
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_data
.payout_attempt
.payout_connector_metadata
.to_owned(),
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
payout_connector_metadata: payout_data
.payout_attempt
.payout_connector_metadata
.to_owned(),
};
let db = &*state.store;
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
}
}
Ok(())
}
#[cfg(feature = "v2")]
pub async fn create_recipient(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
todo!()
}
pub async fn complete_payout_eligibility(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt.to_owned();
if !payout_data.should_terminate
&& payout_attempt.is_eligible.is_none()
&& connector_data
.connector_name
.supports_payout_eligibility(payout_data.payouts.payout_type)
{
Box::pin(check_payout_eligibility(
state,
merchant_context,
connector_data,
payout_data,
))
.await
.attach_printable("Eligibility failed for given Payout request")?;
}
utils::when(
!payout_attempt
.is_eligible
.unwrap_or(state.conf.payouts.payout_eligibility),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "Payout method data is invalid".to_string(),
})
.attach_printable("Payout data provided is invalid"))
},
)?;
Ok(())
}
pub async fn check_payout_eligibility(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoEligibility,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id,
status,
error_code: payout_response_data.error_code,
error_message: payout_response_data.error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_response_data.payout_connector_metadata,
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: Some(false),
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
payout_connector_metadata: payout_data
.payout_attempt
.payout_connector_metadata
.to_owned(),
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
};
Ok(())
}
pub async fn complete_create_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
if !payout_data.should_terminate
&& matches!(
payout_data.payout_attempt.status,
storage_enums::PayoutStatus::RequiresCreation
| storage_enums::PayoutStatus::RequiresConfirmation
| storage_enums::PayoutStatus::RequiresPayoutMethodData
)
{
if connector_data
.connector_name
.supports_instant_payout(payout_data.payouts.payout_type)
{
// create payout_object only in router
let db = &*state.store;
let payout_attempt = &payout_data.payout_attempt;
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.clone(),
status: storage::enums::PayoutStatus::RequiresFulfillment,
error_code: None,
error_message: None,
is_eligible: None,
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_data
.payout_attempt
.payout_connector_metadata
.to_owned(),
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate {
status: storage::enums::PayoutStatus::RequiresFulfillment,
},
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
} else {
// create payout_object in connector as well as router
Box::pin(create_payout(
state,
merchant_context,
connector_data,
payout_data,
))
.await
.attach_printable("Payout creation failed for given Payout request")?;
}
}
Ok(())
}
pub async fn create_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Get/Create access token
access_token::create_access_token(
state,
connector_data,
merchant_context,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
)
.await?;
// 3. Execute pretasks
if helpers::should_continue_payout(&router_data) {
complete_payout_quote_steps_if_required(state, connector_data, &mut router_data).await?;
};
let connector_meta_data = router_data.connector_meta_data.clone();
// 4. Call connector service
let router_data_resp = match helpers::should_continue_payout(&router_data) {
true => {
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoCreate,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?
}
false => router_data,
};
// 5. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id,
status,
error_code: payout_response_data.error_code,
error_message: payout_response_data.error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
payout_connector_metadata: connector_meta_data.clone(),
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
payout_connector_metadata: connector_meta_data,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
};
Ok(())
}
async fn complete_payout_quote_steps_if_required<F>(
state: &SessionState,
connector_data: &api::ConnectorData,
router_data: &mut types::RouterData<F, types::PayoutsData, types::PayoutsResponseData>,
) -> RouterResult<()> {
if connector_data
.connector_name
.is_payout_quote_call_required()
{
let quote_router_data =
types::PayoutsRouterData::foreign_from((router_data, router_data.request.clone()));
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoQuote,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
"e_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
match router_data_resp.response.to_owned() {
Ok(resp) => {
router_data.quote_id = resp.connector_payout_id;
router_data.connector_meta_data = resp.payout_connector_metadata;
}
Err(_err) => {
router_data.response = router_data_resp.response;
}
};
}
Ok(())
}
#[cfg(feature = "v1")]
pub async fn complete_payout_retrieve(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
match connector_call_type {
api::ConnectorCallType::PreDetermined(routing_data) => {
Box::pin(create_payout_retrieve(
state,
merchant_context,
&routing_data.connector_data,
payout_data,
))
.await
.attach_printable("Payout retrieval failed for given Payout request")?;
}
api::ConnectorCallType::Retryable(_) | api::ConnectorCallType::SessionMultiple(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payout retrieval not supported for given ConnectorCallType")?
}
}
Ok(())
}
#[cfg(feature = "v2")]
pub async fn complete_payout_retrieve(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_call_type: api::ConnectorCallType,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
todo!()
}
pub async fn create_payout_retrieve(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Get/Create access token
access_token::create_access_token(
state,
connector_data,
merchant_context,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
)
.await?;
// 3. Call connector service
let router_data_resp = match helpers::should_continue_payout(&router_data) {
true => {
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoSync,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?
}
false => router_data,
};
// 4. Process data returned by the connector
update_retrieve_payout_tracker(state, merchant_context, payout_data, &router_data_resp).await?;
Ok(())
}
pub async fn update_retrieve_payout_tracker<F, T>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payout_data: &mut PayoutData,
payout_router_data: &types::RouterData<F, T, types::PayoutsResponseData>,
) -> RouterResult<()> {
let db = &*state.store;
match payout_router_data.response.as_ref() {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = if helpers::is_payout_err_state(status) {
let (error_code, error_message) = (
payout_response_data.error_code.clone(),
payout_response_data.error_message.clone(),
);
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code,
error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
payout_connector_metadata: payout_response_data
.payout_connector_metadata
.clone(),
}
} else {
storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_response_data
.payout_connector_metadata
.clone(),
}
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
Err(err) => {
// log in case of error in retrieval
logger::error!("Error in payout retrieval");
// show error in the response of sync
payout_data.payout_attempt.error_code = Some(err.code.to_owned());
payout_data.payout_attempt.error_message = Some(err.message.to_owned());
}
};
Ok(())
}
pub async fn complete_create_recipient_disburse_account(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
if !payout_data.should_terminate
&& matches!(
payout_data.payout_attempt.status,
storage_enums::PayoutStatus::RequiresVendorAccountCreation
| storage_enums::PayoutStatus::RequiresCreation
)
&& connector_data
.connector_name
.supports_vendor_disburse_account_create_for_payout()
&& helpers::should_create_connector_transfer_method(payout_data, connector_data)?.is_none()
{
Box::pin(create_recipient_disburse_account(
state,
merchant_context,
connector_data,
payout_data,
))
.await
.attach_printable("Creation of customer failed")?;
}
Ok(())
}
pub async fn create_recipient_disburse_account(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoRecipientAccount,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let payout_attempt = &payout_data.payout_attempt;
let status = payout_response_data
.status
.unwrap_or(payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id.clone(),
status,
error_code: payout_response_data.error_code,
error_message: payout_response_data.error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_response_data.payout_connector_metadata,
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
if let (
true,
Some(ref payout_method_data),
Some(connector_payout_id),
Some(customer_details),
Some(merchant_connector_id),
) = (
payout_data.payouts.recurring,
payout_data.payout_method_data.clone(),
payout_response_data.connector_payout_id.clone(),
payout_data.customer_details.clone(),
connector_data.merchant_connector_id.clone(),
) {
let connector_mandate_details = HashMap::from([(
merchant_connector_id.clone(),
PayoutsMandateReferenceRecord {
transfer_method_id: Some(connector_payout_id),
},
)]);
let common_connector_mandate = CommonMandateReference {
payments: None,
payouts: Some(PayoutsMandateReference(connector_mandate_details)),
};
let connector_mandate_details_value = common_connector_mandate
.get_mandate_details_value()
.map_err(|err| {
router_env::logger::error!(
"Failed to get get_mandate_details_value : {:?}",
err
);
errors::ApiErrorResponse::MandateUpdateFailed
})?;
if let Some(pm_method) = payout_data.payment_method.clone() {
let pm_update =
diesel_models::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
#[cfg(feature = "v1")]
connector_mandate_details: Some(connector_mandate_details_value),
#[cfg(feature = "v2")]
connector_mandate_details: Some(common_connector_mandate),
};
payout_data.payment_method = Some(
db.update_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
pm_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")?,
);
} else {
#[cfg(feature = "v1")]
let customer_id = Some(customer_details.customer_id);
#[cfg(feature = "v2")]
let customer_id = customer_details.merchant_reference_id;
if let Some(customer_id) = customer_id {
helpers::save_payout_data_to_locker(
state,
payout_data,
&customer_id,
payout_method_data,
Some(connector_mandate_details_value),
merchant_context,
)
.await
.attach_printable("Failed to save payout data to locker")?;
}
};
}
}
Err(err) => {
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status: storage_enums::PayoutStatus::Failed,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
payout_connector_metadata: payout_data
.payout_attempt
.payout_connector_metadata
.to_owned(),
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
}
};
Ok(())
}
pub async fn cancel_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Fetch connector integration details
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoCancel,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
// 3. Call connector service
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?;
// 4. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let status = payout_response_data
.status
.unwrap_or(payout_data.payout_attempt.status.to_owned());
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id,
status,
error_code: None,
error_message: None,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_response_data.payout_connector_metadata,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
payout_connector_metadata: payout_data
.payout_attempt
.payout_connector_metadata
.to_owned(),
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
};
Ok(())
}
pub async fn fulfill_payout(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_data: &api::ConnectorData,
payout_data: &mut PayoutData,
) -> RouterResult<()> {
// 1. Form Router data
let mut router_data = core_utils::construct_payout_router_data(
state,
connector_data,
merchant_context,
payout_data,
)
.await?;
// 2. Get/Create access token
access_token::create_access_token(
state,
connector_data,
merchant_context,
&mut router_data,
payout_data.payouts.payout_type.to_owned(),
)
.await?;
// 3. Call connector service
let router_data_resp = match helpers::should_continue_payout(&router_data) {
true => {
let connector_integration: services::BoxedPayoutConnectorIntegrationInterface<
api::PoFulfill,
types::PayoutsData,
types::PayoutsResponseData,
> = connector_data.connector.get_connector_integration();
services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payout_failed_response()?
}
false => router_data,
};
// 4. Process data returned by the connector
let db = &*state.store;
match router_data_resp.response {
Ok(payout_response_data) => {
let status = payout_response_data
.status
.unwrap_or(payout_data.payout_attempt.status.to_owned());
payout_data.payouts.status = status;
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_response_data.connector_payout_id,
status,
error_code: payout_response_data.error_code,
error_message: payout_response_data.error_message,
is_eligible: payout_response_data.payout_eligible,
unified_code: None,
unified_message: None,
payout_connector_metadata: payout_response_data.payout_connector_metadata,
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
if payout_data.payouts.recurring
&& payout_data.payouts.payout_method_id.clone().is_none()
{
let payout_method_data = payout_data
.payout_method_data
.clone()
.get_required_value("payout_method_data")?;
payout_data
.payouts
.customer_id
.clone()
.async_map(|customer_id| async move {
helpers::save_payout_data_to_locker(
state,
payout_data,
&customer_id,
&payout_method_data,
None,
merchant_context,
)
.await
})
.await
.transpose()
.attach_printable("Failed to save payout data to locker")?;
}
}
Err(err) => {
let status = storage_enums::PayoutStatus::Failed;
let (error_code, error_message) = (Some(err.code), Some(err.message));
let (unified_code, unified_message) = helpers::get_gsm_record(
state,
error_code.clone(),
error_message.clone(),
payout_data.payout_attempt.connector.clone(),
consts::PAYOUT_FLOW_STR,
)
.await
.map_or(
(
Some(crate::consts::DEFAULT_UNIFIED_ERROR_CODE.to_string()),
Some(crate::consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_string()),
),
|gsm| (gsm.unified_code, gsm.unified_message),
);
let updated_payout_attempt = storage::PayoutAttemptUpdate::StatusUpdate {
connector_payout_id: payout_data.payout_attempt.connector_payout_id.to_owned(),
status,
error_code,
error_message,
is_eligible: None,
unified_code: unified_code
.map(UnifiedCode::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_code",
})?,
unified_message: unified_message
.map(UnifiedMessage::try_from)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?,
payout_connector_metadata: payout_data
.payout_attempt
.payout_connector_metadata
.to_owned(),
};
payout_data.payout_attempt = db
.update_payout_attempt(
&payout_data.payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt in db")?;
payout_data.payouts = db
.update_payout(
&payout_data.payouts,
storage::PayoutsUpdate::StatusUpdate { status },
&payout_data.payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts in db")?;
}
};
Ok(())
}
pub async fn trigger_webhook_and_handle_response(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payout_data: &PayoutData,
) -> RouterResponse<payouts::PayoutCreateResponse> {
let response = response_handler(state, merchant_context, payout_data).await?;
utils::trigger_payouts_webhook(state, merchant_context, &response).await?;
Ok(services::ApplicationResponse::Json(response))
}
pub async fn response_handler(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payout_data: &PayoutData,
) -> RouterResult<payouts::PayoutCreateResponse> {
let payout_attempt = payout_data.payout_attempt.to_owned();
let payouts = payout_data.payouts.to_owned();
let payout_method_id: Option<String> = payout_data.payment_method.as_ref().map(|pm| {
#[cfg(feature = "v1")]
{
pm.payment_method_id.clone()
}
#[cfg(feature = "v2")]
{
pm.id.clone().get_string_repr().to_string()
}
});
let payout_link = payout_data.payout_link.to_owned();
let billing_address = payout_data.billing_address.to_owned();
let customer_details = payout_data.customer_details.to_owned();
let customer_id = payouts.customer_id;
let billing = billing_address.map(From::from);
let translated_unified_message = helpers::get_translated_unified_code_and_message(
state,
payout_attempt.unified_code.as_ref(),
payout_attempt.unified_message.as_ref(),
&payout_data.current_locale,
)
.await?;
let additional_payout_method_data = payout_attempt.additional_payout_method_data.clone();
let payout_method_data =
additional_payout_method_data.map(payouts::PayoutMethodDataResponse::from);
let response = api::PayoutCreateResponse {
payout_id: payouts.payout_id.to_owned(),
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
merchant_order_reference_id: payout_attempt.merchant_order_reference_id.clone(),
amount: payouts.amount,
currency: payouts.destination_currency.to_owned(),
connector: payout_attempt.connector,
payout_type: payouts.payout_type.to_owned(),
payout_method_data,
billing,
auto_fulfill: payouts.auto_fulfill,
customer_id,
email: customer_details.as_ref().and_then(|c| c.email.clone()),
name: customer_details.as_ref().and_then(|c| c.name.clone()),
phone: customer_details.as_ref().and_then(|c| c.phone.clone()),
phone_country_code: customer_details
.as_ref()
.and_then(|c| c.phone_country_code.clone()),
customer: customer_details
.as_ref()
.map(payment_api_types::CustomerDetailsResponse::foreign_from),
client_secret: payouts.client_secret.to_owned(),
return_url: payouts.return_url.to_owned(),
business_country: payout_attempt.business_country,
business_label: payout_attempt.business_label,
description: payouts.description.to_owned(),
entity_type: payouts.entity_type.to_owned(),
recurring: payouts.recurring,
metadata: payouts.metadata,
merchant_connector_id: payout_attempt.merchant_connector_id.to_owned(),
status: payout_attempt.status.to_owned(),
error_message: payout_attempt.error_message.to_owned(),
error_code: payout_attempt.error_code,
profile_id: payout_attempt.profile_id,
created: Some(payouts.created_at),
connector_transaction_id: payout_attempt.connector_payout_id,
priority: payouts.priority,
attempts: None,
unified_code: payout_attempt.unified_code,
unified_message: translated_unified_message,
payout_link: payout_link
.map(|payout_link| {
url::Url::parse(payout_link.url.peek()).map(|link| PayoutLinkResponse {
payout_link_id: payout_link.link_id,
link: link.into(),
})
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse payout link's URL")?,
payout_method_id,
};
Ok(response)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn payout_create_db_entries(
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_req: &payouts::PayoutCreateRequest,
_payout_id: &str,
_profile_id: &str,
_stored_payout_method_data: Option<&payouts::PayoutMethodData>,
_locale: &str,
_customer: Option<&domain::Customer>,
_payment_method: Option<PaymentMethod>,
) -> RouterResult<PayoutData> {
todo!()
}
// DB entries
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn payout_create_db_entries(
state: &SessionState,
merchant_context: &domain::MerchantContext,
req: &payouts::PayoutCreateRequest,
payout_id: &id_type::PayoutId,
profile_id: &id_type::ProfileId,
stored_payout_method_data: Option<&payouts::PayoutMethodData>,
locale: &str,
customer: Option<&domain::Customer>,
payment_method: Option<PaymentMethod>,
) -> RouterResult<PayoutData> {
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = customer.map(|cust| cust.customer_id.clone());
// Validate whether profile_id passed in request is valid and is linked to the merchant
let business_profile = validate_and_get_business_profile(
state,
merchant_context.get_merchant_key_store(),
profile_id,
merchant_id,
)
.await?;
let payout_link = match req.payout_link {
Some(true) => Some(
create_payout_link(
state,
&business_profile,
&customer_id
.clone()
.get_required_value("customer.id when payout_link is true")?,
merchant_id,
req,
payout_id,
locale,
)
.await?,
),
_ => None,
};
// Get or create billing address
let (billing_address, address_id) = helpers::resolve_billing_address_for_payout(
state,
req.billing.as_ref(),
None,
payment_method.as_ref(),
merchant_context,
customer_id.as_ref(),
payout_id,
)
.await?;
// Make payouts entry
let currency = req.currency.to_owned().get_required_value("currency")?;
let (payout_method_id, payout_type) = match stored_payout_method_data {
Some(payout_method_data) => (
payment_method
.as_ref()
.map(|pm| pm.payment_method_id.clone()),
Some(api_enums::PayoutType::foreign_from(payout_method_data)),
),
None => {
(
payment_method
.as_ref()
.map(|pm| pm.payment_method_id.clone()),
match req.payout_type {
None => payment_method
.as_ref()
.and_then(|pm| pm.payment_method)
.map(|payment_method_enum| {
api_enums::PayoutType::foreign_try_from(payment_method_enum)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"PaymentMethod {payment_method_enum:?} is not supported for payouts"
),
})
.attach_printable("Failed to convert PaymentMethod to PayoutType")
})
.transpose()?,
payout_type => payout_type,
},
)
}
};
let client_secret = utils::generate_id(
consts::ID_LENGTH,
format!("payout_{}_secret", payout_id.get_string_repr()).as_str(),
);
let amount = MinorUnit::from(req.amount.unwrap_or(api::Amount::Zero));
let status = if req.payout_method_data.is_some()
|| req.payout_token.is_some()
|| stored_payout_method_data.is_some()
{
match req.confirm {
Some(true) => storage_enums::PayoutStatus::RequiresCreation,
_ => storage_enums::PayoutStatus::RequiresConfirmation,
}
} else {
storage_enums::PayoutStatus::RequiresPayoutMethodData
};
let payouts_req = storage::PayoutsNew {
payout_id: payout_id.clone(),
merchant_id: merchant_id.to_owned(),
customer_id: customer_id.to_owned(),
address_id: address_id.to_owned(),
payout_type,
amount,
destination_currency: currency,
source_currency: currency,
description: req.description.to_owned(),
recurring: req.recurring.unwrap_or(false),
auto_fulfill: req.auto_fulfill.unwrap_or(false),
return_url: req.return_url.to_owned(),
entity_type: req.entity_type.unwrap_or_default(),
payout_method_id,
profile_id: profile_id.to_owned(),
attempt_count: 1,
metadata: req.metadata.clone(),
confirm: req.confirm,
payout_link_id: payout_link
.clone()
.map(|link_data| link_data.link_id.clone()),
client_secret: Some(client_secret),
priority: req.priority,
status,
created_at: common_utils::date_time::now(),
last_modified_at: common_utils::date_time::now(),
};
let payouts = db
.insert_payout(
payouts_req,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout {
payout_id: payout_id.clone(),
})
.attach_printable("Error inserting payouts in db")?;
// Make payout_attempt entry
let payout_attempt_id = utils::get_payout_attempt_id(payout_id.get_string_repr(), 1);
let additional_pm_data_value = req
.payout_method_data
.clone()
.or(stored_payout_method_data.cloned())
.async_and_then(|payout_method_data| async move {
helpers::get_additional_payout_data(&payout_method_data, &*state.store, profile_id)
.await
})
.await
// If no payout method data in request but we have a stored payment method, populate from it
.or_else(|| {
payment_method.as_ref().and_then(|payment_method| {
payment_method
.get_payment_methods_data()
.and_then(|pmd| pmd.get_additional_payout_method_data())
})
});
let payout_attempt_req = storage::PayoutAttemptNew {
payout_attempt_id: payout_attempt_id.to_string(),
payout_id: payout_id.clone(),
additional_payout_method_data: additional_pm_data_value,
merchant_id: merchant_id.to_owned(),
merchant_order_reference_id: req.merchant_order_reference_id.clone(),
status,
business_country: req.business_country.to_owned(),
business_label: req.business_label.to_owned(),
payout_token: req.payout_token.to_owned(),
profile_id: profile_id.to_owned(),
customer_id,
address_id,
connector: None,
connector_payout_id: None,
is_eligible: None,
error_message: None,
error_code: None,
created_at: common_utils::date_time::now(),
last_modified_at: common_utils::date_time::now(),
merchant_connector_id: None,
routing_info: None,
unified_code: None,
unified_message: None,
payout_connector_metadata: None,
};
let payout_attempt = db
.insert_payout_attempt(
payout_attempt_req,
&payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayout {
payout_id: payout_id.clone(),
})
.attach_printable("Error inserting payout_attempt in db")?;
// Make PayoutData
Ok(PayoutData {
billing_address,
business_profile,
customer_details: customer.map(ToOwned::to_owned),
merchant_connector_account: None,
payouts,
payout_attempt,
payout_method_data: req
.payout_method_data
.as_ref()
.cloned()
.or(stored_payout_method_data.cloned()),
should_terminate: false,
profile_id: profile_id.to_owned(),
payout_link,
current_locale: locale.to_string(),
payment_method,
connector_transfer_method_id: None,
browser_info: req.browser_info.clone().map(Into::into),
})
}
#[cfg(feature = "v2")]
pub async fn make_payout_data(
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_auth_profile_id: Option<id_type::ProfileId>,
_req: &payouts::PayoutRequest,
locale: &str,
) -> RouterResult<PayoutData> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn make_payout_data(
state: &SessionState,
merchant_context: &domain::MerchantContext,
auth_profile_id: Option<id_type::ProfileId>,
req: &payouts::PayoutRequest,
locale: &str,
) -> RouterResult<PayoutData> {
let db = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
let payout_id = match req {
payouts::PayoutRequest::PayoutActionRequest(r) => r.payout_id.clone(),
payouts::PayoutRequest::PayoutCreateRequest(r) => {
r.payout_id.clone().unwrap_or(id_type::PayoutId::generate())
}
payouts::PayoutRequest::PayoutRetrieveRequest(r) => r.payout_id.clone(),
};
let browser_info = match req {
payouts::PayoutRequest::PayoutActionRequest(_) => None,
payouts::PayoutRequest::PayoutCreateRequest(r) => r.browser_info.clone().map(Into::into),
payouts::PayoutRequest::PayoutRetrieveRequest(_) => None,
};
let payouts = db
.find_payout_by_merchant_id_payout_id(
merchant_id,
&payout_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &payouts)?;
let payout_attempt_id =
utils::get_payout_attempt_id(payouts.payout_id.get_string_repr(), payouts.attempt_count);
let mut payout_attempt = db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
&payout_attempt_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?;
let customer_id = payouts.customer_id.as_ref();
// We have to do this because the function that is being used to create / get address is from payments
// which expects a payment_id
let payout_id_as_payment_id_type = id_type::PaymentId::try_from(std::borrow::Cow::Owned(
payouts.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 billing_address = payment_helpers::create_or_find_address_for_payment_by_request(
state,
None,
payouts.address_id.as_deref(),
merchant_id,
customer_id,
merchant_context.get_merchant_key_store(),
&payout_id_as_payment_id_type,
merchant_context.get_merchant_account().storage_scheme,
)
.await?
.map(|addr| domain_models::address::Address::from(&addr));
let payout_id = &payouts.payout_id;
let customer_details = customer_id
.async_map(|customer_id| async move {
db.find_customer_optional_by_customer_id_merchant_id(
&state.into(),
customer_id,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.map_err(|err| err.change_context(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| {
format!(
"Failed while fetching optional customer [id - {customer_id:?}] for payout [id - {}]", payout_id.get_string_repr()
)
})
})
.await
.transpose()?
.and_then(|c| c);
let profile_id = payout_attempt.profile_id.clone();
// Validate whether profile_id passed in request is valid and is linked to the merchant
let business_profile = validate_and_get_business_profile(
state,
merchant_context.get_merchant_key_store(),
&profile_id,
merchant_id,
)
.await?;
let payout_method_data_req = match req {
payouts::PayoutRequest::PayoutCreateRequest(r) => r.payout_method_data.to_owned(),
payouts::PayoutRequest::PayoutActionRequest(_) => {
match payout_attempt.payout_token.to_owned() {
Some(payout_token) => {
let customer_id = customer_details
.as_ref()
.map(|cd| cd.customer_id.to_owned())
.get_required_value("customer_id when payout_token is sent")?;
helpers::make_payout_method_data(
state,
None,
Some(&payout_token),
&customer_id,
merchant_context.get_merchant_account().get_id(),
payouts.payout_type,
merchant_context.get_merchant_key_store(),
None,
merchant_context.get_merchant_account().storage_scheme,
)
.await?
}
None => None,
}
}
payouts::PayoutRequest::PayoutRetrieveRequest(_) => None,
};
if let Some(payout_method_data) = payout_method_data_req.clone() {
let additional_payout_method_data =
helpers::get_additional_payout_data(&payout_method_data, &*state.store, &profile_id)
.await;
let update_additional_payout_method_data =
storage::PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate {
additional_payout_method_data,
};
payout_attempt = db
.update_payout_attempt(
&payout_attempt,
update_additional_payout_method_data,
&payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating additional payout method data in payout_attempt")?;
};
let merchant_connector_account =
if payout_attempt.connector.is_some() && payout_attempt.merchant_connector_id.is_some() {
let connector_name = payout_attempt
.connector
.clone()
.get_required_value("connector_name")?;
Some(
payment_helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
connector_name.as_str(),
payout_attempt.merchant_connector_id.as_ref(),
)
.await?,
)
} else {
None
};
let payout_link = payouts
.payout_link_id
.clone()
.async_map(|link_id| async move {
db.find_payout_link_by_link_id(&link_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching payout links from db")
})
.await
.transpose()?;
let payment_method = payouts
.payout_method_id
.clone()
.async_map(|pm_id| async move {
db.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
&pm_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("Unable to find payment method")
})
.await
.transpose()?;
Ok(PayoutData {
billing_address,
business_profile,
customer_details,
payouts,
payout_attempt,
payout_method_data: payout_method_data_req.to_owned(),
merchant_connector_account,
should_terminate: false,
profile_id,
payout_link,
current_locale: locale.to_string(),
payment_method,
connector_transfer_method_id: None,
browser_info,
})
}
pub async fn add_external_account_addition_task(
db: &dyn StorageInterface,
payout_data: &PayoutData,
schedule_time: time::PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
let runner = storage::ProcessTrackerRunner::AttachPayoutAccountWorkflow;
let task = "STRPE_ATTACH_EXTERNAL_ACCOUNT";
let tag = ["PAYOUTS", "STRIPE", "ACCOUNT", "CREATE"];
let process_tracker_id = pt_utils::get_process_tracker_id(
runner,
task,
&payout_data.payout_attempt.payout_attempt_id,
&payout_data.payout_attempt.merchant_id,
);
let tracking_data = api::PayoutRetrieveRequest {
payout_id: payout_data.payouts.payout_id.to_owned(),
force_sync: None,
merchant_id: Some(payout_data.payouts.merchant_id.to_owned()),
};
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.map_err(errors::StorageError::from)?;
db.insert_process(process_tracker_entry).await?;
Ok(())
}
async fn validate_and_get_business_profile(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
profile_id: &id_type::ProfileId,
merchant_id: &id_type::MerchantId,
) -> RouterResult<domain::Profile> {
let db = &*state.store;
let key_manager_state = &state.into();
if let Some(business_profile) = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_key_store,
Some(profile_id),
merchant_id,
)
.await?
{
Ok(business_profile)
} else {
db.find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})
}
}
#[allow(clippy::too_many_arguments)]
pub async fn create_payout_link(
state: &SessionState,
business_profile: &domain::Profile,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
req: &payouts::PayoutCreateRequest,
payout_id: &id_type::PayoutId,
locale: &str,
) -> RouterResult<PayoutLink> {
let payout_link_config_req = req.payout_link_config.to_owned();
// Fetch all configs
let default_config = &state.conf.generic_link.payout_link;
let profile_config = &business_profile.payout_link_config;
let profile_ui_config = profile_config.as_ref().map(|c| c.config.ui_config.clone());
let ui_config = payout_link_config_req
.as_ref()
.and_then(|config| config.ui_config.clone())
.or(profile_ui_config);
let test_mode_in_config = payout_link_config_req
.as_ref()
.and_then(|config| config.test_mode)
.or_else(|| profile_config.as_ref().and_then(|c| c.payout_test_mode));
let is_test_mode_enabled = test_mode_in_config.unwrap_or(false);
let allowed_domains = match (router_env::which(), is_test_mode_enabled) {
// Throw error in case test_mode was enabled in production
(Env::Production, true) => Err(report!(errors::ApiErrorResponse::LinkConfigurationError {
message: "test_mode cannot be true for creating payout_links in production".to_string()
})),
// Send empty set of whitelisted domains
(_, true) => {
Ok(HashSet::new())
},
// Otherwise, fetch and use allowed domains from profile config
(_, false) => {
profile_config
.as_ref()
.map(|config| config.config.allowed_domains.to_owned())
.get_required_value("allowed_domains")
.change_context(errors::ApiErrorResponse::LinkConfigurationError {
message:
"Payout links cannot be used without setting allowed_domains in profile. If you're using a non-production environment, you can set test_mode to true while in payout_link_config"
.to_string(),
})
}
}?;
// Form data to be injected in the link
let (logo, merchant_name, theme) = match ui_config {
Some(config) => (config.logo, config.merchant_name, config.theme),
_ => (None, None, None),
};
let payout_link_config = GenericLinkUiConfig {
logo,
merchant_name,
theme,
};
let client_secret = utils::generate_id(consts::ID_LENGTH, "payout_link_secret");
let base_url = profile_config
.as_ref()
.and_then(|c| c.config.domain_name.as_ref())
.map(|domain| format!("https://{domain}"))
.unwrap_or(state.base_url.clone());
let session_expiry = req
.session_expiry
.as_ref()
.map_or(default_config.expiry, |expiry| *expiry);
let url = format!(
"{base_url}/payout_link/{}/{}?locale={}",
merchant_id.get_string_repr(),
payout_id.get_string_repr(),
locale
);
let link = url::Url::parse(&url)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed to form payout link URL - {url}"))?;
let req_enabled_payment_methods = payout_link_config_req
.as_ref()
.and_then(|req| req.enabled_payment_methods.to_owned());
let amount = req
.amount
.as_ref()
.get_required_value("amount")
.attach_printable("amount is a required value when creating payout links")?;
let currency = req
.currency
.as_ref()
.get_required_value("currency")
.attach_printable("currency is a required value when creating payout links")?;
let payout_link_id = core_utils::get_or_generate_id(
"payout_link_id",
&payout_link_config_req
.as_ref()
.and_then(|config| config.payout_link_id.clone()),
"payout_link",
)?;
let form_layout = payout_link_config_req
.as_ref()
.and_then(|config| config.form_layout.to_owned())
.or_else(|| {
profile_config
.as_ref()
.and_then(|config| config.form_layout.to_owned())
});
let data = PayoutLinkData {
payout_link_id: payout_link_id.clone(),
customer_id: customer_id.clone(),
payout_id: payout_id.clone(),
link,
client_secret: Secret::new(client_secret),
session_expiry,
ui_config: payout_link_config,
enabled_payment_methods: req_enabled_payment_methods,
amount: MinorUnit::from(*amount),
currency: *currency,
allowed_domains,
form_layout,
test_mode: test_mode_in_config,
};
create_payout_link_db_entry(state, merchant_id, &data, req.return_url.clone()).await
}
pub async fn create_payout_link_db_entry(
state: &SessionState,
merchant_id: &id_type::MerchantId,
payout_link_data: &PayoutLinkData,
return_url: Option<String>,
) -> RouterResult<PayoutLink> {
let db: &dyn StorageInterface = &*state.store;
let link_data = serde_json::to_value(payout_link_data)
.map_err(|_| report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable("Failed to convert PayoutLinkData to Value")?;
let payout_link = GenericLinkNew {
link_id: payout_link_data.payout_link_id.to_string(),
primary_reference: payout_link_data.payout_id.get_string_repr().to_string(),
merchant_id: merchant_id.to_owned(),
link_type: common_enums::GenericLinkType::PayoutLink,
link_status: GenericLinkStatus::PayoutLink(PayoutLinkStatus::Initiated),
link_data,
url: payout_link_data.link.to_string().into(),
return_url,
expiry: common_utils::date_time::now()
+ Duration::seconds(payout_link_data.session_expiry.into()),
..Default::default()
};
db.insert_payout_link(payout_link)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "payout link already exists".to_string(),
})
}
#[instrument(skip_all)]
pub async fn get_mca_from_profile_id(
state: &SessionState,
merchant_context: &domain::MerchantContext,
profile_id: &id_type::ProfileId,
connector_name: &str,
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
) -> RouterResult<payment_helpers::MerchantConnectorAccountType> {
let merchant_connector_account = payment_helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
profile_id,
connector_name,
merchant_connector_id,
)
.await?;
Ok(merchant_connector_account)
}
| crates/router/src/core/payouts.rs | router::src::core::payouts | 24,928 | true |
// File: crates/router/src/core/refunds_v2.rs
// Module: router::src::core::refunds_v2
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, 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,
merchant_context: domain::MerchantContext,
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(
&(&state).into(),
&req.payment_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(
&(&state).into(),
merchant_context.get_merchant_key_store(),
&req.payment_id,
merchant_context.get_merchant_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,
&merchant_context,
&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,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?;
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let mca = db
.find_merchant_connector_account_by_id(
&state.into(),
&mca_id,
merchant_context.get_merchant_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,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.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,
))
.await;
let refund_update = get_refund_update_object(
state,
&connector,
&storage_scheme,
merchant_context,
&connector_response,
)
.await;
let response = match refund_update {
Some(refund_update) => state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_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(),
};
// Implement outgoing webhooks here
connector_response.to_refund_failed_response()?;
Ok(response)
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn internal_trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails,
) -> errors::RouterResult<diesel_refund::Refund> {
let storage_scheme = merchant_context.get_merchant_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,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.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,
))
.await;
let refund_update = get_refund_update_object(
state,
&connector,
&storage_scheme,
merchant_context,
&connector_response,
)
.await;
let response = match refund_update {
Some(refund_update) => state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_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(),
};
// Implement outgoing webhooks here
connector_response.to_refund_failed_response()?;
Ok(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>,
) -> 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,
None,
)
.await
} else {
Ok(router_data)
}
}
async fn get_refund_update_object(
state: &SessionState,
connector: &api::ConnectorData,
storage_scheme: &enums::MerchantStorageScheme,
merchant_context: &domain::MerchantContext,
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,
merchant_context,
)),
}
}
}
}
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.to_string(),
)
.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::AUTHORIZE_FLOW_STR.to_string(),
)
.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,
merchant_context: &domain::MerchantContext,
) -> 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",
merchant_context.get_merchant_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::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,
merchant_context: domain::MerchantContext,
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,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let response = Box::pin(refund_retrieve_core(
state.clone(),
merchant_context,
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,
merchant_context: domain::MerchantContext,
profile_id: Option<id_type::ProfileId>,
request: refunds::RefundsRetrieveRequest,
refund: diesel_refund::Refund,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let key_manager_state = &(&state).into();
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(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(
key_manager_state,
merchant_context.get_merchant_key_store(),
&active_attempt_id,
merchant_context.get_merchant_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 = if should_call_refund(&refund, request.force_sync.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,
&merchant_context,
&payment_attempt,
&payment_intent,
&refund,
merchant_connector_details,
))
.await
} else {
Box::pin(sync_refund_with_gateway(
&state,
&merchant_context,
&payment_attempt,
&payment_intent,
&refund,
))
.await
}
} else {
Ok(refund)
}?;
Ok(response)
}
fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: 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 = 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,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &diesel_refund::Refund,
) -> errors::RouterResult<diesel_refund::Refund> {
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(
&state.into(),
&mca_id,
merchant_context.get_merchant_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,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.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,
))
.await
.to_refund_failed_response()?;
let connector_response = perform_integrity_check(connector_response);
let refund_update =
build_refund_update_for_rsync(&connector, merchant_context, connector_response);
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_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)
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn internal_sync_refund_with_gateway(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &diesel_refund::Refund,
merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails,
) -> errors::RouterResult<diesel_refund::Refund> {
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,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.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,
))
.await
.to_refund_failed_response()?;
let connector_response = perform_integrity_check(connector_response);
let refund_update =
build_refund_update_for_rsync(&connector, merchant_context, connector_response);
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_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)
}
pub fn build_refund_update_for_rsync(
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
router_data_response: RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
) -> diesel_refund::RefundUpdate {
let merchant_account = merchant_context.get_merchant_account();
let storage_scheme = &merchant_context.get_merchant_account().storage_scheme;
match router_data_response.response {
Err(error_message) => {
let refund_status = match error_message.status_code {
// marking failure for 2xx because this is genuine refund failure
200..=299 => Some(enums::RefundStatus::Failure),
_ => None,
};
let refund_error_message = error_message.reason.or(Some(error_message.message));
let refund_error_code = Some(error_message.code);
diesel_refund::RefundUpdate::build_error_update_for_refund_failure(
refund_status,
refund_error_message,
refund_error_code,
storage_scheme,
)
}
Ok(response) => match router_data_response.integrity_check.clone() {
Err(err) => {
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("merchant_id", merchant_account.get_id().clone()),
),
);
let connector_refund_id = err
.connector_transaction_id
.map(common_utils_types::ConnectorTransactionId::from);
diesel_refund::RefundUpdate::build_error_update_for_integrity_check_failure(
err.field_names,
connector_refund_id,
storage_scheme,
)
}
Ok(()) => {
let connector_refund_id =
common_utils_types::ConnectorTransactionId::from(response.connector_refund_id);
diesel_refund::RefundUpdate::build_refund_update(
connector_refund_id,
response.refund_status,
storage_scheme,
)
}
},
}
}
// ********************************************** Refund list **********************************************
/// If payment_id is provided, lists all the refunds associated with that particular payment_id
/// If payment_id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default
#[instrument(skip_all)]
#[cfg(feature = "olap")]
pub async fn refund_list(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile: domain::Profile,
req: refunds::RefundListRequest,
) -> errors::RouterResponse<refunds::RefundListResponse> {
let db = state.store;
let limit = refunds_validator::validate_refund_list(req.limit)?;
let offset = req.offset.unwrap_or_default();
let refund_list = db
.filter_refund_by_constraints(
merchant_account.get_id(),
RefundListConstraints::from((req.clone(), profile.clone())),
merchant_account.storage_scheme,
limit,
offset,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let data: Vec<refunds::RefundResponse> = refund_list
.into_iter()
.map(refunds::RefundResponse::foreign_try_from)
.collect::<Result<_, _>>()?;
let total_count = db
.get_total_count_of_refunds(
merchant_account.get_id(),
RefundListConstraints::from((req, profile)),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
Ok(services::ApplicationResponse::Json(
api_models::refunds::RefundListResponse {
count: data.len(),
total_count,
data,
},
))
}
// ********************************************** VALIDATIONS **********************************************
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn validate_and_create_refund(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund_amount: common_utils_types::MinorUnit,
req: refunds::RefundsCreateRequest,
global_refund_id: id_type::GlobalRefundId,
merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
) -> errors::RouterResult<refunds::RefundResponse> {
let db = &*state.store;
let refund_type = req.refund_type.unwrap_or_default();
let merchant_reference_id = req.merchant_reference_id;
let predicate = req
.merchant_id
.as_ref()
.map(|merchant_id| merchant_id != merchant_context.get_merchant_account().get_id());
utils::when(predicate.unwrap_or(false), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string()
})
.attach_printable("invalid merchant_id in request"))
})?;
let connector_payment_id = payment_attempt.clone().connector_payment_id.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.")
})?;
let all_refunds = db
.find_refund_by_merchant_id_connector_transaction_id(
merchant_context.get_merchant_account().get_id(),
&connector_payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let currency = payment_intent.amount_details.currency;
refunds_validator::validate_payment_order_age(
&payment_intent.created_at,
state.conf.refund.max_age,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "created_at".to_string(),
expected_format: format!(
"created_at not older than {} days",
state.conf.refund.max_age,
),
})?;
let total_amount_captured = payment_intent
.amount_captured
.unwrap_or(payment_attempt.get_total_amount());
refunds_validator::validate_refund_amount(
total_amount_captured.get_amount_as_i64(),
&all_refunds,
refund_amount.get_amount_as_i64(),
)
.change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
refunds_validator::validate_maximum_refund_against_payment_attempt(
&all_refunds,
state.conf.refund.max_attempts,
)
.change_context(errors::ApiErrorResponse::MaximumRefundCount)?;
let connector = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
let (connector_transaction_id, processor_transaction_data) =
common_utils_types::ConnectorTransactionId::form_id_and_data(connector_payment_id);
let refund_create_req = diesel_refund::RefundNew {
id: global_refund_id,
merchant_reference_id: merchant_reference_id.clone(),
external_reference_id: Some(merchant_reference_id.get_string_repr().to_string()),
payment_id: req.payment_id,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector_transaction_id,
connector,
refund_type: enums::RefundType::foreign_from(req.refund_type.unwrap_or_default()),
total_amount: payment_attempt.get_total_amount(),
refund_amount,
currency,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
refund_status: enums::RefundStatus::Pending,
metadata: req.metadata,
description: req.reason.clone(),
attempt_id: payment_attempt.id.clone(),
refund_reason: req.reason,
profile_id: Some(payment_intent.profile_id.clone()),
connector_id: payment_attempt.merchant_connector_id.clone(),
charges: None,
split_refunds: None,
connector_refund_id: None,
sent_to_gateway: Default::default(),
refund_arn: None,
updated_by: Default::default(),
organization_id: merchant_context
.get_merchant_account()
.organization_id
.clone(),
processor_transaction_data,
processor_refund_data: None,
};
let refund = match db
.insert_refund(
refund_create_req,
merchant_context.get_merchant_account().storage_scheme,
)
.await
{
Ok(refund) => {
Box::pin(schedule_refund_execution(
state,
refund.clone(),
refund_type,
merchant_context,
payment_attempt,
payment_intent,
merchant_connector_details,
))
.await?
}
Err(err) => {
if err.current_context().is_db_unique_violation() {
Err(errors::ApiErrorResponse::DuplicateRefundRequest)?
} else {
Err(err)
.change_context(errors::ApiErrorResponse::RefundFailed { data: None })
.attach_printable("Failed to insert refund")?
}
}
};
let unified_translated_message =
match (refund.unified_code.clone(), refund.unified_message.clone()) {
(Some(unified_code), Some(unified_message)) => helpers::get_unified_translation(
state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message)),
_ => refund.unified_message,
};
let refund = diesel_refund::Refund {
unified_message: unified_translated_message,
..refund
};
api::RefundResponse::foreign_try_from(refund)
}
impl ForeignTryFrom<diesel_refund::Refund> for api::RefundResponse {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(refund: diesel_refund::Refund) -> Result<Self, Self::Error> {
let refund = refund;
let profile_id = refund
.profile_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Profile id not found")?;
let connector_name = refund.connector;
let connector = Connector::from_str(&connector_name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector_name:?}")
})?;
Ok(Self {
payment_id: refund.payment_id,
id: refund.id.clone(),
amount: refund.refund_amount,
currency: refund.currency,
reason: refund.refund_reason,
status: refunds::RefundStatus::foreign_from(refund.refund_status),
profile_id,
metadata: refund.metadata,
created_at: refund.created_at,
updated_at: refund.modified_at,
connector,
merchant_connector_id: refund.connector_id,
merchant_reference_id: Some(refund.merchant_reference_id),
error_details: Some(RefundErrorDetails {
code: refund.refund_error_code.unwrap_or_default(),
message: refund.refund_error_message.unwrap_or_default(),
}),
connector_refund_reference_id: None,
})
}
}
// ********************************************** PROCESS TRACKER **********************************************
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn schedule_refund_execution(
state: &SessionState,
refund: diesel_refund::Refund,
refund_type: api_models::refunds::RefundType,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter;
let task = "EXECUTE_REFUND";
let task_id = format!("{runner}_{task}_{}", refund.id.get_string_repr());
let refund_process = db
.find_process_by_id(&task_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find the process id")?;
let result = match refund.refund_status {
enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => {
match (refund.sent_to_gateway, refund_process) {
(false, None) => {
// Execute the refund task based on refund_type
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_execute_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.id.get_string_repr()))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
let update_refund =
if state.conf.merchant_id_auth.merchant_id_auth_enabled {
let merchant_connector_details =
match merchant_connector_details {
Some(details) => details,
None => {
return Err(report!(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_connector_details"
}
));
}
};
Box::pin(internal_trigger_refund_to_gateway(
state,
&refund,
merchant_context,
payment_attempt,
payment_intent,
merchant_connector_details,
))
.await
} else {
Box::pin(trigger_refund_to_gateway(
state,
&refund,
merchant_context,
payment_attempt,
payment_intent,
))
.await
};
match update_refund {
Ok(updated_refund_data) => {
add_refund_sync_task(db, &updated_refund_data, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!(
"Failed while pushing refund sync task in scheduler: refund_id: {}",
refund.id.get_string_repr()
))?;
Ok(updated_refund_data)
}
Err(err) => Err(err),
}
}
}
}
_ => {
// Sync the refund for status check
//[#300]: return refund status response
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_sync_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr()))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
// [#255]: This is not possible in schedule_refund_execution as it will always be scheduled
// sync_refund_with_gateway(data, &refund).await
Ok(refund)
}
}
}
}
}
// [#255]: This is not allowed to be otherwise or all
_ => Ok(refund),
}?;
Ok(result)
}
#[instrument]
pub fn refund_to_refund_core_workflow_model(
refund: &diesel_refund::Refund,
) -> diesel_refund::RefundCoreWorkflow {
diesel_refund::RefundCoreWorkflow {
refund_id: refund.id.clone(),
connector_transaction_id: refund.connector_transaction_id.clone(),
merchant_id: refund.merchant_id.clone(),
payment_id: refund.payment_id.clone(),
processor_transaction_data: refund.processor_transaction_data.clone(),
}
}
#[instrument(skip_all)]
pub async fn add_refund_execute_task(
db: &dyn db::StorageInterface,
refund: &diesel_refund::Refund,
runner: storage::ProcessTrackerRunner,
) -> errors::RouterResult<storage::ProcessTracker> {
let task = "EXECUTE_REFUND";
let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr());
let tag = ["REFUND"];
let schedule_time = common_utils::date_time::now();
let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
refund_workflow_tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct refund execute process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)
.attach_printable_lazy(|| {
format!(
"Failed while inserting task in process_tracker: refund_id: {}",
refund.id.get_string_repr()
)
})?;
Ok(response)
}
#[instrument(skip_all)]
pub async fn add_refund_sync_task(
db: &dyn db::StorageInterface,
refund: &diesel_refund::Refund,
runner: storage::ProcessTrackerRunner,
) -> errors::RouterResult<storage::ProcessTracker> {
let task = "SYNC_REFUND";
let process_tracker_id = format!("{runner}_{task}_{}", refund.id.get_string_repr());
let schedule_time = common_utils::date_time::now();
let refund_workflow_tracking_data = refund_to_refund_core_workflow_model(refund);
let tag = ["REFUND"];
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
refund_workflow_tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct refund sync process tracker task")?;
let response = db
.insert_process(process_tracker_entry)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)
.attach_printable_lazy(|| {
format!(
"Failed while inserting task in process_tracker: refund_id: {}",
refund.id.get_string_repr()
)
})?;
metrics::TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "Refund")));
Ok(response)
}
| crates/router/src/core/refunds_v2.rs | router::src::core::refunds_v2 | 10,403 | true |
// File: crates/router/src/core/fraud_check.rs
// Module: router::src::core::fraud_check
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,
merchant_context: &domain::MerchantContext,
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,
merchant_context: &domain::MerchantContext,
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,
merchant_context,
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,
merchant_context,
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,
merchant_context,
)
.await?;
Ok(router_data_res)
}
#[cfg(feature = "v2")]
pub async fn should_call_frm<F, D>(
_merchant_context: &domain::MerchantContext,
_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>(
merchant_context: &domain::MerchantContext,
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 merchant_context
.get_merchant_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(
&state.into(),
&profile_id,
&frm_routing_algorithm_struct.data,
merchant_context.get_merchant_key_store(),
)
.await
.map_err(|error| {
logger::error!(
"{:?}",
error.change_context(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_context
.get_merchant_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,
merchant_context: &domain::MerchantContext,
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,
merchant_context: &domain::MerchantContext,
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: merchant_context.get_merchant_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,
merchant_context: &domain::MerchantContext,
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, merchant_context, customer)
.await?;
let _router_data = call_frm_service::<F, frm_api::Transaction, _, D>(
state,
payment_data,
frm_data,
merchant_context,
customer,
)
.await?;
let frm_data_updated = fraud_check_operation
.to_update_tracker()?
.update_tracker(
state,
merchant_context.get_merchant_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,
merchant_context: &domain::MerchantContext,
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,
merchant_context,
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,
merchant_context.get_merchant_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,
merchant_context,
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,
merchant_context.get_merchant_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>,
merchant_context: &domain::MerchantContext,
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(merchant_context, 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,
merchant_context,
payment_data.to_owned(),
frm_routing_algorithm_val,
profile_id,
frm_configs.clone(),
customer,
))
.await?;
if is_frm_enabled {
pre_payment_frm_core(
state,
merchant_context,
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,
merchant_context: domain::MerchantContext,
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(
&(&state).into(),
&req.payment_id.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
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(),
merchant_context.get_merchant_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,
merchant_context,
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(
db: &dyn StorageInterface,
fraud_check: FraudCheck,
payment_intent: PaymentIntent,
state: SessionState,
merchant_context: domain::MerchantContext,
req: frm_core_types::FrmFulfillmentRequest,
) -> RouterResponse<frm_types::FraudCheckResponseData> {
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&payment_intent.active_attempt.get_id(),
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_data = FraudCheckConnectorData::get_connector_by_name(&fraud_check.frm_name)?;
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
Fulfillment,
frm_types::FraudCheckFulfillmentData,
frm_types::FraudCheckResponseData,
> = connector_data.connector.get_connector_integration();
let router_data = frm_flows::fulfillment_flow::construct_fulfillment_router_data(
&state,
&payment_intent,
&payment_attempt,
&merchant_context,
fraud_check.frm_name.clone(),
req,
)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let fraud_check_copy = fraud_check.clone();
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: fraud_check.frm_status,
frm_transaction_id: fraud_check.frm_transaction_id,
frm_reason: fraud_check.frm_reason,
frm_score: fraud_check.frm_score,
metadata: fraud_check.metadata,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Fulfillment,
payment_capture_method: fraud_check.payment_capture_method,
};
let _updated = db
.update_fraud_check_response_with_attempt_id(fraud_check_copy, fraud_check_update)
.await
.map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?;
let fulfillment_response =
response
.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(services::ApplicationResponse::Json(fulfillment_response))
}
| crates/router/src/core/fraud_check.rs | router::src::core::fraud_check | 6,711 | true |
// File: crates/router/src/core/cards_info.rs
// Module: router::src::core::cards_info
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,
merchant_context: domain::MerchantContext,
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,
&merchant_context,
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()))
}
| crates/router/src/core/cards_info.rs | router::src::core::cards_info | 2,602 | true |
// File: crates/router/src/core/revenue_recovery_data_backfill.rs
// Module: router::src::core::revenue_recovery_data_backfill
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 error_stack::ResultExt;
use hyperswitch_domain_models::api::ApplicationResponse;
use masking::ExposeInterface;
use router_env::{instrument, logger};
use time::{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(
state: SessionState,
connector_customer_id: String,
) -> RouterResult<ApplicationResponse<UnlockStatusResponse>> {
let unlocked = storage::revenue_recovery_redis_operation::
RedisTokenManager::unlock_connector_customer_status(&state, &connector_customer_id)
.await
.map_err(|e| {
logger::error!(
"Failed to unlock connector customer status for {}: {}",
connector_customer_id,
e
);
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,
}
}
};
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<Date, i32>> {
match json_str {
Some(json) if !json.is_empty() => {
match serde_json::from_str::<HashMap<String, i32>>(json) {
Ok(string_retry_history) => {
// Convert string dates to Date objects
let format = format_description::parse("[year]-[month]-[day]")
.map_err(|e| {
BackfillError::CsvParsingError(format!(
"Invalid date format configuration: {}",
e
))
})
.ok()?;
let mut date_retry_history = HashMap::new();
for (date_str, count) in string_retry_history {
match Date::parse(&date_str, &format) {
Ok(date) => {
date_retry_history.insert(date, count);
}
Err(e) => {
logger::warn!(
"Failed to parse date '{}' in daily_retry_history: {}",
date_str,
e
);
}
}
}
logger::debug!(
"Successfully parsed daily_retry_history with {} entries",
date_retry_history.len()
);
Some(date_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 = Some(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,
})
}
/// Determine card type with fallback logic: payment_method_sub_type if not present -> "Card"
fn determine_card_type(payment_method_sub_type: Option<PaymentMethodType>) -> 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
);
mapped_type
}
None => {
logger::info!("In CSV payment_method_sub_type not present, defaulting to 'card'");
"card".to_string()
}
}
}
/// 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))
})
}
| crates/router/src/core/revenue_recovery_data_backfill.rs | router::src::core::revenue_recovery_data_backfill | 3,398 | true |
// File: crates/router/src/core/configs.rs
// Module: router::src::core::configs
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
let result = 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)
};
result
}
/// 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
let result = 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)
};
result
}
/// 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
let result = 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)
};
result
}
/// 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
let result = 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)
};
result
}
/// 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
let result = 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)
};
result
}
| crates/router/src/core/configs.rs | router::src::core::configs | 1,915 | true |
// File: crates/router/src/core/payout_link.rs
// Module: router::src::core::payout_link
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,
_merchant_context: domain::MerchantContext,
_req: payouts::PayoutLinkInitiateRequest,
_request_headers: &header::HeaderMap,
_locale: String,
) -> RouterResponse<services::GenericLinkFormData> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn initiate_payout_link(
state: SessionState,
merchant_context: domain::MerchantContext,
req: payouts::PayoutLinkInitiateRequest,
request_headers: &header::HeaderMap,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
let merchant_id = merchant_context.get_merchant_account().get_id();
// Fetch payout
let payout = db
.find_payout_by_merchant_id_payout_id(
merchant_id,
&req.payout_id,
merchant_context.get_merchant_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),
merchant_context.get_merchant_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(
&(&state).into(),
&customer_id,
&req.merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(
&(&state).into(),
address_id,
merchant_context.get_merchant_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, &merchant_context, &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(
merchant_context
.get_merchant_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,
merchant_context: &domain::MerchantContext,
payout: &hyperswitch_domain_models::payouts::payouts::Payouts,
address: Option<&domain::Address>,
) -> errors::RouterResult<Vec<link_utils::EnabledPaymentMethod>> {
use masking::ExposeInterface;
let db = &*state.store;
let key_manager_state = &state.into();
//Fetch all merchant connector accounts
let all_mcas = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
false,
merchant_context.get_merchant_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 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::CardRedirect
| common_enums::PaymentMethod::PayLater
| common_enums::PaymentMethod::BankRedirect
| 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 => 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))
}
}
| crates/router/src/core/payout_link.rs | router::src::core::payout_link | 3,870 | true |
// File: crates/router/src/core/connector_validation.rs
// Module: router::src::core::connector_validation
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_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)?;
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::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(()),
}
}
}
| crates/router/src/core/connector_validation.rs | router::src::core::connector_validation | 6,077 | true |
// File: crates/router/src/core/verification.rs
// Module: router::src::core::verification
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_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&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(
key_manager_state,
&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(
key_manager_state,
&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 },
))
}
| crates/router/src/core/verification.rs | router::src::core::verification | 1,020 | true |
// File: crates/router/src/core/payments.rs
// Module: router::src::core::payments
pub mod access_token;
pub mod conditional_configs;
pub mod customers;
pub mod flows;
pub mod helpers;
pub mod operations;
#[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,
};
#[cfg(feature = "v2")]
use external_services::grpc_client;
#[cfg(feature = "v2")]
pub mod payment_methods;
use std::future;
#[cfg(feature = "olap")]
use api_models::admin::MerchantConnectorInfo;
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::{ephemeral_key, 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,
};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::router_response_types::RedirectForm;
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::{
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;
use time;
#[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},
operations::{BoxedOperation, Operation, PaymentResponse},
routing::{self as self_routing, SessionFlowRoutingInput},
};
use super::{
errors::StorageErrorExt, payment_methods::surcharge_decision_configs, routing::TransactionData,
unified_connector_service::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 = "v1")]
use crate::core::payments::helpers::{
process_through_direct, process_through_direct_with_shadow_unified_connector_service,
process_through_ucs,
};
#[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,
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,
merchant_context: domain::MerchantContext,
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, &merchant_context, profile, &mut payment_data)
.await?;
let (_operation, customer) = operation
.to_domain()?
.get_customer_details(
state,
&mut payment_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(&merchant_context, 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(),
&merchant_context,
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(),
&merchant_context,
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,
&merchant_context,
&mut payment_data,
profile,
)
.await?;
let payment_data = payments_response_operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(),
&merchant_context,
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(),
&merchant_context,
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,
&merchant_context,
&mut payment_data,
profile,
)
.await?;
let payment_data = payments_response_operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
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,
&merchant_context,
profile,
&connector_data,
)
.await?;
let router_data = connector_service_decider(
state,
req_state.clone(),
&merchant_context,
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,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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,
merchant_context: &domain::MerchantContext,
profile_id_from_auth_layer: Option<id_type::ProfileId>,
operation: Op,
req: Req,
call_connector_action: CallConnectorAction,
auth_flow: services::AuthFlow,
eligible_connectors: Option<Vec<common_enums::RoutableConnectors>>,
header_payload: HeaderPayload,
) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync + '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",
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
);
let (operation, validate_result) = operation
.to_validate_request()?
.validate_request(&req, merchant_context)?;
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,
merchant_context,
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(),
)?;
let (operation, customer) = operation
.to_domain()?
// get_customer_details
.get_or_create_customer_details(
state,
&mut payment_data,
customer_details,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
let authentication_type =
call_decision_manager(state, merchant_context, &business_profile, &payment_data).await?;
payment_data.set_authentication_type_in_attempt(authentication_type);
let connector = get_connector_choice(
&operation,
state,
&req,
merchant_context,
&business_profile,
&mut payment_data,
eligible_connectors,
mandate_type,
)
.await?;
let payment_method_token = get_decrypted_wallet_payment_method_token(
&operation,
state,
merchant_context,
&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;
operation
.to_domain()?
.apply_three_ds_authentication_strategy(state, &mut payment_data, &business_profile)
.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,
merchant_context.get_merchant_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,
merchant_context,
&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(
merchant_context.get_merchant_account().get_id(),
state,
)
.await?;
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,
merchant_context.get_merchant_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,
merchant_context.get_merchant_key_store(),
mandate_type,
)
.await?;
};
operation
.to_domain()?
.payments_dynamic_tax_calculation(
state,
&mut payment_data,
&connector_details,
&business_profile,
merchant_context,
)
.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(),
merchant_context.get_merchant_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,
merchant_context,
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(),
merchant_context,
connector.connector_data.clone(),
&operation,
&mut payment_data,
&customer,
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,
merchant_context,
&mut payment_data,
&business_profile,
)
.await?;
let mut payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
&locale,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
routable_connectors,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
&business_profile,
)
.await?;
if should_trigger_post_processing_flows {
complete_postprocessing_steps_if_required(
state,
merchant_context,
&customer,
&mca,
&connector.connector_data,
&mut payment_data,
op_ref,
Some(header_payload.clone()),
)
.await?;
}
if is_eligible_for_uas {
complete_confirmation_for_click_to_pay_if_required(
state,
merchant_context,
&payment_data,
)
.await?;
}
payment_data
}
ConnectorCallType::Retryable(ref connectors) => {
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
let routable_connectors =
convert_connector_data_to_routable_connectors(connectors)
.map_err(|e| logger::error!(routable_connector_error=?e))
.unwrap_or_default();
let mut connectors = connectors.clone().into_iter();
let (connector_data, routing_decision) =
get_connector_data_with_routing_decision(
&mut connectors,
&business_profile,
debit_routing_output,
)?;
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector_data.connector.id(),
merchant_context.get_merchant_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,
merchant_context,
connector_data.clone(),
&operation,
&mut payment_data,
&customer,
&validate_result,
&business_profile,
false,
routing_decision,
)
.await?;
let (router_data, mca) = decide_unified_connector_service_call(
state,
req_state.clone(),
merchant_context,
connector_data.clone(),
&operation,
&mut payment_data,
&customer,
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?;
#[cfg(all(feature = "retry", feature = "v1"))]
let mut router_data = router_data;
#[cfg(all(feature = "retry", feature = "v1"))]
{
use crate::core::payments::retry::{self, GsmValidation};
let config_bool = retry::config_should_call_gsm(
&*state.store,
merchant_context.get_merchant_account().get_id(),
&business_profile,
)
.await;
if config_bool && router_data.should_call_gsm() {
router_data = retry::do_gsm_actions(
state,
req_state.clone(),
&mut payment_data,
connectors,
&connector_data,
router_data,
merchant_context,
&operation,
&customer,
&validate_result,
schedule_time,
#[cfg(feature = "frm")]
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
&business_profile,
)
.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,
merchant_context,
&mut payment_data,
&business_profile,
)
.await?;
let mut payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
&locale,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
routable_connectors,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
&business_profile,
)
.await?;
if should_trigger_post_processing_flows {
complete_postprocessing_steps_if_required(
state,
merchant_context,
&customer,
&mca,
&connector_data,
&mut payment_data,
op_ref,
Some(header_payload.clone()),
)
.await?;
}
if is_eligible_for_uas {
complete_confirmation_for_click_to_pay_if_required(
state,
merchant_context,
&payment_data,
)
.await?;
}
payment_data
}
ConnectorCallType::SessionMultiple(connectors) => {
let session_surcharge_details =
call_surcharge_decision_management_for_session_flow(
state,
merchant_context,
&business_profile,
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_billing_address(),
&connectors,
)
.await?;
Box::pin(call_multiple_connectors_service(
state,
merchant_context,
connectors,
&operation,
payment_data,
&customer,
session_surcharge_details,
&business_profile,
header_payload.clone(),
<Req as Authenticate>::should_return_raw_response(&req),
))
.await?
}
};
#[cfg(feature = "frm")]
if let Some(fraud_info) = &mut frm_info {
#[cfg(feature = "v1")]
Box::pin(frm_core::post_payment_frm_core(
state,
req_state,
merchant_context,
&mut payment_data,
fraud_info,
frm_configs
.clone()
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "frm_configs",
})
.attach_printable("Frm configs label not found")?,
&customer,
&mut should_continue_capture,
))
.await?;
}
} else {
(_, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
validate_result.storage_scheme,
None,
merchant_context.get_merchant_key_store(),
#[cfg(feature = "frm")]
frm_info.and_then(|info| info.suggested_action),
#[cfg(not(feature = "frm"))]
None,
header_payload.clone(),
)
.await?;
}
let payment_intent_status = payment_data.get_payment_intent().status;
payment_data
.get_payment_attempt()
.payment_token
.as_ref()
.zip(payment_data.get_payment_attempt().payment_method)
.map(ParentPaymentMethodToken::create_key_for_token)
.async_map(|key_for_hyperswitch_token| async move {
if key_for_hyperswitch_token
.should_delete_payment_method_token(payment_intent_status)
{
let _ = key_for_hyperswitch_token.delete(state).await;
}
})
.await;
} else {
(_, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
validate_result.storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload.clone(),
)
.await?;
}
let cloned_payment_data = payment_data.clone();
let cloned_customer = customer.clone();
#[cfg(feature = "v1")]
operation
.to_domain()?
.store_extended_card_info_temporarily(
state,
payment_data.get_payment_intent().get_id(),
&business_profile,
payment_data.get_payment_method_data(),
)
.await?;
utils::trigger_payments_webhook(
merchant_context.clone(),
business_profile,
cloned_payment_data,
cloned_customer,
state,
operation,
)
.await
.map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))
.ok();
Ok((
payment_data,
req,
customer,
connector_http_status_code,
external_latency,
))
}
#[cfg(feature = "v1")]
// This function is intended for use when the feature being implemented is not aligned with the
// core payment operations.
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile_id_from_auth_layer: Option<id_type::ProfileId>,
operation: Op,
req: Req,
call_connector_action: CallConnectorAction,
auth_flow: services::AuthFlow,
header_payload: HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<(D, Req, Option<domain::Customer>, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync,
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>
+ Send
+ Sync,
// 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);
tracing::Span::current().record(
"merchant_id",
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
);
let (operation, validate_result) = operation
.to_validate_request()?
.validate_request(&req, &merchant_context)?;
tracing::Span::current().record("payment_id", format!("{}", validate_result.payment_id));
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,
&merchant_context,
auth_flow,
&header_payload,
)
.await?;
core_utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&payment_data.get_payment_intent().clone(),
)?;
common_utils::fp_utils::when(!should_call_connector(&operation, &payment_data), || {
Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration).attach_printable(format!(
"Nti and card details based mit flow is not support for this {operation:?} payment operation"
))
})?;
let connector_choice = operation
.to_domain()?
.get_connector(
&merchant_context,
&state.clone(),
&req,
payment_data.get_payment_intent(),
)
.await?;
let connector = set_eligible_connector_for_nti_in_payment_data(
state,
&business_profile,
merchant_context.get_merchant_key_store(),
&mut payment_data,
connector_choice,
)
.await?;
let should_add_task_to_process_tracker = should_add_task_to_process_tracker(&payment_data);
let locale = header_payload.locale.clone();
let schedule_time = if should_add_task_to_process_tracker {
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector.connector.id(),
merchant_context.get_merchant_account().get_id(),
0,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting process schedule time")?
} else {
None
};
let (operation, customer) = operation
.to_domain()?
.get_or_create_customer_details(
state,
&mut payment_data,
customer_details,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
let (router_data, mca) = proxy_for_call_connector_service(
state,
req_state.clone(),
&merchant_context,
connector.clone(),
&operation,
&mut payment_data,
&customer,
call_connector_action.clone(),
&validate_result,
schedule_time,
header_payload.clone(),
&business_profile,
return_raw_connector_response,
)
.await?;
let op_ref = &operation;
let should_trigger_post_processing_flows = is_operation_confirm(&operation);
let operation = Box::new(PaymentResponse);
let connector_http_status_code = router_data.connector_http_status_code;
let external_latency = router_data.external_latency;
add_connector_http_status_code_metrics(connector_http_status_code);
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
let routable_connectors =
convert_connector_data_to_routable_connectors(&[connector.clone().into()])
.map_err(|e| logger::error!(routable_connector_error=?e))
.unwrap_or_default();
let mut payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
&locale,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
routable_connectors,
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
&business_profile,
)
.await?;
if should_trigger_post_processing_flows {
complete_postprocessing_steps_if_required(
state,
&merchant_context,
&None,
&mca,
&connector,
&mut payment_data,
op_ref,
Some(header_payload.clone()),
)
.await?;
}
let cloned_payment_data = payment_data.clone();
utils::trigger_payments_webhook(
merchant_context.clone(),
business_profile,
cloned_payment_data,
None,
state,
operation,
)
.await
.map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))
.ok();
Ok((
payment_data,
req,
None,
connector_http_status_code,
external_latency,
))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
get_tracker_response: operations::GetTrackerResponse<D>,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<(D, Req, Option<u16>, Option<u128>)>
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;
// consume the req merchant_connector_id and set it in the payment_data
let connector = operation
.to_domain()?
.perform_routing(&merchant_context, &profile, state, &mut payment_data)
.await?;
let payment_data = match connector {
ConnectorCallType::PreDetermined(connector_data) => {
let router_data = proxy_for_call_connector_service(
state,
req_state.clone(),
&merchant_context,
connector_data.connector_data.clone(),
&operation,
&mut payment_data,
call_connector_action.clone(),
header_payload.clone(),
&profile,
return_raw_connector_response,
)
.await?;
let payments_response_operation = Box::new(PaymentResponse);
payments_response_operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?
}
ConnectorCallType::Retryable(vec) => todo!(),
ConnectorCallType::SessionMultiple(vec) => todo!(),
ConnectorCallType::Skip => payment_data,
};
Ok((payment_data, req, None, None))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn external_vault_proxy_for_payments_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
get_tracker_response: operations::GetTrackerResponse<D>,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<(D, Req, Option<u16>, Option<u128>)>
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;
let (_operation, customer) = operation
.to_domain()?
.get_customer_details(
state,
&mut payment_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
operation
.to_domain()?
.create_or_fetch_payment_method(state, &merchant_context, &profile, &mut payment_data)
.await?;
// consume the req merchant_connector_id and set it in the payment_data
let connector = operation
.to_domain()?
.perform_routing(&merchant_context, &profile, state, &mut payment_data)
.await?;
let payment_data = match connector {
ConnectorCallType::PreDetermined(connector_data) => {
let (mca_type_details, external_vault_mca_type_details, updated_customer, router_data) =
call_connector_service_prerequisites_for_external_vault_proxy(
state,
req_state.clone(),
&merchant_context,
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 = call_unified_connector_service_for_external_proxy(
state,
req_state.clone(),
&merchant_context,
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,
external_vault_mca_type_details,
router_data,
updated_customer,
)
.await?;
// update payment method if its a successful transaction
if router_data.status.is_success() {
operation
.to_domain()?
.update_payment_method(state, &merchant_context, &mut payment_data)
.await;
}
let payments_response_operation = Box::new(PaymentResponse);
payments_response_operation
.to_post_update_tracker()?
.update_tracker(
state,
payment_data,
router_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?
}
ConnectorCallType::Retryable(_) => todo!(),
ConnectorCallType::SessionMultiple(_) => todo!(),
ConnectorCallType::Skip => payment_data,
};
Ok((payment_data, req, None, None))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn payments_intent_operation_core<F, Req, Op, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
header_payload: HeaderPayload,
) -> RouterResult<(D, Req, Option<domain::Customer>)>
where
F: Send + Clone + Sync,
Req: Clone,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
tracing::Span::current().record(
"merchant_id",
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
);
let _validate_result = operation
.to_validate_request()?
.validate_request(&req, &merchant_context)?;
tracing::Span::current().record("global_payment_id", payment_id.get_string_repr());
let operations::GetTrackerResponse { mut payment_data } = operation
.to_get_tracker()?
.get_trackers(
state,
&payment_id,
&req,
&merchant_context,
&profile,
&header_payload,
)
.await?;
let (_operation, customer) = operation
.to_domain()?
.get_customer_details(
state,
&mut payment_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
let (_operation, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data,
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload,
)
.await?;
Ok((payment_data, req, customer))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn payments_attempt_operation_core<F, Req, Op, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
header_payload: HeaderPayload,
) -> RouterResult<(D, Req, Option<domain::Customer>)>
where
F: Send + Clone + Sync,
Req: Clone,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
let operation: BoxedOperation<'_, F, Req, D> = Box::new(operation);
tracing::Span::current().record(
"merchant_id",
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
);
let _validate_result = operation
.to_validate_request()?
.validate_request(&req, &merchant_context)?;
tracing::Span::current().record("global_payment_id", payment_id.get_string_repr());
let operations::GetTrackerResponse { mut payment_data } = operation
.to_get_tracker()?
.get_trackers(
state,
&payment_id,
&req,
&merchant_context,
&profile,
&header_payload,
)
.await?;
let (_operation, customer) = operation
.to_domain()?
.get_customer_details(
state,
&mut payment_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
let (_operation, payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data,
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload,
)
.await?;
Ok((payment_data, req, customer))
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
pub async fn call_decision_manager<F, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
payment_data: &D,
) -> RouterResult<Option<enums::AuthenticationType>>
where
F: Clone,
D: OperationSessionGetters<F>,
{
let setup_mandate = payment_data.get_setup_mandate();
let payment_method_data = payment_data.get_payment_method_data();
let payment_dsl_data = core_routing::PaymentsDslInput::new(
setup_mandate,
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_method_data,
payment_data.get_address(),
payment_data.get_recurring_details(),
payment_data.get_currency(),
);
let algorithm_ref: api::routing::RoutingAlgorithmRef = merchant_context
.get_merchant_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 output = perform_decision_management(
state,
algorithm_ref,
merchant_context.get_merchant_account().get_id(),
&payment_dsl_data,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the conditional config")?;
Ok(payment_dsl_data
.payment_attempt
.authentication_type
.or(output.override_3ds))
}
// TODO: Move to business profile surcharge column
#[instrument(skip_all)]
#[cfg(feature = "v2")]
pub fn call_decision_manager<F>(
state: &SessionState,
record: common_types::payments::DecisionManagerRecord,
payment_data: &PaymentConfirmData<F>,
) -> RouterResult<Option<enums::AuthenticationType>>
where
F: Clone,
{
let payment_method_data = payment_data.get_payment_method_data();
let payment_dsl_data = core_routing::PaymentsDslInput::new(
None,
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_method_data,
payment_data.get_address(),
None,
payment_data.get_currency(),
);
let output = perform_decision_management(record, &payment_dsl_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode the conditional config")?;
Ok(output.override_3ds)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn populate_surcharge_details<F>(
state: &SessionState,
payment_data: &mut PaymentData<F>,
) -> RouterResult<()>
where
F: Send + Clone,
{
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn populate_surcharge_details<F>(
state: &SessionState,
payment_data: &mut PaymentData<F>,
) -> RouterResult<()>
where
F: Send + Clone,
{
if payment_data
.payment_intent
.surcharge_applicable
.unwrap_or(false)
{
logger::debug!("payment_intent.surcharge_applicable = true");
if let Some(surcharge_details) = payment_data.payment_attempt.get_surcharge_details() {
// if retry payment, surcharge would have been populated from the previous attempt. Use the same surcharge
let surcharge_details =
types::SurchargeDetails::from((&surcharge_details, &payment_data.payment_attempt));
payment_data.surcharge_details = Some(surcharge_details);
return Ok(());
}
let raw_card_key = payment_data
.payment_method_data
.as_ref()
.and_then(helpers::get_key_params_for_surcharge_details)
.map(|(payment_method, payment_method_type, card_network)| {
types::SurchargeKey::PaymentMethodData(
payment_method,
payment_method_type,
card_network,
)
});
let saved_card_key = payment_data.token.clone().map(types::SurchargeKey::Token);
let surcharge_key = raw_card_key
.or(saved_card_key)
.get_required_value("payment_method_data or payment_token")?;
logger::debug!(surcharge_key_confirm =? surcharge_key);
let calculated_surcharge_details =
match types::SurchargeMetadata::get_individual_surcharge_detail_from_redis(
state,
surcharge_key,
&payment_data.payment_attempt.attempt_id,
)
.await
{
Ok(surcharge_details) => Some(surcharge_details),
Err(err) if err.current_context() == &RedisError::NotFound => None,
Err(err) => {
Err(err).change_context(errors::ApiErrorResponse::InternalServerError)?
}
};
payment_data.surcharge_details = calculated_surcharge_details.clone();
//Update payment_attempt net_amount with surcharge details
payment_data
.payment_attempt
.net_amount
.set_surcharge_details(calculated_surcharge_details);
} else {
let surcharge_details =
payment_data
.payment_attempt
.get_surcharge_details()
.map(|surcharge_details| {
logger::debug!("surcharge sent in payments create request");
types::SurchargeDetails::from((
&surcharge_details,
&payment_data.payment_attempt,
))
});
payment_data.surcharge_details = surcharge_details;
}
Ok(())
}
#[inline]
pub fn get_connector_data(
connectors: &mut IntoIter<api::ConnectorRoutingData>,
) -> RouterResult<api::ConnectorRoutingData> {
connectors
.next()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector not found in connectors iterator")
}
#[cfg(feature = "v1")]
pub fn get_connector_with_networks(
connectors: &mut IntoIter<api::ConnectorRoutingData>,
) -> Option<(api::ConnectorData, enums::CardNetwork)> {
connectors.find_map(|connector| {
connector
.network
.map(|network| (connector.connector_data, network))
})
}
#[cfg(feature = "v1")]
fn get_connector_data_with_routing_decision(
connectors: &mut IntoIter<api::ConnectorRoutingData>,
business_profile: &domain::Profile,
debit_routing_output_optional: Option<api_models::open_router::DebitRoutingOutput>,
) -> RouterResult<(
api::ConnectorData,
Option<routing_helpers::RoutingDecisionData>,
)> {
if business_profile.is_debit_routing_enabled && debit_routing_output_optional.is_some() {
if let Some((data, card_network)) = get_connector_with_networks(connectors) {
let debit_routing_output =
debit_routing_output_optional.get_required_value("debit routing output")?;
let routing_decision =
routing_helpers::RoutingDecisionData::get_debit_routing_decision_data(
card_network,
Some(debit_routing_output),
);
return Ok((data, Some(routing_decision)));
}
}
Ok((get_connector_data(connectors)?.connector_data, None))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn call_surcharge_decision_management_for_session_flow(
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_attempt: &storage::PaymentAttempt,
_payment_intent: &storage::PaymentIntent,
_billing_address: Option<hyperswitch_domain_models::address::Address>,
_session_connector_data: &[api::SessionConnectorData],
) -> RouterResult<Option<api::SessionSurchargeDetails>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn call_surcharge_decision_management_for_session_flow(
state: &SessionState,
merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
billing_address: Option<hyperswitch_domain_models::address::Address>,
session_connector_data: &api::SessionConnectorDatas,
) -> RouterResult<Option<api::SessionSurchargeDetails>> {
if let Some(surcharge_amount) = payment_attempt.net_amount.get_surcharge_amount() {
Ok(Some(api::SessionSurchargeDetails::PreDetermined(
types::SurchargeDetails {
original_amount: payment_attempt.net_amount.get_order_amount(),
surcharge: Surcharge::Fixed(surcharge_amount),
tax_on_surcharge: None,
surcharge_amount,
tax_on_surcharge_amount: payment_attempt
.net_amount
.get_tax_on_surcharge()
.unwrap_or_default(),
},
)))
} else {
let payment_method_type_list = session_connector_data
.iter()
.map(|session_connector_data| session_connector_data.payment_method_sub_type)
.collect();
#[cfg(feature = "v1")]
let algorithm_ref: api::routing::RoutingAlgorithmRef = merchant_context
.get_merchant_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();
// TODO: Move to business profile surcharge column
#[cfg(feature = "v2")]
let algorithm_ref: api::routing::RoutingAlgorithmRef = todo!();
let surcharge_results =
surcharge_decision_configs::perform_surcharge_decision_management_for_session_flow(
state,
algorithm_ref,
payment_attempt,
payment_intent,
billing_address,
&payment_method_type_list,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing surcharge decision operation")?;
Ok(if surcharge_results.is_empty_result() {
None
} else {
Some(api::SessionSurchargeDetails::Calculated(surcharge_results))
})
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_core<F, Res, Req, Op, FData, D>(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile_id: Option<id_type::ProfileId>,
operation: Op,
req: Req,
auth_flow: services::AuthFlow,
call_connector_action: CallConnectorAction,
eligible_connectors: Option<Vec<enums::Connector>>,
header_payload: HeaderPayload,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync + 'static,
FData: Send + Sync + Clone + router_types::Capturable + 'static + serde::Serialize,
Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
Req: Debug + Authenticate + Clone,
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>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
{
let eligible_routable_connectors = eligible_connectors.map(|connectors| {
connectors
.into_iter()
.flat_map(|c| c.foreign_try_into())
.collect()
});
let (payment_data, _req, customer, connector_http_status_code, external_latency) =
payments_operation_core::<_, _, _, _, _>(
&state,
req_state,
&merchant_context,
profile_id,
operation.clone(),
req,
call_connector_action,
auth_flow,
eligible_routable_connectors,
header_payload.clone(),
)
.await?;
Res::generate_response(
payment_data,
customer,
auth_flow,
&state.base_url,
operation,
&state.conf.connector_request_reference_id_config,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
)
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile_id: Option<id_type::ProfileId>,
operation: Op,
req: Req,
auth_flow: services::AuthFlow,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
FData: Send + Sync + Clone,
Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
Req: Debug + Authenticate + Clone,
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>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
{
let (payment_data, _req, customer, connector_http_status_code, external_latency) =
proxy_for_payments_operation_core::<_, _, _, _, _>(
&state,
req_state,
merchant_context,
profile_id,
operation.clone(),
req,
call_connector_action,
auth_flow,
header_payload.clone(),
return_raw_connector_response,
)
.await?;
Res::generate_response(
payment_data,
customer,
auth_flow,
&state.base_url,
operation,
&state.conf.connector_request_reference_id_config,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn proxy_for_payments_core<F, Res, Req, Op, FData, D>(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
Req: Send + Sync + Authenticate,
FData: Send + Sync + Clone,
Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone,
Req: Debug,
D: OperationSessionGetters<F>
+ OperationSessionSetters<F>
+ transformers::GenerateResponse<Res>
+ Send
+ Sync
+ Clone,
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
PaymentResponse: Operation<F, FData, Data = D>,
RouterData<F, FData, router_types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>,
{
operation
.to_validate_request()?
.validate_request(&req, &merchant_context)?;
let get_tracker_response = operation
.to_get_tracker()?
.get_trackers(
&state,
&payment_id,
&req,
&merchant_context,
&profile,
&header_payload,
)
.await?;
let (payment_data, _req, connector_http_status_code, external_latency) =
proxy_for_payments_operation_core::<_, _, _, _, _>(
&state,
req_state,
merchant_context.clone(),
profile.clone(),
operation.clone(),
req,
get_tracker_response,
call_connector_action,
header_payload.clone(),
return_raw_connector_response,
)
.await?;
payment_data.generate_response(
&state,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&merchant_context,
&profile,
None,
)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn external_vault_proxy_for_payments_core<F, Res, Req, Op, FData, D>(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
Req: Send + Sync + Authenticate,
FData: Send + Sync + Clone,
Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone,
Req: Debug,
D: OperationSessionGetters<F>
+ OperationSessionSetters<F>
+ transformers::GenerateResponse<Res>
+ Send
+ Sync
+ Clone,
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
PaymentResponse: Operation<F, FData, Data = D>,
RouterData<F, FData, router_types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>,
{
operation
.to_validate_request()?
.validate_request(&req, &merchant_context)?;
let get_tracker_response = operation
.to_get_tracker()?
.get_trackers(
&state,
&payment_id,
&req,
&merchant_context,
&profile,
&header_payload,
)
.await?;
let (payment_data, _req, connector_http_status_code, external_latency) =
external_vault_proxy_for_payments_operation_core::<_, _, _, _, _>(
&state,
req_state,
merchant_context.clone(),
profile.clone(),
operation.clone(),
req,
get_tracker_response,
call_connector_action,
header_payload.clone(),
return_raw_connector_response,
)
.await?;
payment_data.generate_response(
&state,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&merchant_context,
&profile,
None,
)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn record_attempt_core(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
req: api_models::payments::PaymentsAttemptRecordRequest,
payment_id: id_type::GlobalPaymentId,
header_payload: HeaderPayload,
) -> RouterResponse<api_models::payments::PaymentAttemptRecordResponse> {
tracing::Span::current().record(
"merchant_id",
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
);
let operation: &operations::payment_attempt_record::PaymentAttemptRecord =
&operations::payment_attempt_record::PaymentAttemptRecord;
let boxed_operation: BoxedOperation<
'_,
api::RecordAttempt,
api_models::payments::PaymentsAttemptRecordRequest,
domain_payments::PaymentAttemptRecordData<api::RecordAttempt>,
> = Box::new(operation);
let _validate_result = boxed_operation
.to_validate_request()?
.validate_request(&req, &merchant_context)?;
tracing::Span::current().record("global_payment_id", payment_id.get_string_repr());
let operations::GetTrackerResponse { payment_data } = boxed_operation
.to_get_tracker()?
.get_trackers(
&state,
&payment_id,
&req,
&merchant_context,
&profile,
&header_payload,
)
.await?;
let default_payment_status_data = PaymentStatusData {
flow: PhantomData,
payment_intent: payment_data.payment_intent.clone(),
payment_attempt: payment_data.payment_attempt.clone(),
attempts: None,
should_sync_with_connector: false,
payment_address: payment_data.payment_address.clone(),
merchant_connector_details: None,
};
let payment_status_data = (req.triggered_by == common_enums::TriggeredBy::Internal)
.then(|| default_payment_status_data.clone())
.async_unwrap_or_else(|| async {
match Box::pin(proxy_for_payments_operation_core::<
api::PSync,
_,
_,
_,
PaymentStatusData<api::PSync>,
>(
&state,
req_state.clone(),
merchant_context.clone(),
profile.clone(),
operations::PaymentGet,
api::PaymentsRetrieveRequest {
force_sync: true,
expand_attempts: false,
param: None,
return_raw_connector_response: None,
merchant_connector_details: None,
},
operations::GetTrackerResponse {
payment_data: PaymentStatusData {
flow: PhantomData,
payment_intent: payment_data.payment_intent.clone(),
payment_attempt: payment_data.payment_attempt.clone(),
attempts: None,
should_sync_with_connector: true,
payment_address: payment_data.payment_address.clone(),
merchant_connector_details: None,
},
},
CallConnectorAction::Trigger,
HeaderPayload::default(),
None,
))
.await
{
Ok((data, _, _, _)) => data,
Err(err) => {
router_env::logger::error!(error=?err, "proxy_for_payments_operation_core failed for external payment attempt");
default_payment_status_data
}
}
})
.await;
let record_payment_data = domain_payments::PaymentAttemptRecordData {
flow: PhantomData,
payment_intent: payment_status_data.payment_intent,
payment_attempt: payment_status_data.payment_attempt,
revenue_recovery_data: payment_data.revenue_recovery_data.clone(),
payment_address: payment_data.payment_address.clone(),
};
let (_operation, final_payment_data) = boxed_operation
.to_update_tracker()?
.update_trackers(
&state,
req_state,
record_payment_data,
None,
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload.clone(),
)
.await?;
transformers::GenerateResponse::generate_response(
final_payment_data,
&state,
None,
None,
header_payload.x_hs_latency,
&merchant_context,
&profile,
None,
)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_intent_core<F, Res, Req, Op, D>(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
header_payload: HeaderPayload,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
Req: Debug + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
Res: transformers::ToResponse<F, D, Op>,
{
let (payment_data, _req, customer) = payments_intent_operation_core::<_, _, _, _>(
&state,
req_state,
merchant_context.clone(),
profile,
operation.clone(),
req,
payment_id,
header_payload.clone(),
)
.await?;
Res::generate_response(
payment_data,
customer,
&state.base_url,
operation,
&state.conf.connector_request_reference_id_config,
None,
None,
header_payload.x_hs_latency,
&merchant_context,
)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_list_attempts_using_payment_intent_id<F, Res, Req, Op, D>(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
operation: Op,
req: Req,
payment_id: id_type::GlobalPaymentId,
header_payload: HeaderPayload,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
Op: Operation<F, Req, Data = D> + Send + Sync + Clone,
Req: Debug + Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
Res: transformers::ToResponse<F, D, Op>,
{
let (payment_data, _req, customer) = payments_attempt_operation_core::<_, _, _, _>(
&state,
req_state,
merchant_context.clone(),
profile,
operation.clone(),
req,
payment_id,
header_payload.clone(),
)
.await?;
Res::generate_response(
payment_data,
customer,
&state.base_url,
operation,
&state.conf.connector_request_reference_id_config,
None,
None,
header_payload.x_hs_latency,
&merchant_context,
)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_get_intent_using_merchant_reference(
state: SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
req_state: ReqState,
merchant_reference_id: &id_type::PaymentReferenceId,
header_payload: HeaderPayload,
) -> RouterResponse<api::PaymentsIntentResponse> {
let db = state.store.as_ref();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let key_manager_state = &(&state).into();
let payment_intent = db
.find_payment_intent_by_merchant_reference_id_profile_id(
key_manager_state,
merchant_reference_id,
profile.get_id(),
merchant_context.get_merchant_key_store(),
&storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let (payment_data, _req, customer) = Box::pin(payments_intent_operation_core::<
api::PaymentGetIntent,
_,
_,
PaymentIntentData<api::PaymentGetIntent>,
>(
&state,
req_state,
merchant_context.clone(),
profile.clone(),
operations::PaymentGetIntent,
api_models::payments::PaymentsGetIntentRequest {
id: payment_intent.get_id().clone(),
},
payment_intent.get_id().clone(),
header_payload.clone(),
))
.await?;
transformers::ToResponse::<
api::PaymentGetIntent,
PaymentIntentData<api::PaymentGetIntent>,
operations::PaymentGetIntent,
>::generate_response(
payment_data,
customer,
&state.base_url,
operations::PaymentGetIntent,
&state.conf.connector_request_reference_id_config,
None,
None,
header_payload.x_hs_latency,
&merchant_context,
)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_core<F, Res, Req, Op, FData, D>(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
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 + Authenticate,
FData: Send + Sync + Clone + serde::Serialize,
Op: Operation<F, Req, Data = D> + ValidateStatusForOperation + Send + Sync + Clone,
Req: Debug,
D: OperationSessionGetters<F>
+ OperationSessionSetters<F>
+ transformers::GenerateResponse<Res>
+ 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>,
// To create updatable objects in post update tracker
RouterData<F, FData, router_types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>,
{
// Validate the request fields
operation
.to_validate_request()?
.validate_request(&req, &merchant_context)?;
// Get the tracker related information. This includes payment intent and payment attempt
let get_tracker_response = operation
.to_get_tracker()?
.get_trackers(
&state,
&payment_id,
&req,
&merchant_context,
&profile,
&header_payload,
)
.await?;
let (payment_data, connector_http_status_code, external_latency, connector_response_data) =
if state.conf.merchant_id_auth.merchant_id_auth_enabled {
let (
payment_data,
_req,
connector_http_status_code,
external_latency,
connector_response_data,
) = internal_payments_operation_core::<_, _, _, _, _>(
&state,
req_state,
merchant_context.clone(),
&profile,
operation.clone(),
req,
get_tracker_response,
call_connector_action,
header_payload.clone(),
)
.await?;
(
payment_data,
connector_http_status_code,
external_latency,
connector_response_data,
)
} else {
let (
payment_data,
_req,
_customer,
connector_http_status_code,
external_latency,
connector_response_data,
) = payments_operation_core::<_, _, _, _, _>(
&state,
req_state,
merchant_context.clone(),
&profile,
operation.clone(),
req,
get_tracker_response,
call_connector_action,
header_payload.clone(),
)
.await?;
(
payment_data,
connector_http_status_code,
external_latency,
connector_response_data,
)
};
payment_data.generate_response(
&state,
connector_http_status_code,
external_latency,
header_payload.x_hs_latency,
&merchant_context,
&profile,
Some(connector_response_data),
)
}
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "v2")]
pub(crate) async fn payments_create_and_confirm_intent(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
request: payments_api::PaymentsRequest,
header_payload: HeaderPayload,
) -> RouterResponse<payments_api::PaymentsResponse> {
use hyperswitch_domain_models::{
payments::PaymentIntentData, router_flow_types::PaymentCreateIntent,
};
let payment_id = id_type::GlobalPaymentId::generate(&state.conf.cell_information.id);
let payload = payments_api::PaymentsCreateIntentRequest::from(&request);
let create_intent_response = Box::pin(payments_intent_core::<
PaymentCreateIntent,
payments_api::PaymentsIntentResponse,
_,
_,
PaymentIntentData<PaymentCreateIntent>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
operations::PaymentIntentCreate,
payload,
payment_id.clone(),
header_payload.clone(),
))
.await?;
logger::info!(?create_intent_response);
let create_intent_response = create_intent_response
.get_json_body()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response from payments core")?;
let payload = payments_api::PaymentsConfirmIntentRequest::from(&request);
let confirm_intent_response = decide_authorize_or_setup_intent_flow(
state,
req_state,
merchant_context,
profile,
&create_intent_response,
payload,
payment_id,
header_payload,
)
.await?;
logger::info!(?confirm_intent_response);
Ok(confirm_intent_response)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn decide_authorize_or_setup_intent_flow(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
create_intent_response: &payments_api::PaymentsIntentResponse,
confirm_intent_request: payments_api::PaymentsConfirmIntentRequest,
payment_id: id_type::GlobalPaymentId,
header_payload: HeaderPayload,
) -> RouterResponse<payments_api::PaymentsResponse> {
use hyperswitch_domain_models::{
payments::PaymentConfirmData,
router_flow_types::{Authorize, SetupMandate},
};
if create_intent_response.amount_details.order_amount == MinorUnit::zero() {
Box::pin(payments_core::<
SetupMandate,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentConfirmData<SetupMandate>,
>(
state,
req_state,
merchant_context,
profile,
operations::PaymentIntentConfirm,
confirm_intent_request,
payment_id,
CallConnectorAction::Trigger,
header_payload,
))
.await
} else {
Box::pin(payments_core::<
Authorize,
api_models::payments::PaymentsResponse,
_,
_,
_,
PaymentConfirmData<Authorize>,
>(
state,
req_state,
merchant_context,
profile,
operations::PaymentIntentConfirm,
confirm_intent_request,
payment_id,
CallConnectorAction::Trigger,
header_payload,
))
.await
}
}
fn is_start_pay<Op: Debug>(operation: &Op) -> bool {
format!("{operation:?}").eq("PaymentStart")
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentsRedirectResponseData {
pub connector: Option<String>,
pub param: Option<String>,
pub merchant_id: Option<id_type::MerchantId>,
pub json_payload: Option<serde_json::Value>,
pub resource_id: api::PaymentIdType,
pub force_sync: bool,
pub creds_identifier: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct PaymentsRedirectResponseData {
pub payment_id: id_type::GlobalPaymentId,
pub query_params: String,
pub json_payload: Option<serde_json::Value>,
}
#[async_trait::async_trait]
pub trait PaymentRedirectFlow: Sync {
// Associated type for call_payment_flow response
type PaymentFlowResponse;
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn call_payment_flow(
&self,
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
req: PaymentsRedirectResponseData,
connector_action: CallConnectorAction,
connector: String,
payment_id: id_type::PaymentId,
) -> RouterResult<Self::PaymentFlowResponse>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn call_payment_flow(
&self,
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
req: PaymentsRedirectResponseData,
) -> RouterResult<Self::PaymentFlowResponse>;
fn get_payment_action(&self) -> services::PaymentAction;
#[cfg(feature = "v1")]
fn generate_response(
&self,
payment_flow_response: &Self::PaymentFlowResponse,
payment_id: id_type::PaymentId,
connector: String,
) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>>;
#[cfg(feature = "v2")]
fn generate_response(
&self,
payment_flow_response: &Self::PaymentFlowResponse,
) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>>;
#[cfg(feature = "v1")]
async fn handle_payments_redirect_response(
&self,
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
req: PaymentsRedirectResponseData,
) -> RouterResponse<api::RedirectionResponse> {
metrics::REDIRECTION_TRIGGERED.add(
1,
router_env::metric_attributes!(
(
"connector",
req.connector.to_owned().unwrap_or("null".to_string()),
),
(
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
),
),
);
let connector = req.connector.clone().get_required_value("connector")?;
let query_params = req.param.clone().get_required_value("param")?;
#[cfg(feature = "v1")]
let resource_id = api::PaymentIdTypeExt::get_payment_intent_id(&req.resource_id)
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_id",
})?;
#[cfg(feature = "v2")]
//TODO: Will get the global payment id from the resource id, we need to handle this in the further flow
let resource_id: id_type::PaymentId = todo!();
// This connector data is ephemeral, the call payment flow will get new connector data
// with merchant account details, so the connector_id can be safely set to None here
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector,
api::GetToken::Connector,
None,
)?;
let flow_type = connector_data
.connector
.get_flow_type(
&query_params,
req.json_payload.clone(),
self.get_payment_action(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decide the response flow")?;
let payment_flow_response = self
.call_payment_flow(
&state,
req_state,
merchant_context,
req.clone(),
flow_type,
connector.clone(),
resource_id.clone(),
)
.await?;
self.generate_response(&payment_flow_response, resource_id, connector)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn handle_payments_redirect_response(
&self,
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
request: PaymentsRedirectResponseData,
) -> RouterResponse<api::RedirectionResponse> {
metrics::REDIRECTION_TRIGGERED.add(
1,
router_env::metric_attributes!((
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
)),
);
let payment_flow_response = self
.call_payment_flow(&state, req_state, merchant_context, profile, request)
.await?;
self.generate_response(&payment_flow_response)
}
}
#[derive(Clone, Debug)]
pub struct PaymentRedirectCompleteAuthorize;
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse;
#[allow(clippy::too_many_arguments)]
async fn call_payment_flow(
&self,
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
req: PaymentsRedirectResponseData,
connector_action: CallConnectorAction,
_connector: String,
_payment_id: id_type::PaymentId,
) -> RouterResult<Self::PaymentFlowResponse> {
let key_manager_state = &state.into();
let payment_confirm_req = api::PaymentsRequest {
payment_id: Some(req.resource_id.clone()),
merchant_id: req.merchant_id.clone(),
merchant_connector_details: req.creds_identifier.map(|creds_id| {
api::MerchantConnectorDetailsWrap {
creds_identifier: creds_id,
encoded_data: None,
}
}),
feature_metadata: Some(api_models::payments::FeatureMetadata {
redirect_response: Some(api_models::payments::RedirectResponse {
param: req.param.map(Secret::new),
json_payload: Some(req.json_payload.unwrap_or(serde_json::json!({})).into()),
}),
search_tags: None,
apple_pay_recurring_details: None,
}),
..Default::default()
};
let response = Box::pin(payments_core::<
api::CompleteAuthorize,
api::PaymentsResponse,
_,
_,
_,
_,
>(
state.clone(),
req_state,
merchant_context.clone(),
None,
operations::payment_complete_authorize::CompleteAuthorize,
payment_confirm_req,
services::api::AuthFlow::Merchant,
connector_action,
None,
HeaderPayload::default(),
))
.await?;
let payments_response = match response {
services::ApplicationResponse::Json(response) => Ok(response),
services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response),
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the response in json"),
}?;
let profile_id = payments_response
.profile_id
.as_ref()
.get_required_value("profile_id")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(router_types::RedirectPaymentFlowResponse {
payments_response,
business_profile,
})
}
fn get_payment_action(&self) -> services::PaymentAction {
services::PaymentAction::CompleteAuthorize
}
fn generate_response(
&self,
payment_flow_response: &Self::PaymentFlowResponse,
payment_id: id_type::PaymentId,
connector: String,
) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> {
let payments_response = &payment_flow_response.payments_response;
// There might be multiple redirections needed for some flows
// If the status is requires customer action, then send the startpay url again
// The redirection data must have been provided and updated by the connector
let redirection_response = match payments_response.status {
enums::IntentStatus::RequiresCustomerAction => {
let startpay_url = payments_response
.next_action
.clone()
.and_then(|next_action_data| match next_action_data {
api_models::payments::NextActionData::RedirectToUrl { redirect_to_url } => Some(redirect_to_url),
api_models::payments::NextActionData::RedirectInsidePopup{popup_url, ..} => Some(popup_url),
api_models::payments::NextActionData::DisplayBankTransferInformation { .. } => None,
api_models::payments::NextActionData::ThirdPartySdkSessionToken { .. } => None,
api_models::payments::NextActionData::QrCodeInformation{..} => None,
api_models::payments::NextActionData::FetchQrCodeInformation{..} => None,
api_models::payments::NextActionData::DisplayVoucherInformation{ .. } => None,
api_models::payments::NextActionData::WaitScreenInformation{..} => None,
api_models::payments::NextActionData::ThreeDsInvoke{..} => None,
api_models::payments::NextActionData::InvokeSdkClient{..} => None,
api_models::payments::NextActionData::CollectOtp{ .. } => None,
api_models::payments::NextActionData::InvokeHiddenIframe{ .. } => None,
api_models::payments::NextActionData::SdkUpiIntentInformation{ .. } => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"did not receive redirect to url when status is requires customer action",
)?;
Ok(api::RedirectionResponse {
return_url: String::new(),
params: vec![],
return_url_with_query_params: startpay_url,
http_method: "GET".to_string(),
headers: vec![],
})
}
// If the status is terminal status, then redirect to merchant return url to provide status
enums::IntentStatus::Succeeded
| enums::IntentStatus::Failed
| enums::IntentStatus::Cancelled | enums::IntentStatus::RequiresCapture| enums::IntentStatus::Processing=> helpers::get_handle_response_url(
payment_id,
&payment_flow_response.business_profile,
payments_response,
connector,
),
_ => Err(errors::ApiErrorResponse::InternalServerError).attach_printable_lazy(|| format!("Could not proceed with payment as payment status {} cannot be handled during redirection",payments_response.status))?
}?;
if payments_response
.is_iframe_redirection_enabled
.unwrap_or(false)
{
// html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url
let html = core_utils::get_html_redirect_response_popup(
redirection_response.return_url_with_query_params,
)?;
Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
redirect_form: services::RedirectForm::Html { html_data: html },
payment_method_data: None,
amount: payments_response.amount.to_string(),
currency: payments_response.currency.clone(),
},
)))
} else {
Ok(services::ApplicationResponse::JsonForRedirection(
redirection_response,
))
}
}
}
#[derive(Clone, Debug)]
pub struct PaymentRedirectSync;
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl PaymentRedirectFlow for PaymentRedirectSync {
type PaymentFlowResponse = router_types::RedirectPaymentFlowResponse;
#[allow(clippy::too_many_arguments)]
async fn call_payment_flow(
&self,
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
req: PaymentsRedirectResponseData,
connector_action: CallConnectorAction,
_connector: String,
_payment_id: id_type::PaymentId,
) -> RouterResult<Self::PaymentFlowResponse> {
let key_manager_state = &state.into();
let payment_sync_req = api::PaymentsRetrieveRequest {
resource_id: req.resource_id,
merchant_id: req.merchant_id,
param: req.param,
force_sync: req.force_sync,
connector: req.connector,
merchant_connector_details: req.creds_identifier.map(|creds_id| {
api::MerchantConnectorDetailsWrap {
creds_identifier: creds_id,
encoded_data: None,
}
}),
client_secret: None,
expand_attempts: None,
expand_captures: None,
all_keys_required: None,
};
let response = Box::pin(
payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>(
state.clone(),
req_state,
merchant_context.clone(),
None,
PaymentStatus,
payment_sync_req,
services::api::AuthFlow::Merchant,
connector_action,
None,
HeaderPayload::default(),
),
)
.await?;
let payments_response = match response {
services::ApplicationResponse::Json(response) => Ok(response),
services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response),
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the response in json"),
}?;
let profile_id = payments_response
.profile_id
.as_ref()
.get_required_value("profile_id")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(router_types::RedirectPaymentFlowResponse {
payments_response,
business_profile,
})
}
fn generate_response(
&self,
payment_flow_response: &Self::PaymentFlowResponse,
payment_id: id_type::PaymentId,
connector: String,
) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> {
let payments_response = &payment_flow_response.payments_response;
let redirect_response = helpers::get_handle_response_url(
payment_id.clone(),
&payment_flow_response.business_profile,
payments_response,
connector.clone(),
)?;
if payments_response
.is_iframe_redirection_enabled
.unwrap_or(false)
{
// html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url
let html = core_utils::get_html_redirect_response_popup(
redirect_response.return_url_with_query_params,
)?;
Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
redirect_form: services::RedirectForm::Html { html_data: html },
payment_method_data: None,
amount: payments_response.amount.to_string(),
currency: payments_response.currency.clone(),
},
)))
} else {
Ok(services::ApplicationResponse::JsonForRedirection(
redirect_response,
))
}
}
fn get_payment_action(&self) -> services::PaymentAction {
services::PaymentAction::PSync
}
}
#[cfg(feature = "v2")]
impl ValidateStatusForOperation for &PaymentRedirectSync {
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
common_enums::IntentStatus::RequiresCustomerAction => 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::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: ["requires_customer_action".to_string()].join(", "),
})
}
}
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl PaymentRedirectFlow for PaymentRedirectSync {
type PaymentFlowResponse =
router_types::RedirectPaymentFlowResponse<PaymentStatusData<api::PSync>>;
async fn call_payment_flow(
&self,
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
req: PaymentsRedirectResponseData,
) -> RouterResult<Self::PaymentFlowResponse> {
let payment_id = req.payment_id.clone();
let payment_sync_request = api::PaymentsRetrieveRequest {
param: Some(req.query_params.clone()),
force_sync: true,
expand_attempts: false,
return_raw_connector_response: None,
merchant_connector_details: None, // TODO: Implement for connectors requiring 3DS or redirection-based authentication flows.
};
let operation = operations::PaymentGet;
let boxed_operation: BoxedOperation<
'_,
api::PSync,
api::PaymentsRetrieveRequest,
PaymentStatusData<api::PSync>,
> = Box::new(operation);
let get_tracker_response = boxed_operation
.to_get_tracker()?
.get_trackers(
state,
&payment_id,
&payment_sync_request,
&merchant_context,
&profile,
&HeaderPayload::default(),
)
.await?;
let payment_data = &get_tracker_response.payment_data;
self.validate_status_for_operation(payment_data.payment_intent.status)?;
let payment_attempt = payment_data.payment_attempt.clone();
let connector = payment_attempt
.connector
.as_ref()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"connector is not set in payment attempt in finish redirection flow",
)?;
// This connector data is ephemeral, the call payment flow will get new connector data
// with merchant account details, so the connector_id can be safely set to None here
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
None,
)?;
let call_connector_action = connector_data
.connector
.get_flow_type(
&req.query_params,
req.json_payload.clone(),
self.get_payment_action(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decide the response flow")?;
let (payment_data, _, _, _, _, _) =
Box::pin(payments_operation_core::<api::PSync, _, _, _, _>(
state,
req_state,
merchant_context,
&profile,
operation,
payment_sync_request,
get_tracker_response,
call_connector_action,
HeaderPayload::default(),
))
.await?;
Ok(router_types::RedirectPaymentFlowResponse {
payment_data,
profile,
})
}
fn generate_response(
&self,
payment_flow_response: &Self::PaymentFlowResponse,
) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> {
let payment_intent = &payment_flow_response.payment_data.payment_intent;
let profile = &payment_flow_response.profile;
let return_url = payment_intent
.return_url
.as_ref()
.or(profile.return_url.as_ref())
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("return url not found in payment intent and profile")?
.to_owned();
let return_url = return_url
.add_query_params(("id", payment_intent.id.get_string_repr()))
.add_query_params(("status", &payment_intent.status.to_string()));
let return_url_str = return_url.into_inner().to_string();
Ok(services::ApplicationResponse::JsonForRedirection(
api::RedirectionResponse {
return_url_with_query_params: return_url_str,
},
))
}
fn get_payment_action(&self) -> services::PaymentAction {
services::PaymentAction::PSync
}
}
#[derive(Clone, Debug)]
pub struct PaymentAuthenticateCompleteAuthorize;
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
type PaymentFlowResponse = router_types::AuthenticatePaymentFlowResponse;
#[allow(clippy::too_many_arguments)]
async fn call_payment_flow(
&self,
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
req: PaymentsRedirectResponseData,
connector_action: CallConnectorAction,
connector: String,
payment_id: id_type::PaymentId,
) -> RouterResult<Self::PaymentFlowResponse> {
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let key_manager_state = &state.into();
let payment_intent = state
.store
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
&merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = state
.store
.find_payment_attempt_by_attempt_id_merchant_id(
&payment_intent.active_attempt.get_id(),
&merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let authentication_id = payment_attempt
.authentication_id
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing authentication_id in payment_attempt")?;
let authentication = state
.store
.find_authentication_by_merchant_id_authentication_id(&merchant_id, &authentication_id)
.await
.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_string(),
})?;
// Fetching merchant_connector_account to check if pull_mechanism is enabled for 3ds connector
let authentication_merchant_connector_account = helpers::get_merchant_connector_account(
state,
&merchant_id,
None,
merchant_context.get_merchant_key_store(),
&payment_intent
.profile_id
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing profile_id in payment_intent")?,
&payment_attempt
.authentication_connector
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing authentication connector in payment_intent")?,
None,
)
.await?;
let is_pull_mechanism_enabled =
utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(
authentication_merchant_connector_account
.get_metadata()
.map(|metadata| metadata.expose()),
);
let response = if is_pull_mechanism_enabled
|| authentication.authentication_type
!= Some(common_enums::DecoupledAuthenticationType::Challenge)
{
let payment_confirm_req = api::PaymentsRequest {
payment_id: Some(req.resource_id.clone()),
merchant_id: req.merchant_id.clone(),
feature_metadata: Some(api_models::payments::FeatureMetadata {
redirect_response: Some(api_models::payments::RedirectResponse {
param: req.param.map(Secret::new),
json_payload: Some(
req.json_payload.unwrap_or(serde_json::json!({})).into(),
),
}),
search_tags: None,
apple_pay_recurring_details: None,
}),
..Default::default()
};
Box::pin(payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
_,
>(
state.clone(),
req_state,
merchant_context.clone(),
None,
PaymentConfirm,
payment_confirm_req,
services::api::AuthFlow::Merchant,
connector_action,
None,
HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator),
))
.await?
} else {
let payment_sync_req = api::PaymentsRetrieveRequest {
resource_id: req.resource_id,
merchant_id: req.merchant_id,
param: req.param,
force_sync: req.force_sync,
connector: req.connector,
merchant_connector_details: req.creds_identifier.map(|creds_id| {
api::MerchantConnectorDetailsWrap {
creds_identifier: creds_id,
encoded_data: None,
}
}),
client_secret: None,
expand_attempts: None,
expand_captures: None,
all_keys_required: None,
};
Box::pin(
payments_core::<api::PSync, api::PaymentsResponse, _, _, _, _>(
state.clone(),
req_state,
merchant_context.clone(),
None,
PaymentStatus,
payment_sync_req,
services::api::AuthFlow::Merchant,
connector_action,
None,
HeaderPayload::default(),
),
)
.await?
};
let payments_response = match response {
services::ApplicationResponse::Json(response) => Ok(response),
services::ApplicationResponse::JsonWithHeaders((response, _)) => Ok(response),
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the response in json"),
}?;
// When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client
if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction {
let req_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_id);
let poll_id = core_utils::get_poll_id(&merchant_id, req_poll_id.clone());
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.set_key_with_expiry(
&poll_id.into(),
api_models::poll::PollStatus::Pending.to_string(),
consts::POLL_ID_TTL,
)
.await
.change_context(errors::StorageError::KVError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add poll_id in redis")?;
};
let default_poll_config = router_types::PollConfig::default();
let default_config_str = default_poll_config
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while stringifying default poll config")?;
let poll_config = state
.store
.find_config_by_key_unwrap_or(
&router_types::PollConfig::get_poll_config_key(connector),
Some(default_config_str),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The poll config was not found in the DB")?;
let poll_config: router_types::PollConfig = poll_config
.config
.parse_struct("PollConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing PollConfig")?;
let profile_id = payments_response
.profile_id
.as_ref()
.get_required_value("profile_id")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(router_types::AuthenticatePaymentFlowResponse {
payments_response,
poll_config,
business_profile,
})
}
fn generate_response(
&self,
payment_flow_response: &Self::PaymentFlowResponse,
payment_id: id_type::PaymentId,
connector: String,
) -> RouterResult<services::ApplicationResponse<api::RedirectionResponse>> {
let payments_response = &payment_flow_response.payments_response;
let redirect_response = helpers::get_handle_response_url(
payment_id.clone(),
&payment_flow_response.business_profile,
payments_response,
connector.clone(),
)?;
// html script to check if inside iframe, then send post message to parent for redirection else redirect self to return_url
let html = core_utils::get_html_redirect_response_for_external_authentication(
redirect_response.return_url_with_query_params,
payments_response,
payment_id,
&payment_flow_response.poll_config,
)?;
Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
redirect_form: services::RedirectForm::Html { html_data: html },
payment_method_data: None,
amount: payments_response.amount.to_string(),
currency: payments_response.currency.clone(),
},
)))
}
fn get_payment_action(&self) -> services::PaymentAction {
services::PaymentAction::PaymentAuthenticateCompleteAuthorize
}
}
#[cfg(feature = "v1")]
pub async fn get_decrypted_wallet_payment_method_token<F, Req, D>(
operation: &BoxedOperation<'_, F, Req, D>,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &mut D,
connector_call_type_optional: Option<&ConnectorCallType>,
) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse>
where
F: Send + Clone + Sync,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
if is_operation_confirm(operation)
&& payment_data.get_payment_attempt().payment_method
== Some(storage_enums::PaymentMethod::Wallet)
&& payment_data.get_payment_method_data().is_some()
{
let wallet_type = payment_data
.get_payment_attempt()
.payment_method_type
.get_required_value("payment_method_type")?;
let wallet: Box<dyn WalletFlow<F, D>> = match wallet_type {
storage_enums::PaymentMethodType::ApplePay => Box::new(ApplePayWallet),
storage_enums::PaymentMethodType::Paze => Box::new(PazeWallet),
storage_enums::PaymentMethodType::GooglePay => Box::new(GooglePayWallet),
_ => return Ok(None),
};
// Check if the wallet has already decrypted the token from the payment data.
// If a pre-decrypted token is available, use it directly to avoid redundant decryption.
if let Some(predecrypted_token) = wallet.check_predecrypted_token(payment_data)? {
logger::debug!("Using predecrypted token for wallet");
return Ok(Some(predecrypted_token));
}
let merchant_connector_account =
get_merchant_connector_account_for_wallet_decryption_flow::<F, D>(
state,
merchant_context,
payment_data,
connector_call_type_optional,
)
.await?;
let decide_wallet_flow = &wallet
.decide_wallet_flow(state, payment_data, &merchant_connector_account)
.attach_printable("Failed to decide wallet flow")?
.async_map(|payment_price_data| async move {
wallet
.decrypt_wallet_token(&payment_price_data, payment_data)
.await
})
.await
.transpose()
.attach_printable("Failed to decrypt Wallet token")?;
Ok(decide_wallet_flow.clone())
} else {
Ok(None)
}
}
#[cfg(feature = "v1")]
pub async fn get_merchant_connector_account_for_wallet_decryption_flow<F, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &mut D,
connector_call_type_optional: Option<&ConnectorCallType>,
) -> RouterResult<helpers::MerchantConnectorAccountType>
where
F: Send + Clone + Sync,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
let connector_call_type = connector_call_type_optional
.get_required_value("connector_call_type")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let connector_routing_data = match connector_call_type {
ConnectorCallType::PreDetermined(connector_routing_data) => connector_routing_data,
ConnectorCallType::Retryable(connector_routing_data) => connector_routing_data
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Found no connector routing data in retryable call")?,
ConnectorCallType::SessionMultiple(_session_connector_data) => {
return Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
"SessionMultiple connector call type is invalid in confirm calls",
);
}
};
construct_profile_id_and_get_mca(
state,
merchant_context,
payment_data,
&connector_routing_data
.connector_data
.connector_name
.to_string(),
connector_routing_data
.connector_data
.merchant_connector_id
.as_ref(),
false,
)
.await
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
is_retry_payment: bool,
return_raw_connector_response: Option<bool>,
merchant_connector_account: helpers::MerchantConnectorAccountType,
mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
tokenization_action: TokenizationAction,
) -> RouterResult<(
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
helpers::MerchantConnectorAccountType,
)>
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>
+ Send
+ Sync,
{
let add_access_token_result = router_data
.add_access_token(
state,
&connector,
merchant_context,
payment_data.get_creds_identifier(),
)
.await?;
router_data = router_data.add_session_token(state, &connector).await?;
let should_continue_further = access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&call_connector_action,
);
let should_continue_further = match router_data
.create_order_at_connector(state, &connector, should_continue_further)
.await?
{
Some(create_order_response) => {
if let Ok(order_id) = create_order_response.clone().create_order_result {
payment_data.set_connector_response_reference_id(Some(order_id.clone()))
}
// Set the response in routerdata response to carry forward
router_data
.update_router_data_with_create_order_response(create_order_response.clone());
create_order_response.create_order_result.ok().is_some()
}
// If create order is not required, then we can proceed with further processing
None => true,
};
let updated_customer = call_create_connector_customer_if_required(
state,
customer,
merchant_context,
&merchant_connector_account,
payment_data,
router_data.access_token.as_ref(),
)
.await?;
#[cfg(feature = "v1")]
if let Some(connector_customer_id) = payment_data.get_connector_customer_id() {
router_data.connector_customer = Some(connector_customer_id);
}
router_data.payment_method_token = payment_data.get_payment_method_token().cloned();
let payment_method_token_response = router_data
.add_payment_method_token(
state,
&connector,
&tokenization_action,
should_continue_further,
)
.await?;
let mut should_continue_further =
tokenization::update_router_data_with_payment_method_token_result(
payment_method_token_response,
&mut router_data,
is_retry_payment,
should_continue_further,
);
(router_data, should_continue_further) = complete_preprocessing_steps_if_required(
state,
&connector,
payment_data,
router_data,
operation,
should_continue_further,
)
.await?;
if let Ok(router_types::PaymentsResponseData::PreProcessingResponse {
session_token: Some(session_token),
..
}) = router_data.response.to_owned()
{
payment_data.push_sessions_token(session_token);
};
// In case of authorize flow, pre-task and post-tasks are being called in build request
// if we do not want to proceed further, then the function will return Ok(None, false)
let (connector_request, should_continue_further) = if should_continue_further {
// Check if the actual flow specific request can be built with available data
router_data
.build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
.await?
} else {
(None, false)
};
if should_add_task_to_process_tracker(payment_data) {
operation
.to_domain()?
.add_task_to_process_tracker(
state,
payment_data.get_payment_attempt(),
validate_result.requeue,
schedule_time,
)
.await
.map_err(|error| logger::error!(process_tracker_error=?error))
.ok();
}
// Update the payment trackers just before calling the connector
// Since the request is already built in the previous step,
// there should be no error in request construction from hyperswitch end
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
updated_customer,
merchant_context.get_merchant_key_store(),
frm_suggestion,
header_payload.clone(),
)
.await?;
let router_data = if should_continue_further {
// The status of payment_attempt and intent will be updated in the previous step
// update this in router_data.
// This is added because few connector integrations do not update the status,
// and rely on previous status set in router_data
router_data.status = payment_data.get_payment_attempt().status;
router_data
.decide_flows(
state,
&connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
return_raw_connector_response,
)
.await
} else {
Ok(router_data)
}?;
Ok((router_data, merchant_connector_account))
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
validate_result: &operations::ValidateResult,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
routing_decision: Option<routing_helpers::RoutingDecisionData>,
) -> RouterResult<(
helpers::MerchantConnectorAccountType,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
TokenizationAction,
)>
where
F: Send + Clone + Sync,
RouterDReq: Send + Clone + 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 + Clone,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let merchant_connector_account = construct_profile_id_and_get_mca(
state,
merchant_context,
payment_data,
&connector.connector_name.to_string(),
connector.merchant_connector_id.as_ref(),
false,
)
.await?;
let customer_acceptance = payment_data
.get_payment_attempt()
.customer_acceptance
.clone();
if is_pre_network_tokenization_enabled(
state,
business_profile,
customer_acceptance,
connector.connector_name,
) {
let payment_method_data = payment_data.get_payment_method_data();
let customer_id = payment_data.get_payment_intent().customer_id.clone();
if let (Some(domain::PaymentMethodData::Card(card_data)), Some(customer_id)) =
(payment_method_data, customer_id)
{
let vault_operation =
get_vault_operation_for_pre_network_tokenization(state, customer_id, card_data)
.await;
match vault_operation {
payments::VaultOperation::SaveCardAndNetworkTokenData(
card_and_network_token_data,
) => {
payment_data.set_vault_operation(
payments::VaultOperation::SaveCardAndNetworkTokenData(Box::new(
*card_and_network_token_data.clone(),
)),
);
payment_data.set_payment_method_data(Some(
domain::PaymentMethodData::NetworkToken(
card_and_network_token_data
.network_token
.network_token_data
.clone(),
),
));
}
payments::VaultOperation::SaveCardData(card_data_for_vault) => payment_data
.set_vault_operation(payments::VaultOperation::SaveCardData(
card_data_for_vault.clone(),
)),
payments::VaultOperation::ExistingVaultData(_) => (),
}
}
}
if payment_data
.get_payment_attempt()
.merchant_connector_id
.is_none()
{
payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id());
}
operation
.to_domain()?
.populate_payment_data(
state,
payment_data,
merchant_context,
business_profile,
&connector,
)
.await?;
let (pd, tokenization_action) = get_connector_tokenization_action_when_confirm_true(
state,
operation,
payment_data,
validate_result,
merchant_context.get_merchant_key_store(),
customer,
business_profile,
should_retry_with_pan,
)
.await?;
*payment_data = pd;
// This is used to apply any kind of routing decision to the required data,
// before the call to `connector` is made.
routing_decision.map(|decision| decision.apply_routing_decision(payment_data));
// Validating the blocklist guard and generate the fingerprint
blocklist_guard(state, merchant_context, operation, payment_data).await?;
let merchant_recipient_data = payment_data
.get_merchant_recipient_data(
state,
merchant_context,
&merchant_connector_account,
&connector,
)
.await?;
let router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
customer,
&merchant_connector_account,
merchant_recipient_data,
None,
payment_data.get_payment_attempt().payment_method,
payment_data.get_payment_attempt().payment_method_type,
)
.await?;
let connector_request_reference_id = router_data.connector_request_reference_id.clone();
payment_data
.set_connector_request_reference_id_in_payment_attempt(connector_request_reference_id);
Ok((merchant_connector_account, router_data, tokenization_action))
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn decide_unified_connector_service_call<'a, F, RouterDReq, ApiRequest, D>(
state: &'a SessionState,
req_state: ReqState,
merchant_context: &'a domain::MerchantContext,
connector: api::ConnectorData,
operation: &'a BoxedOperation<'a, F, ApiRequest, D>,
payment_data: &'a mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
validate_result: &'a operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &'a domain::Profile,
is_retry_payment: bool,
all_keys_required: Option<bool>,
merchant_connector_account: helpers::MerchantConnectorAccountType,
router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
tokenization_action: TokenizationAction,
) -> RouterResult<(
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
helpers::MerchantConnectorAccountType,
)>
where
F: Send + Clone + Sync + 'static,
RouterDReq: Send + Sync + Clone + 'static + serde::Serialize,
// 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 + Clone + serde::Serialize,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let execution_path = should_call_unified_connector_service(
state,
merchant_context,
&router_data,
Some(payment_data),
)
.await?;
let is_handle_response_action = matches!(
call_connector_action,
CallConnectorAction::UCSHandleResponse(_) | CallConnectorAction::HandleResponse(_)
);
record_time_taken_with(|| async {
match (execution_path, is_handle_response_action) {
// Process through UCS when system is UCS and not handling response
(ExecutionPath::UnifiedConnectorService, false) => {
process_through_ucs(
state,
req_state,
merchant_context,
operation,
payment_data,
customer,
validate_result,
schedule_time,
header_payload,
frm_suggestion,
business_profile,
merchant_connector_account,
router_data,
)
.await
}
// Process through Direct with Shadow UCS
(ExecutionPath::ShadowUnifiedConnectorService, false) => {
process_through_direct_with_shadow_unified_connector_service(
state,
req_state,
merchant_context,
connector,
operation,
payment_data,
customer,
call_connector_action,
validate_result,
schedule_time,
header_payload,
frm_suggestion,
business_profile,
is_retry_payment,
all_keys_required,
merchant_connector_account,
router_data,
tokenization_action,
)
.await
}
// Process through Direct gateway
(ExecutionPath::Direct, _)
| (ExecutionPath::UnifiedConnectorService, true)
| (ExecutionPath::ShadowUnifiedConnectorService, true) => {
process_through_direct(
state,
req_state,
merchant_context,
connector,
operation,
payment_data,
customer,
call_connector_action,
validate_result,
schedule_time,
header_payload,
frm_suggestion,
business_profile,
is_retry_payment,
all_keys_required,
merchant_connector_account,
router_data,
tokenization_action,
)
.await
}
}
})
.await
}
async fn record_time_taken_with<F, Fut, R>(f: F) -> RouterResult<R>
where
F: FnOnce() -> Fut,
Fut: future::Future<Output = RouterResult<R>>,
{
let stime = Instant::now();
let result = f().await;
let etime = Instant::now();
let duration = etime.saturating_duration_since(stime);
tracing::info!(duration = format!("Duration taken: {}", duration.as_millis()));
result
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn call_connector_service<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
is_retry_payment: bool,
should_retry_with_pan: bool,
return_raw_connector_response: Option<bool>,
merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
updated_customer: Option<storage::CustomerUpdate>,
tokenization_action: TokenizationAction,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
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 add_access_token_result = router_data
.add_access_token(
state,
&connector,
merchant_context,
payment_data.get_creds_identifier(),
)
.await?;
router_data = router_data.add_session_token(state, &connector).await?;
let should_continue_further = access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&call_connector_action,
);
let payment_method_token_response = router_data
.add_payment_method_token(
state,
&connector,
&tokenization_action,
should_continue_further,
)
.await?;
let should_continue_further = tokenization::update_router_data_with_payment_method_token_result(
payment_method_token_response,
&mut router_data,
is_retry_payment,
should_continue_further,
);
let should_continue = match router_data
.create_order_at_connector(state, &connector, should_continue_further)
.await?
{
Some(create_order_response) => {
if let Ok(order_id) = create_order_response.clone().create_order_result {
payment_data.set_connector_response_reference_id(Some(order_id))
}
// Set the response in routerdata response to carry forward
router_data
.update_router_data_with_create_order_response(create_order_response.clone());
create_order_response.create_order_result.ok().map(|_| ())
}
// If create order is not required, then we can proceed with further processing
None => Some(()),
};
// In case of authorize flow, pre-task and post-tasks are being called in build request
// if we do not want to proceed further, then the function will return Ok(None, false)
let (connector_request, should_continue_further) = match should_continue {
Some(_) => {
router_data
.build_flow_specific_connector_request(
state,
&connector,
call_connector_action.clone(),
)
.await?
}
None => (None, false),
};
// Update the payment trackers just before calling the connector
// Since the request is already built in the previous step,
// there should be no error in request construction from hyperswitch end
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
updated_customer,
merchant_context.get_merchant_key_store(),
frm_suggestion,
header_payload.clone(),
)
.await?;
let router_data = if should_continue_further {
// The status of payment_attempt and intent will be updated in the previous step
// update this in router_data.
// This is added because few connector integrations do not update the status,
// and rely on previous status set in router_data
// TODO: status is already set when constructing payment data, why should this be done again?
// router_data.status = payment_data.get_payment_attempt().status;
router_data
.decide_flows(
state,
&connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
return_raw_connector_response,
)
.await
} else {
Ok(router_data)
}?;
Ok(router_data)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
#[instrument(skip_all)]
pub async fn call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
is_retry_payment: bool,
should_retry_with_pan: bool,
all_keys_required: Option<bool>,
) -> RouterResult<(
domain::MerchantConnectorAccountTypeDetails,
Option<storage::CustomerUpdate>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
TokenizationAction,
)>
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 merchant_connector_account_type_details =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
connector.merchant_connector_id.as_ref(),
)
.await?,
));
operation
.to_domain()?
.populate_payment_data(
state,
payment_data,
merchant_context,
business_profile,
&connector,
)
.await?;
let updated_customer = call_create_connector_customer_if_required(
state,
customer,
merchant_context,
&merchant_connector_account_type_details,
payment_data,
)
.await?;
let router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
customer,
&merchant_connector_account_type_details,
None,
Some(header_payload),
)
.await?;
let tokenization_action = operation
.to_domain()?
.get_connector_tokenization_action(state, payment_data)
.await?;
Ok((
merchant_connector_account_type_details,
updated_customer,
router_data,
tokenization_action,
))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
#[instrument(skip_all)]
pub async fn call_connector_service_prerequisites_for_external_vault_proxy<
F,
RouterDReq,
ApiRequest,
D,
>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
is_retry_payment: bool,
should_retry_with_pan: bool,
all_keys_required: Option<bool>,
) -> RouterResult<(
domain::MerchantConnectorAccountTypeDetails,
domain::MerchantConnectorAccountTypeDetails,
Option<storage::CustomerUpdate>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
)>
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>,
{
// get merchant connector account related to external vault
let external_vault_source: id_type::MerchantConnectorAccountId = business_profile
.external_vault_connector_details
.clone()
.map(|connector_details| connector_details.vault_connector_id.clone())
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("mca_id not present for external vault")?;
let external_vault_merchant_connector_account_type_details =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
Some(&external_vault_source),
)
.await?,
));
let (
merchant_connector_account_type_details,
updated_customer,
router_data,
_tokenization_action,
) = call_connector_service_prerequisites(
state,
req_state,
merchant_context,
connector,
operation,
payment_data,
customer,
call_connector_action,
schedule_time,
header_payload,
frm_suggestion,
business_profile,
is_retry_payment,
should_retry_with_pan,
all_keys_required,
)
.await?;
Ok((
merchant_connector_account_type_details,
external_vault_merchant_connector_account_type_details,
updated_customer,
router_data,
))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn internal_call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
business_profile: &domain::Profile,
) -> RouterResult<(
domain::MerchantConnectorAccountTypeDetails,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
)>
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 merchant_connector_details =
payment_data
.get_merchant_connector_details()
.ok_or_else(|| {
error_stack::report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector details not found in payment data")
})?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(
merchant_connector_details,
);
operation
.to_domain()?
.populate_payment_data(
state,
payment_data,
merchant_context,
business_profile,
&connector,
)
.await?;
let router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
&None,
&merchant_connector_account,
None,
None,
)
.await?;
Ok((merchant_connector_account, router_data))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn connector_service_decider<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
business_profile: &domain::Profile,
return_raw_connector_response: Option<bool>,
merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
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 mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
&None,
&merchant_connector_account_type_details,
None,
Some(header_payload.clone()),
)
.await?;
// do order creation
let execution_path = should_call_unified_connector_service(
state,
merchant_context,
&router_data,
Some(payment_data),
)
.await?;
let (connector_request, should_continue_further) =
if matches!(execution_path, ExecutionPath::Direct) {
let mut should_continue_further = true;
let should_continue = match router_data
.create_order_at_connector(state, &connector, should_continue_further)
.await?
{
Some(create_order_response) => {
if let Ok(order_id) = create_order_response.clone().create_order_result {
payment_data.set_connector_response_reference_id(Some(order_id))
}
// Set the response in routerdata response to carry forward
router_data.update_router_data_with_create_order_response(
create_order_response.clone(),
);
create_order_response.create_order_result.ok().map(|_| ())
}
// If create order is not required, then we can proceed with further processing
None => Some(()),
};
let should_continue: (Option<common_utils::request::Request>, bool) =
match should_continue {
Some(_) => {
router_data
.build_flow_specific_connector_request(
state,
&connector,
call_connector_action.clone(),
)
.await?
}
None => (None, false),
};
should_continue
} else {
// If unified connector service is called, these values are not used
// as the request is built in the unified connector service call
(None, false)
};
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
None, // customer is not used in internal flows
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None, // frm_suggestion is not used in internal flows
header_payload.clone(),
)
.await?;
record_time_taken_with(|| async {
if matches!(execution_path, ExecutionPath::UnifiedConnectorService) {
router_env::logger::info!(
"Processing payment through UCS gateway system- payment_id={}, attempt_id={}",
payment_data.get_payment_intent().id.get_string_repr(),
payment_data.get_payment_attempt().id.get_string_repr()
);
let lineage_ids = grpc_client::LineageIds::new(business_profile.merchant_id.clone(), business_profile.get_id().clone());
router_data
.call_unified_connector_service(
state,
&header_payload,
lineage_ids,
merchant_connector_account_type_details.clone(),
merchant_context,
ExecutionMode::Primary, // UCS is called in primary mode
)
.await?;
Ok(router_data)
} else {
Err(
errors::ApiErrorResponse::InternalServerError
)
.attach_printable("Unified connector service is down and traditional connector service fallback is not implemented")
}
})
.await
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn decide_unified_connector_service_call<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
is_retry_payment: bool,
should_retry_with_pan: bool,
return_raw_connector_response: Option<bool>,
merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
updated_customer: Option<storage::CustomerUpdate>,
tokenization_action: TokenizationAction,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
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>,
{
record_time_taken_with(|| async {
let execution_path = should_call_unified_connector_service(
state,
merchant_context,
&router_data,
Some(payment_data),
)
.await?;
if matches!(execution_path, ExecutionPath::UnifiedConnectorService) {
router_env::logger::info!(
"Executing payment through UCS gateway system - payment_id={}, attempt_id={}",
payment_data.get_payment_intent().id.get_string_repr(),
payment_data.get_payment_attempt().id.get_string_repr()
);
if should_add_task_to_process_tracker(payment_data) {
operation
.to_domain()?
.add_task_to_process_tracker(
state,
payment_data.get_payment_attempt(),
false,
schedule_time,
)
.await
.map_err(|error| logger::error!(process_tracker_error=?error))
.ok();
}
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
frm_suggestion,
header_payload.clone(),
)
.await?;
let lineage_ids = grpc_client::LineageIds::new(
business_profile.merchant_id.clone(),
business_profile.get_id().clone(),
);
router_data
.call_unified_connector_service(
state,
&header_payload,
lineage_ids,
merchant_connector_account_type_details.clone(),
merchant_context,
ExecutionMode::Primary, //UCS is called in primary mode
)
.await?;
Ok(router_data)
} else {
if matches!(execution_path, ExecutionPath::ShadowUnifiedConnectorService) {
router_env::logger::info!(
"Shadow UCS mode not implemented in v2, processing through direct path - payment_id={}, attempt_id={}",
payment_data.get_payment_intent().id.get_string_repr(),
payment_data.get_payment_attempt().id.get_string_repr()
);
} else {
router_env::logger::info!(
"Processing payment through Direct gateway system - payment_id={}, attempt_id={}",
payment_data.get_payment_intent().id.get_string_repr(),
payment_data.get_payment_attempt().id.get_string_repr()
);
}
call_connector_service(
state,
req_state,
merchant_context,
connector,
operation,
payment_data,
customer,
call_connector_action,
schedule_time,
header_payload,
frm_suggestion,
business_profile,
is_retry_payment,
should_retry_with_pan,
return_raw_connector_response,
merchant_connector_account_type_details,
router_data,
updated_customer,
tokenization_action,
)
.await
}
})
.await
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn call_unified_connector_service_for_external_proxy<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
_connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
_call_connector_action: CallConnectorAction,
_schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
_is_retry_payment: bool,
_should_retry_with_pan: bool,
_return_raw_connector_response: Option<bool>,
merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
external_vault_merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
_updated_customer: Option<storage::CustomerUpdate>,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
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>,
{
record_time_taken_with(|| async {
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
frm_suggestion,
header_payload.clone(),
)
.await?;
let lineage_ids = grpc_client::LineageIds::new(
business_profile.merchant_id.clone(),
business_profile.get_id().clone(),
);
router_data
.call_unified_connector_service_with_external_vault_proxy(
state,
&header_payload,
lineage_ids,
merchant_connector_account_type_details.clone(),
external_vault_merchant_connector_account_type_details.clone(),
merchant_context,
ExecutionMode::Primary, //UCS is called in primary mode
)
.await?;
Ok(router_data)
})
.await
}
#[cfg(feature = "v1")]
// This function does not perform the tokenization action, as the payment method is not saved in this flow.
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
business_profile: &domain::Profile,
return_raw_connector_response: Option<bool>,
) -> RouterResult<(
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
helpers::MerchantConnectorAccountType,
)>
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 stime_connector = Instant::now();
let merchant_connector_account = construct_profile_id_and_get_mca(
state,
merchant_context,
payment_data,
&connector.connector_name.to_string(),
connector.merchant_connector_id.as_ref(),
false,
)
.await?;
if payment_data
.get_payment_attempt()
.merchant_connector_id
.is_none()
{
payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id());
}
let merchant_recipient_data = None;
let mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
customer,
&merchant_connector_account,
merchant_recipient_data,
Some(header_payload.clone()),
payment_data.get_payment_attempt().payment_method,
payment_data.get_payment_attempt().payment_method_type,
)
.await?;
let add_access_token_result = router_data
.add_access_token(
state,
&connector,
merchant_context,
payment_data.get_creds_identifier(),
)
.await?;
router_data = router_data.add_session_token(state, &connector).await?;
let mut should_continue_further = access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&call_connector_action,
);
(router_data, should_continue_further) = complete_preprocessing_steps_if_required(
state,
&connector,
payment_data,
router_data,
operation,
should_continue_further,
)
.await?;
if let Ok(router_types::PaymentsResponseData::PreProcessingResponse {
session_token: Some(session_token),
..
}) = router_data.response.to_owned()
{
payment_data.push_sessions_token(session_token);
};
let (connector_request, should_continue_further) = if should_continue_further {
// Check if the actual flow specific request can be built with available data
router_data
.build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
.await?
} else {
(None, false)
};
if should_add_task_to_process_tracker(payment_data) {
operation
.to_domain()?
.add_task_to_process_tracker(
state,
payment_data.get_payment_attempt(),
validate_result.requeue,
schedule_time,
)
.await
.map_err(|error| logger::error!(process_tracker_error=?error))
.ok();
}
let updated_customer = None;
let frm_suggestion = None;
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
updated_customer,
merchant_context.get_merchant_key_store(),
frm_suggestion,
header_payload.clone(),
)
.await?;
let router_data = if should_continue_further {
// The status of payment_attempt and intent will be updated in the previous step
// update this in router_data.
// This is added because few connector integrations do not update the status,
// and rely on previous status set in router_data
router_data.status = payment_data.get_payment_attempt().status;
router_data
.decide_flows(
state,
&connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
return_raw_connector_response,
)
.await
} else {
Ok(router_data)
}?;
let etime_connector = Instant::now();
let duration_connector = etime_connector.saturating_duration_since(stime_connector);
tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
Ok((router_data, merchant_connector_account))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
business_profile: &domain::Profile,
return_raw_connector_response: Option<bool>,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
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 stime_connector = Instant::now();
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
connector.merchant_connector_id.as_ref(),
)
.await?,
));
operation
.to_domain()?
.populate_payment_data(
state,
payment_data,
merchant_context,
business_profile,
&connector,
)
.await?;
let mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
&None,
&merchant_connector_account,
None,
Some(header_payload.clone()),
)
.await?;
let add_access_token_result = router_data
.add_access_token(
state,
&connector,
merchant_context,
payment_data.get_creds_identifier(),
)
.await?;
router_data = router_data.add_session_token(state, &connector).await?;
let mut should_continue_further = access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&call_connector_action,
);
let (connector_request, should_continue_further) = if should_continue_further {
router_data
.build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
.await?
} else {
(None, false)
};
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
None,
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload.clone(),
)
.await?;
let router_data = if should_continue_further {
router_data
.decide_flows(
state,
&connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
return_raw_connector_response,
)
.await
} else {
Ok(router_data)
}?;
let etime_connector = Instant::now();
let duration_connector = etime_connector.saturating_duration_since(stime_connector);
tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
Ok(router_data)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn call_connector_service_for_external_vault_proxy<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
business_profile: &domain::Profile,
return_raw_connector_response: Option<bool>,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
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 stime_connector = Instant::now();
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
connector.merchant_connector_id.as_ref(),
)
.await?,
));
operation
.to_domain()?
.populate_payment_data(
state,
payment_data,
merchant_context,
business_profile,
&connector,
)
.await?;
let mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
&None,
&merchant_connector_account,
None,
Some(header_payload.clone()),
)
.await?;
// let add_access_token_result = router_data
// .add_access_token(
// state,
// &connector,
// merchant_context,
// payment_data.get_creds_identifier(),
// )
// .await?;
// router_data = router_data.add_session_token(state, &connector).await?;
// let mut should_continue_further = access_token::update_router_data_with_access_token_result(
// &add_access_token_result,
// &mut router_data,
// &call_connector_action,
// );
let should_continue_further = true;
let (connector_request, should_continue_further) = if should_continue_further {
router_data
.build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
.await?
} else {
(None, false)
};
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
None,
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload.clone(),
)
.await?;
let router_data = if should_continue_further {
router_data
.decide_flows(
state,
&connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
return_raw_connector_response,
)
.await
} else {
Ok(router_data)
}?;
let etime_connector = Instant::now();
let duration_connector = etime_connector.saturating_duration_since(stime_connector);
tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
Ok(router_data)
}
struct ApplePayWallet;
struct PazeWallet;
struct GooglePayWallet;
#[async_trait::async_trait]
pub trait WalletFlow<F, D>: Send + Sync
where
F: Send + Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
/// Check if wallet data is already decrypted and return token if so
fn check_predecrypted_token(
&self,
_payment_data: &D,
) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> {
// Default implementation returns None (no pre-decrypted data)
Ok(None)
}
fn decide_wallet_flow(
&self,
state: &SessionState,
payment_data: &D,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse>;
async fn decrypt_wallet_token(
&self,
wallet_flow: &DecideWalletFlow,
payment_data: &D,
) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse>;
}
#[async_trait::async_trait]
impl<F, D> WalletFlow<F, D> for PazeWallet
where
F: Send + Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
fn decide_wallet_flow(
&self,
state: &SessionState,
_payment_data: &D,
_merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {
let paze_keys = state
.conf
.paze_decrypt_keys
.as_ref()
.get_required_value("Paze decrypt keys")
.attach_printable("Paze decrypt keys not found in the configuration")?;
let wallet_flow = DecideWalletFlow::PazeDecrypt(PazePaymentProcessingDetails {
paze_private_key: paze_keys.get_inner().paze_private_key.clone(),
paze_private_key_passphrase: paze_keys.get_inner().paze_private_key_passphrase.clone(),
});
Ok(Some(wallet_flow))
}
async fn decrypt_wallet_token(
&self,
wallet_flow: &DecideWalletFlow,
payment_data: &D,
) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> {
let paze_payment_processing_details = wallet_flow
.get_paze_payment_processing_details()
.get_required_value("Paze payment processing details")
.attach_printable(
"Paze payment processing details not found in Paze decryption flow",
)?;
let paze_wallet_data = payment_data
.get_payment_method_data()
.and_then(|payment_method_data| payment_method_data.get_wallet_data())
.and_then(|wallet_data| wallet_data.get_paze_wallet_data())
.get_required_value("Paze wallet token").attach_printable(
"Paze wallet data not found in the payment method data during the Paze decryption flow",
)?;
let paze_data = decrypt_paze_token(
paze_wallet_data.clone(),
paze_payment_processing_details.paze_private_key.clone(),
paze_payment_processing_details
.paze_private_key_passphrase
.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to decrypt paze token")?;
let paze_decrypted_data = paze_data
.parse_value::<hyperswitch_domain_models::router_data::PazeDecryptedData>(
"PazeDecryptedData",
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to parse PazeDecryptedData")?;
Ok(PaymentMethodToken::PazeDecrypt(Box::new(
paze_decrypted_data,
)))
}
}
#[async_trait::async_trait]
impl<F, D> WalletFlow<F, D> for ApplePayWallet
where
F: Send + Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
fn check_predecrypted_token(
&self,
payment_data: &D,
) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> {
let apple_pay_wallet_data = payment_data
.get_payment_method_data()
.and_then(|payment_method_data| payment_method_data.get_wallet_data())
.and_then(|wallet_data| wallet_data.get_apple_pay_wallet_data());
let result = if let Some(data) = apple_pay_wallet_data {
match &data.payment_data {
common_payments_types::ApplePayPaymentData::Encrypted(_) => None,
common_payments_types::ApplePayPaymentData::Decrypted(
apple_pay_predecrypt_data,
) => {
helpers::validate_card_expiry(
&apple_pay_predecrypt_data.application_expiration_month,
&apple_pay_predecrypt_data.application_expiration_year,
)?;
Some(PaymentMethodToken::ApplePayDecrypt(Box::new(
apple_pay_predecrypt_data.clone(),
)))
}
}
} else {
None
};
Ok(result)
}
fn decide_wallet_flow(
&self,
state: &SessionState,
payment_data: &D,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {
let apple_pay_metadata = check_apple_pay_metadata(state, Some(merchant_connector_account));
add_apple_pay_flow_metrics(
&apple_pay_metadata,
payment_data.get_payment_attempt().connector.clone(),
payment_data.get_payment_attempt().merchant_id.clone(),
);
let wallet_flow = match apple_pay_metadata {
Some(domain::ApplePayFlow::Simplified(payment_processing_details)) => Some(
DecideWalletFlow::ApplePayDecrypt(payment_processing_details),
),
Some(domain::ApplePayFlow::Manual) | None => None,
};
Ok(wallet_flow)
}
async fn decrypt_wallet_token(
&self,
wallet_flow: &DecideWalletFlow,
payment_data: &D,
) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> {
let apple_pay_payment_processing_details = wallet_flow
.get_apple_pay_payment_processing_details()
.get_required_value("Apple Pay payment processing details")
.attach_printable(
"Apple Pay payment processing details not found in Apple Pay decryption flow",
)?;
let apple_pay_wallet_data = payment_data
.get_payment_method_data()
.and_then(|payment_method_data| payment_method_data.get_wallet_data())
.and_then(|wallet_data| wallet_data.get_apple_pay_wallet_data())
.get_required_value("Apple Pay wallet token").attach_printable(
"Apple Pay wallet data not found in the payment method data during the Apple Pay decryption flow",
)?;
let apple_pay_data =
ApplePayData::token_json(domain::WalletData::ApplePay(apple_pay_wallet_data.clone()))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to parse apple pay token to json")?
.decrypt(
&apple_pay_payment_processing_details.payment_processing_certificate,
&apple_pay_payment_processing_details.payment_processing_certificate_key,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to decrypt apple pay token")?;
let apple_pay_predecrypt_internal = apple_pay_data
.parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptDataInternal>(
"ApplePayPredecryptDataInternal",
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to parse decrypted apple pay response to ApplePayPredecryptData",
)?;
let apple_pay_predecrypt =
common_types::payments::ApplePayPredecryptData::try_from(apple_pay_predecrypt_internal)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to convert ApplePayPredecryptDataInternal to ApplePayPredecryptData",
)?;
Ok(PaymentMethodToken::ApplePayDecrypt(Box::new(
apple_pay_predecrypt,
)))
}
}
#[async_trait::async_trait]
impl<F, D> WalletFlow<F, D> for GooglePayWallet
where
F: Send + Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
fn check_predecrypted_token(
&self,
payment_data: &D,
) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> {
let google_pay_wallet_data = payment_data
.get_payment_method_data()
.and_then(|payment_method_data| payment_method_data.get_wallet_data())
.and_then(|wallet_data| wallet_data.get_google_pay_wallet_data());
let result = if let Some(data) = google_pay_wallet_data {
match &data.tokenization_data {
common_payments_types::GpayTokenizationData::Encrypted(_) => None,
common_payments_types::GpayTokenizationData::Decrypted(
google_pay_predecrypt_data,
) => {
helpers::validate_card_expiry(
&google_pay_predecrypt_data.card_exp_month,
&google_pay_predecrypt_data.card_exp_year,
)?;
Some(PaymentMethodToken::GooglePayDecrypt(Box::new(
google_pay_predecrypt_data.clone(),
)))
}
}
} else {
None
};
Ok(result)
}
fn decide_wallet_flow(
&self,
state: &SessionState,
_payment_data: &D,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {
Ok(
get_google_pay_connector_wallet_details(state, merchant_connector_account)
.map(DecideWalletFlow::GooglePayDecrypt),
)
}
async fn decrypt_wallet_token(
&self,
wallet_flow: &DecideWalletFlow,
payment_data: &D,
) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> {
let google_pay_payment_processing_details = wallet_flow
.get_google_pay_payment_processing_details()
.get_required_value("Google Pay payment processing details")
.attach_printable(
"Google Pay payment processing details not found in Google Pay decryption flow",
)?;
let google_pay_wallet_data = payment_data
.get_payment_method_data()
.and_then(|payment_method_data| payment_method_data.get_wallet_data())
.and_then(|wallet_data| wallet_data.get_google_pay_wallet_data())
.get_required_value("Paze wallet token").attach_printable(
"Google Pay wallet data not found in the payment method data during the Google Pay decryption flow",
)?;
let decryptor = helpers::GooglePayTokenDecryptor::new(
google_pay_payment_processing_details
.google_pay_root_signing_keys
.clone(),
google_pay_payment_processing_details
.google_pay_recipient_id
.clone(),
google_pay_payment_processing_details
.google_pay_private_key
.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to create google pay token decryptor")?;
// should_verify_token is set to false to disable verification of token
let google_pay_data_internal = decryptor
.decrypt_token(
google_pay_wallet_data
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ApiErrorResponse::InternalServerError)?
.clone(),
false,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to decrypt google pay token")?;
let google_pay_data =
common_types::payments::GPayPredecryptData::from(google_pay_data_internal);
Ok(PaymentMethodToken::GooglePayDecrypt(Box::new(
google_pay_data,
)))
}
}
#[derive(Debug, Clone)]
pub enum DecideWalletFlow {
ApplePayDecrypt(payments_api::PaymentProcessingDetails),
PazeDecrypt(PazePaymentProcessingDetails),
GooglePayDecrypt(GooglePayPaymentProcessingDetails),
SkipDecryption,
}
impl DecideWalletFlow {
fn get_paze_payment_processing_details(&self) -> Option<&PazePaymentProcessingDetails> {
if let Self::PazeDecrypt(details) = self {
Some(details)
} else {
None
}
}
fn get_apple_pay_payment_processing_details(
&self,
) -> Option<&payments_api::PaymentProcessingDetails> {
if let Self::ApplePayDecrypt(details) = self {
Some(details)
} else {
None
}
}
fn get_google_pay_payment_processing_details(
&self,
) -> Option<&GooglePayPaymentProcessingDetails> {
if let Self::GooglePayDecrypt(details) = self {
Some(details)
} else {
None
}
}
}
pub async fn get_merchant_bank_data_for_open_banking_connectors(
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_context: &domain::MerchantContext,
connector: &api::ConnectorData,
state: &SessionState,
) -> RouterResult<Option<router_types::MerchantRecipientData>> {
let merchant_data = merchant_connector_account
.get_additional_merchant_data()
.get_required_value("additional_merchant_data")?
.into_inner()
.peek()
.clone();
let merchant_recipient_data = merchant_data
.parse_value::<router_types::AdditionalMerchantData>("AdditionalMerchantData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to decode MerchantRecipientData")?;
let connector_name = enums::Connector::to_string(&connector.connector_name);
let locker_based_connector_list = state.conf.locker_based_open_banking_connectors.clone();
let contains = locker_based_connector_list
.connector_list
.contains(connector_name.as_str());
let recipient_id = helpers::get_recipient_id_for_open_banking(&merchant_recipient_data)?;
let final_recipient_data = if let Some(id) = recipient_id {
if contains {
// Customer Id for OpenBanking connectors will be merchant_id as the account data stored at locker belongs to the merchant
let merchant_id_str = merchant_context
.get_merchant_account()
.get_id()
.get_string_repr()
.to_owned();
let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from(merchant_id_str))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert to CustomerId")?;
let locker_resp = cards::get_payment_method_from_hs_locker(
state,
merchant_context.get_merchant_key_store(),
&cust_id,
merchant_context.get_merchant_account().get_id(),
id.as_str(),
Some(enums::LockerChoice::HyperswitchCardVault),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant bank account data could not be fetched from locker")?;
let parsed: router_types::MerchantAccountData = locker_resp
.peek()
.to_string()
.parse_struct("MerchantAccountData")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Some(router_types::MerchantRecipientData::AccountData(parsed))
} else {
Some(router_types::MerchantRecipientData::ConnectorRecipientId(
Secret::new(id),
))
}
} else {
None
};
Ok(final_recipient_data)
}
async fn blocklist_guard<F, ApiRequest, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
) -> CustomResult<bool, errors::ApiErrorResponse>
where
F: Send + Clone + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let merchant_id = merchant_context.get_merchant_account().get_id();
let blocklist_enabled_key = merchant_id.get_blocklist_guard_key();
let blocklist_guard_enabled = state
.store
.find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string()))
.await;
let blocklist_guard_enabled: bool = match blocklist_guard_enabled {
Ok(config) => serde_json::from_str(&config.config).unwrap_or(false),
// If it is not present in db we are defaulting it to false
Err(inner) => {
if !inner.current_context().is_db_not_found() {
logger::error!("Error fetching guard blocklist enabled config {:?}", inner);
}
false
}
};
if blocklist_guard_enabled {
Ok(operation
.to_domain()?
.guard_payment_against_blocklist(state, merchant_context, payment_data)
.await?)
} else {
Ok(false)
}
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn call_multiple_connectors_service<F, Op, Req, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connectors: api::SessionConnectorDatas,
_operation: &Op,
mut payment_data: D,
customer: &Option<domain::Customer>,
_session_surcharge_details: Option<api::SessionSurchargeDetails>,
business_profile: &domain::Profile,
header_payload: HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<D>
where
Op: Debug,
F: Send + Clone + 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>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,
{
let call_connectors_start_time = Instant::now();
let mut join_handlers = Vec::with_capacity(connectors.len());
for session_connector_data in connectors.iter() {
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
session_connector_data
.connector
.merchant_connector_id
.as_ref(),
)
.await?,
));
let connector_id = session_connector_data.connector.connector.id();
let router_data = payment_data
.construct_router_data(
state,
connector_id,
merchant_context,
customer,
&merchant_connector_account,
None,
Some(header_payload.clone()),
)
.await?;
let res = router_data.decide_flows(
state,
&session_connector_data.connector,
CallConnectorAction::Trigger,
None,
business_profile,
header_payload.clone(),
return_raw_connector_response,
);
join_handlers.push(res);
}
let result = join_all(join_handlers).await;
for (connector_res, session_connector) in result.into_iter().zip(connectors) {
let connector_name = session_connector.connector.connector_name.to_string();
match connector_res {
Ok(connector_response) => {
if let Ok(router_types::PaymentsResponseData::SessionResponse {
session_token,
..
}) = connector_response.response.clone()
{
// If session token is NoSessionTokenReceived, it is not pushed into the sessions_token as there is no response or there can be some error
// In case of error, that error is already logged
if !matches!(
session_token,
api_models::payments::SessionToken::NoSessionTokenReceived,
) {
payment_data.push_sessions_token(session_token);
}
}
if let Err(connector_error_response) = connector_response.response {
logger::error!(
"sessions_connector_error {} {:?}",
connector_name,
connector_error_response
);
}
}
Err(api_error) => {
logger::error!("sessions_api_error {} {:?}", connector_name, api_error);
}
}
}
let call_connectors_end_time = Instant::now();
let call_connectors_duration =
call_connectors_end_time.saturating_duration_since(call_connectors_start_time);
tracing::info!(duration = format!("Duration taken: {}", call_connectors_duration.as_millis()));
Ok(payment_data)
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn call_multiple_connectors_service<F, Op, Req, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connectors: api::SessionConnectorDatas,
_operation: &Op,
mut payment_data: D,
customer: &Option<domain::Customer>,
session_surcharge_details: Option<api::SessionSurchargeDetails>,
business_profile: &domain::Profile,
header_payload: HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<D>
where
Op: Debug,
F: Send + Clone,
// 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>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,
{
let call_connectors_start_time = Instant::now();
let mut join_handlers = Vec::with_capacity(connectors.len());
for session_connector_data in connectors.iter() {
let connector_id = session_connector_data.connector.connector.id();
let merchant_connector_account = construct_profile_id_and_get_mca(
state,
merchant_context,
&payment_data,
&session_connector_data.connector.connector_name.to_string(),
session_connector_data
.connector
.merchant_connector_id
.as_ref(),
false,
)
.await?;
payment_data.set_surcharge_details(session_surcharge_details.as_ref().and_then(
|session_surcharge_details| {
session_surcharge_details.fetch_surcharge_details(
session_connector_data.payment_method_sub_type.into(),
session_connector_data.payment_method_sub_type,
None,
)
},
));
let router_data = payment_data
.construct_router_data(
state,
connector_id,
merchant_context,
customer,
&merchant_connector_account,
None,
Some(header_payload.clone()),
Some(session_connector_data.payment_method_type),
Some(session_connector_data.payment_method_sub_type),
)
.await?;
let res = router_data.decide_flows(
state,
&session_connector_data.connector,
CallConnectorAction::Trigger,
None,
business_profile,
header_payload.clone(),
return_raw_connector_response,
);
join_handlers.push(res);
}
let result = join_all(join_handlers).await;
for (connector_res, session_connector) in result.into_iter().zip(connectors) {
let connector_name = session_connector.connector.connector_name.to_string();
match connector_res {
Ok(connector_response) => {
if let Ok(router_types::PaymentsResponseData::SessionResponse {
session_token,
..
}) = connector_response.response.clone()
{
// If session token is NoSessionTokenReceived, it is not pushed into the sessions_token as there is no response or there can be some error
// In case of error, that error is already logged
if !matches!(
session_token,
api_models::payments::SessionToken::NoSessionTokenReceived,
) {
payment_data.push_sessions_token(session_token);
}
}
if let Err(connector_error_response) = connector_response.response {
logger::error!(
"sessions_connector_error {} {:?}",
connector_name,
connector_error_response
);
}
}
Err(api_error) => {
logger::error!("sessions_api_error {} {:?}", connector_name, api_error);
}
}
}
// If click_to_pay is enabled and authentication_product_ids is configured in profile, we need to attach click_to_pay block in the session response for invoking click_to_pay SDK
if business_profile.is_click_to_pay_enabled {
if let Some(value) = business_profile.authentication_product_ids.clone() {
let session_token = get_session_token_for_click_to_pay(
state,
merchant_context.get_merchant_account().get_id(),
merchant_context,
value,
payment_data.get_payment_intent(),
business_profile.get_id(),
)
.await?;
payment_data.push_sessions_token(session_token);
}
}
let call_connectors_end_time = Instant::now();
let call_connectors_duration =
call_connectors_end_time.saturating_duration_since(call_connectors_start_time);
tracing::info!(duration = format!("Duration taken: {}", call_connectors_duration.as_millis()));
Ok(payment_data)
}
#[cfg(feature = "v1")]
pub async fn get_session_token_for_click_to_pay(
state: &SessionState,
merchant_id: &id_type::MerchantId,
merchant_context: &domain::MerchantContext,
authentication_product_ids: common_types::payments::AuthenticationConnectorAccountMap,
payment_intent: &payments::PaymentIntent,
profile_id: &id_type::ProfileId,
) -> RouterResult<api_models::payments::SessionToken> {
let click_to_pay_mca_id = authentication_product_ids
.get_click_to_pay_connector_account_id()
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "authentication_product_ids",
})?;
let key_manager_state = &(state).into();
let merchant_connector_account = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
&click_to_pay_mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: click_to_pay_mca_id.get_string_repr().to_string(),
})?;
let click_to_pay_metadata: ClickToPayMetaData = merchant_connector_account
.metadata
.parse_value("ClickToPayMetaData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing ClickToPayMetaData")?;
let transaction_currency = payment_intent
.currency
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("currency is not present in payment_data.payment_intent")?;
let required_amount_type = common_utils::types::StringMajorUnitForConnector;
let transaction_amount = required_amount_type
.convert(payment_intent.amount, transaction_currency)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "string major unit",
})?;
let customer_details_value = payment_intent
.customer_details
.clone()
.get_required_value("customer_details")?;
let customer_details: CustomerData = customer_details_value
.parse_value("CustomerData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing customer data from payment intent")?;
validate_customer_details_for_click_to_pay(&customer_details)?;
let provider = match merchant_connector_account.connector_name.as_str() {
"ctp_mastercard" => Some(enums::CtpServiceProvider::Mastercard),
"ctp_visa" => Some(enums::CtpServiceProvider::Visa),
_ => None,
};
let card_brands = get_card_brands_based_on_active_merchant_connector_account(
state,
profile_id,
merchant_context.get_merchant_key_store(),
)
.await?;
Ok(api_models::payments::SessionToken::ClickToPay(Box::new(
api_models::payments::ClickToPaySessionResponse {
dpa_id: click_to_pay_metadata.dpa_id,
dpa_name: click_to_pay_metadata.dpa_name,
locale: click_to_pay_metadata.locale,
card_brands,
acquirer_bin: click_to_pay_metadata.acquirer_bin,
acquirer_merchant_id: click_to_pay_metadata.acquirer_merchant_id,
merchant_category_code: click_to_pay_metadata.merchant_category_code,
merchant_country_code: click_to_pay_metadata.merchant_country_code,
transaction_amount,
transaction_currency_code: transaction_currency,
phone_number: customer_details.phone.clone(),
email: customer_details.email.clone(),
phone_country_code: customer_details.phone_country_code.clone(),
provider,
dpa_client_id: click_to_pay_metadata.dpa_client_id.clone(),
},
)))
}
#[cfg(feature = "v1")]
async fn get_card_brands_based_on_active_merchant_connector_account(
state: &SessionState,
profile_id: &id_type::ProfileId,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<HashSet<enums::CardNetwork>> {
let key_manager_state = &(state).into();
let merchant_configured_payment_connectors = state
.store
.list_enabled_connector_accounts_by_profile_id(
key_manager_state,
profile_id,
key_store,
common_enums::ConnectorType::PaymentProcessor,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error when fetching merchant connector accounts")?;
let payment_connectors_eligible_for_click_to_pay =
state.conf.authentication_providers.click_to_pay.clone();
let filtered_payment_connector_accounts: Vec<
hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
> = merchant_configured_payment_connectors
.into_iter()
.filter(|account| {
enums::Connector::from_str(&account.connector_name)
.ok()
.map(|connector| payment_connectors_eligible_for_click_to_pay.contains(&connector))
.unwrap_or(false)
})
.collect();
let mut card_brands = HashSet::new();
for account in filtered_payment_connector_accounts {
if let Some(values) = &account.payment_methods_enabled {
for val in values {
let payment_methods_enabled: api_models::admin::PaymentMethodsEnabled =
serde_json::from_value(val.peek().to_owned()).inspect_err(|err| {
logger::error!("Failed to parse Payment methods enabled data set from dashboard because {}", err)
})
.change_context(errors::ApiErrorResponse::InternalServerError)?;
if let Some(payment_method_types) = payment_methods_enabled.payment_method_types {
for payment_method_type in payment_method_types {
if let Some(networks) = payment_method_type.card_networks {
card_brands.extend(networks);
}
}
}
}
}
}
Ok(card_brands)
}
fn validate_customer_details_for_click_to_pay(customer_details: &CustomerData) -> RouterResult<()> {
match (
customer_details.phone.as_ref(),
customer_details.phone_country_code.as_ref(),
customer_details.email.as_ref()
) {
(None, None, Some(_)) => Ok(()),
(Some(_), Some(_), Some(_)) => Ok(()),
(Some(_), Some(_), None) => Ok(()),
(Some(_), None, Some(_)) => Ok(()),
(None, Some(_), None) => Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "phone",
})
.attach_printable("phone number is not present in payment_intent.customer_details"),
(Some(_), None, None) => Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "phone_country_code",
})
.attach_printable("phone_country_code is not present in payment_intent.customer_details"),
(_, _, _) => Err(errors::ApiErrorResponse::MissingRequiredFields {
field_names: vec!["phone", "phone_country_code", "email"],
})
.attach_printable("either of phone, phone_country_code or email is not present in payment_intent.customer_details"),
}
}
#[cfg(feature = "v1")]
pub async fn call_create_connector_customer_if_required<F, Req, D>(
state: &SessionState,
customer: &Option<domain::Customer>,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
payment_data: &mut D,
access_token: Option<&AccessToken>,
) -> 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 connector_name = payment_data.get_payment_attempt().connector.clone();
match connector_name {
Some(connector_name) => {
let connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
merchant_connector_account.get_mca_id(),
)?;
let label = {
let connector_label = core_utils::get_connector_label(
payment_data.get_payment_intent().business_country,
payment_data.get_payment_intent().business_label.as_ref(),
payment_data
.get_payment_attempt()
.business_sub_label
.as_ref(),
&connector_name,
);
if let Some(connector_label) = merchant_connector_account
.get_mca_id()
.map(|mca_id| mca_id.get_string_repr().to_string())
.or(connector_label)
{
connector_label
} else {
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")?;
format!("{connector_name}_{}", profile_id.get_string_repr())
}
};
let (should_call_connector, existing_connector_customer_id) =
customers::should_call_connector_create_customer(
&connector,
customer,
payment_data.get_payment_attempt(),
&label,
);
if should_call_connector {
// Create customer at connector and update the customer table to store this data
let mut customer_router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
customer,
merchant_connector_account,
None,
None,
payment_data.get_payment_attempt().payment_method,
payment_data.get_payment_attempt().payment_method_type,
)
.await?;
customer_router_data.access_token = access_token.cloned();
let connector_customer_id = customer_router_data
.create_connector_customer(state, &connector)
.await?;
let customer_update = customers::update_connector_customer_in_customers(
&label,
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 => Ok(None),
}
}
#[cfg(feature = "v2")]
pub async fn call_create_connector_customer_if_required<F, Req, D>(
state: &SessionState,
customer: &Option<domain::Customer>,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &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 connector_name = payment_data.get_payment_attempt().connector.clone();
match connector_name {
Some(connector_name) => {
let connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
merchant_connector_account.get_id(),
)?;
let (should_call_connector, existing_connector_customer_id) =
customers::should_call_connector_create_customer(
&connector,
customer,
payment_data.get_payment_attempt(),
merchant_connector_account,
);
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(),
merchant_context,
customer,
merchant_connector_account,
None,
None,
)
.await?;
let connector_customer_id = router_data
.create_connector_customer(state, &connector)
.await?;
let customer_update = customers::update_connector_customer_in_customers(
merchant_connector_account,
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 => Ok(None),
}
}
async fn complete_preprocessing_steps_if_required<F, Req, Q, D>(
state: &SessionState,
connector: &api::ConnectorData,
payment_data: &D,
mut router_data: RouterData<F, Req, router_types::PaymentsResponseData>,
operation: &BoxedOperation<'_, F, Q, D>,
should_continue_payment: bool,
) -> RouterResult<(RouterData<F, Req, router_types::PaymentsResponseData>, bool)>
where
F: Send + Clone + Sync,
D: OperationSessionGetters<F> + Send + Sync + Clone,
Req: Send + Sync,
RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send,
dyn api::Connector:
services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,
{
if !is_operation_complete_authorize(&operation)
&& connector
.connector_name
.is_pre_processing_required_before_authorize()
{
router_data = router_data.preprocessing_steps(state, connector).await?;
return Ok((router_data, should_continue_payment));
}
//TODO: For ACH transfers, if preprocessing_step is not required for connectors encountered in future, add the check
let router_data_and_should_continue_payment = match payment_data.get_payment_method_data() {
Some(domain::PaymentMethodData::BankTransfer(_)) => (router_data, should_continue_payment),
Some(domain::PaymentMethodData::Wallet(_)) => {
if is_preprocessing_required_for_wallets(connector.connector_name.to_string()) {
(
router_data.preprocessing_steps(state, connector).await?,
false,
)
} else if connector.connector_name == router_types::Connector::Paysafe {
match payment_data.get_payment_method_data() {
Some(domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(_))) => {
router_data = router_data.preprocessing_steps(state, connector).await?;
let is_error_in_response = router_data.response.is_err();
(router_data, !is_error_in_response)
}
_ => (router_data, should_continue_payment),
}
} else {
(router_data, should_continue_payment)
}
}
Some(domain::PaymentMethodData::Card(_)) => {
if connector.connector_name == router_types::Connector::Payme
&& !matches!(format!("{operation:?}").as_str(), "CompleteAuthorize")
{
router_data = router_data.preprocessing_steps(state, connector).await?;
let is_error_in_response = router_data.response.is_err();
// If is_error_in_response is true, should_continue_payment should be false, we should throw the error
(router_data, !is_error_in_response)
} else if connector.connector_name == router_types::Connector::Nmi
&& !matches!(format!("{operation:?}").as_str(), "CompleteAuthorize")
&& router_data.auth_type == storage_enums::AuthenticationType::ThreeDs
&& !matches!(
payment_data
.get_payment_attempt()
.external_three_ds_authentication_attempted,
Some(true)
)
{
router_data = router_data.preprocessing_steps(state, connector).await?;
(router_data, false)
} else if connector.connector_name == router_types::Connector::Paysafe
&& router_data.auth_type == storage_enums::AuthenticationType::NoThreeDs
{
router_data = router_data.preprocessing_steps(state, connector).await?;
let is_error_in_response = router_data.response.is_err();
// If is_error_in_response is true, should_continue_payment should be false, we should throw the error
(router_data, !is_error_in_response)
} else if (connector.connector_name == router_types::Connector::Cybersource
|| connector.connector_name == router_types::Connector::Barclaycard)
&& is_operation_complete_authorize(&operation)
&& router_data.auth_type == storage_enums::AuthenticationType::ThreeDs
{
router_data = router_data.preprocessing_steps(state, connector).await?;
// Should continue the flow only if no redirection_data is returned else a response with redirection form shall be returned
let should_continue = matches!(
router_data.response,
Ok(router_types::PaymentsResponseData::TransactionResponse {
ref redirection_data,
..
}) if redirection_data.is_none()
) && router_data.status
!= common_enums::AttemptStatus::AuthenticationFailed;
(router_data, should_continue)
} else if router_data.auth_type == common_enums::AuthenticationType::ThreeDs
&& ((connector.connector_name == router_types::Connector::Nexixpay
&& is_operation_complete_authorize(&operation))
|| (((connector.connector_name == router_types::Connector::Nuvei && {
#[cfg(feature = "v1")]
{
payment_data
.get_payment_intent()
.request_external_three_ds_authentication
!= Some(true)
}
#[cfg(feature = "v2")]
{
payment_data
.get_payment_intent()
.request_external_three_ds_authentication
!= Some(true).into()
}
}) || connector.connector_name == router_types::Connector::Shift4)
&& !is_operation_complete_authorize(&operation)))
{
router_data = router_data.preprocessing_steps(state, connector).await?;
(router_data, should_continue_payment)
} else if connector.connector_name == router_types::Connector::Xendit
&& is_operation_confirm(&operation)
{
match payment_data.get_payment_intent().split_payments {
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(_),
)) => {
router_data = router_data.preprocessing_steps(state, connector).await?;
let is_error_in_response = router_data.response.is_err();
(router_data, !is_error_in_response)
}
_ => (router_data, should_continue_payment),
}
} else if connector.connector_name == router_types::Connector::Redsys
&& router_data.auth_type == common_enums::AuthenticationType::ThreeDs
&& is_operation_confirm(&operation)
{
router_data = router_data.preprocessing_steps(state, connector).await?;
let should_continue = match router_data.response {
Ok(router_types::PaymentsResponseData::TransactionResponse {
ref connector_metadata,
..
}) => {
let three_ds_invoke_data: Option<
api_models::payments::PaymentsConnectorThreeDsInvokeData,
> = connector_metadata.clone().and_then(|metadata| {
metadata
.parse_value("PaymentsConnectorThreeDsInvokeData")
.ok() // "ThreeDsInvokeData was not found; proceeding with the payment flow without triggering the ThreeDS invoke action"
});
three_ds_invoke_data.is_none()
}
_ => false,
};
(router_data, should_continue)
} else {
(router_data, should_continue_payment)
}
}
Some(domain::PaymentMethodData::GiftCard(gift_card_data)) => {
if connector.connector_name == router_types::Connector::Adyen
&& matches!(gift_card_data.deref(), domain::GiftCardData::Givex(..))
{
router_data = router_data.preprocessing_steps(state, connector).await?;
let is_error_in_response = router_data.response.is_err();
// If is_error_in_response is true, should_continue_payment should be false, we should throw the error
(router_data, !is_error_in_response)
} else {
(router_data, should_continue_payment)
}
}
Some(domain::PaymentMethodData::BankDebit(_)) => {
if connector.connector_name == router_types::Connector::Gocardless
|| connector.connector_name == router_types::Connector::Nordea
{
router_data = router_data.preprocessing_steps(state, connector).await?;
let is_error_in_response = router_data.response.is_err();
// If is_error_in_response is true, should_continue_payment should be false, we should throw the error
(router_data, !is_error_in_response)
} else {
(router_data, should_continue_payment)
}
}
_ => {
// 3DS validation for paypal cards after verification (authorize call)
if connector.connector_name == router_types::Connector::Paypal
&& payment_data.get_payment_attempt().get_payment_method()
== Some(storage_enums::PaymentMethod::Card)
&& matches!(format!("{operation:?}").as_str(), "CompleteAuthorize")
{
router_data = router_data.preprocessing_steps(state, connector).await?;
let is_error_in_response = router_data.response.is_err();
// If is_error_in_response is true, should_continue_payment should be false, we should throw the error
(router_data, !is_error_in_response)
} else {
(router_data, should_continue_payment)
}
}
};
Ok(router_data_and_should_continue_payment)
}
#[cfg(feature = "v1")]
async fn complete_confirmation_for_click_to_pay_if_required<F, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &D,
) -> RouterResult<()>
where
F: Send + Clone + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let payment_attempt = payment_data.get_payment_attempt();
let payment_intent = payment_data.get_payment_intent();
let service_details = payment_data.get_click_to_pay_service_details();
let authentication = payment_data.get_authentication();
let should_do_uas_confirmation_call = service_details
.as_ref()
.map(|details| details.is_network_confirmation_call_required())
.unwrap_or(false);
if should_do_uas_confirmation_call
&& (payment_intent.status == storage_enums::IntentStatus::Succeeded
|| payment_intent.status == storage_enums::IntentStatus::Failed)
{
let authentication_connector_id = authentication
.as_ref()
.and_then(|auth| auth.authentication.merchant_connector_id.clone())
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to get authentication connector id from authentication table",
)?;
let key_manager_state = &(state).into();
let key_store = merchant_context.get_merchant_key_store();
let merchant_id = merchant_context.get_merchant_account().get_id();
let connector_mca = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
&authentication_connector_id,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: authentication_connector_id.get_string_repr().to_string(),
})?;
let payment_method = payment_attempt
.payment_method
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get payment method from payment attempt")?;
ClickToPay::confirmation(
state,
payment_attempt.authentication_id.as_ref(),
payment_intent.currency,
payment_attempt.status,
service_details.cloned(),
&helpers::MerchantConnectorAccountType::DbVal(Box::new(connector_mca.clone())),
&connector_mca.connector_name,
payment_method,
payment_attempt.net_amount.get_order_amount(),
Some(&payment_intent.payment_id),
merchant_id,
)
.await?;
Ok(())
} else {
Ok(())
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn complete_postprocessing_steps_if_required<F, Q, RouterDReq, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_conn_account: &helpers::MerchantConnectorAccountType,
connector: &api::ConnectorData,
payment_data: &mut D,
_operation: &BoxedOperation<'_, F, Q, D>,
header_payload: Option<HeaderPayload>,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
{
let mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
customer,
merchant_conn_account,
None,
header_payload,
payment_data.get_payment_attempt().payment_method,
payment_data.get_payment_attempt().payment_method_type,
)
.await?;
match payment_data.get_payment_method_data() {
Some(domain::PaymentMethodData::OpenBanking(domain::OpenBankingData::OpenBankingPIS {
..
})) => {
if connector.connector_name == router_types::Connector::Plaid {
router_data = router_data.postprocessing_steps(state, connector).await?;
let token = if let Ok(ref res) = router_data.response {
match res {
router_types::PaymentsResponseData::PostProcessingResponse {
session_token,
} => session_token
.as_ref()
.map(|token| api::SessionToken::OpenBanking(token.clone())),
_ => None,
}
} else {
None
};
if let Some(t) = token {
payment_data.push_sessions_token(t);
}
Ok(router_data)
} else {
Ok(router_data)
}
}
_ => Ok(router_data),
}
}
pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool {
connector_name == *"trustpay" || connector_name == *"payme"
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn construct_profile_id_and_get_mca<'a, F, D>(
state: &'a SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &D,
connector_name: &str,
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
_should_validate: bool,
) -> RouterResult<helpers::MerchantConnectorAccountType>
where
F: Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
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 = "v2")]
let profile_id = payment_data.get_payment_intent().profile_id.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
payment_data.get_creds_identifier(),
merchant_context.get_merchant_key_store(),
&profile_id,
connector_name,
merchant_connector_id,
)
.await?;
Ok(merchant_connector_account)
}
#[cfg(feature = "v2")]
fn is_payment_method_tokenization_enabled_for_connector(
state: &SessionState,
connector_name: &str,
payment_method: storage::enums::PaymentMethod,
payment_method_type: Option<storage::enums::PaymentMethodType>,
mandate_flow_enabled: storage_enums::FutureUsage,
) -> RouterResult<bool> {
let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name);
Ok(connector_tokenization_filter
.map(|connector_filter| {
connector_filter
.payment_method
.clone()
.contains(&payment_method)
&& is_payment_method_type_allowed_for_connector(
payment_method_type,
connector_filter.payment_method_type.clone(),
)
&& is_payment_flow_allowed_for_connector(
mandate_flow_enabled,
connector_filter.flow.clone(),
)
})
.unwrap_or(false))
}
// Determines connector tokenization eligibility: if no flow restriction, allow for one-off/CIT with raw cards; if flow = “mandates”, only allow MIT off-session with stored tokens.
#[cfg(feature = "v2")]
fn is_payment_flow_allowed_for_connector(
mandate_flow_enabled: storage_enums::FutureUsage,
payment_flow: Option<PaymentFlow>,
) -> bool {
if payment_flow.is_none() {
true
} else {
matches!(payment_flow, Some(PaymentFlow::Mandates))
&& matches!(mandate_flow_enabled, storage_enums::FutureUsage::OffSession)
}
}
#[cfg(feature = "v1")]
fn is_payment_method_tokenization_enabled_for_connector(
state: &SessionState,
connector_name: &str,
payment_method: storage::enums::PaymentMethod,
payment_method_type: Option<storage::enums::PaymentMethodType>,
payment_method_token: Option<&PaymentMethodToken>,
mandate_flow_enabled: Option<storage_enums::FutureUsage>,
) -> RouterResult<bool> {
let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name);
Ok(connector_tokenization_filter
.map(|connector_filter| {
connector_filter
.payment_method
.clone()
.contains(&payment_method)
&& is_payment_method_type_allowed_for_connector(
payment_method_type,
connector_filter.payment_method_type.clone(),
)
&& is_apple_pay_pre_decrypt_type_connector_tokenization(
payment_method_type,
payment_method_token,
connector_filter.apple_pay_pre_decrypt_flow.clone(),
)
&& is_google_pay_pre_decrypt_type_connector_tokenization(
payment_method_type,
payment_method_token,
connector_filter.google_pay_pre_decrypt_flow.clone(),
)
&& is_payment_flow_allowed_for_connector(
mandate_flow_enabled,
connector_filter.flow.clone(),
)
})
.unwrap_or(false))
}
#[cfg(feature = "v1")]
fn is_payment_flow_allowed_for_connector(
mandate_flow_enabled: Option<storage_enums::FutureUsage>,
payment_flow: Option<PaymentFlow>,
) -> bool {
if payment_flow.is_none() {
true
} else {
matches!(payment_flow, Some(PaymentFlow::Mandates))
&& matches!(
mandate_flow_enabled,
Some(storage_enums::FutureUsage::OffSession)
)
}
}
fn is_apple_pay_pre_decrypt_type_connector_tokenization(
payment_method_type: Option<storage::enums::PaymentMethodType>,
payment_method_token: Option<&PaymentMethodToken>,
apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>,
) -> bool {
match (payment_method_type, payment_method_token) {
(
Some(storage::enums::PaymentMethodType::ApplePay),
Some(PaymentMethodToken::ApplePayDecrypt(..)),
) => !matches!(
apple_pay_pre_decrypt_flow_filter,
Some(ApplePayPreDecryptFlow::NetworkTokenization)
),
_ => true,
}
}
fn is_google_pay_pre_decrypt_type_connector_tokenization(
payment_method_type: Option<storage::enums::PaymentMethodType>,
payment_method_token: Option<&PaymentMethodToken>,
google_pay_pre_decrypt_flow_filter: Option<GooglePayPreDecryptFlow>,
) -> bool {
if let (
Some(storage::enums::PaymentMethodType::GooglePay),
Some(PaymentMethodToken::GooglePayDecrypt(..)),
) = (payment_method_type, payment_method_token)
{
!matches!(
google_pay_pre_decrypt_flow_filter,
Some(GooglePayPreDecryptFlow::NetworkTokenization)
)
} else {
// Always return true for non–Google Pay pre-decrypt cases,
// because the filter is only relevant for Google Pay pre-decrypt tokenization.
// Returning true ensures that other payment methods or token types are not blocked.
true
}
}
fn decide_apple_pay_flow(
state: &SessionState,
payment_method_type: Option<enums::PaymentMethodType>,
merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>,
) -> Option<domain::ApplePayFlow> {
payment_method_type.and_then(|pmt| match pmt {
enums::PaymentMethodType::ApplePay => {
check_apple_pay_metadata(state, merchant_connector_account)
}
_ => None,
})
}
fn check_apple_pay_metadata(
state: &SessionState,
merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>,
) -> Option<domain::ApplePayFlow> {
merchant_connector_account.and_then(|mca| {
let metadata = mca.get_metadata();
metadata.and_then(|apple_pay_metadata| {
let parsed_metadata = apple_pay_metadata
.clone()
.parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
apple_pay_metadata
.parse_value::<api_models::payments::ApplepaySessionTokenData>(
"ApplepaySessionTokenData",
)
.map(|old_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(
old_metadata.apple_pay,
)
})
})
.map_err(|error| {
logger::warn!(?error, "Failed to Parse Value to ApplepaySessionTokenData")
});
parsed_metadata.ok().map(|metadata| match metadata {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined,
) => match apple_pay_combined {
api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => {
domain::ApplePayFlow::Simplified(payments_api::PaymentProcessingDetails {
payment_processing_certificate: state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_ppc
.clone(),
payment_processing_certificate_key: state
.conf
.applepay_decrypt_keys
.get_inner()
.apple_pay_ppc_key
.clone(),
})
}
api_models::payments::ApplePayCombinedMetadata::Manual {
payment_request_data: _,
session_token_data,
} => {
if let Some(manual_payment_processing_details_at) =
session_token_data.payment_processing_details_at
{
match manual_payment_processing_details_at {
payments_api::PaymentProcessingDetailsAt::Hyperswitch(
payment_processing_details,
) => domain::ApplePayFlow::Simplified(payment_processing_details),
payments_api::PaymentProcessingDetailsAt::Connector => {
domain::ApplePayFlow::Manual
}
}
} else {
domain::ApplePayFlow::Manual
}
}
},
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => {
domain::ApplePayFlow::Manual
}
})
})
})
}
fn get_google_pay_connector_wallet_details(
state: &SessionState,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> Option<GooglePayPaymentProcessingDetails> {
let google_pay_root_signing_keys = state
.conf
.google_pay_decrypt_keys
.as_ref()
.map(|google_pay_keys| google_pay_keys.google_pay_root_signing_keys.clone());
match merchant_connector_account.get_connector_wallets_details() {
Some(wallet_details) => {
let google_pay_wallet_details = wallet_details
.parse_value::<api_models::payments::GooglePayWalletDetails>(
"GooglePayWalletDetails",
)
.map_err(|error| {
logger::warn!(?error, "Failed to Parse Value to GooglePayWalletDetails")
});
google_pay_wallet_details
.ok()
.and_then(
|google_pay_wallet_details| {
match google_pay_wallet_details
.google_pay
.provider_details {
api_models::payments::GooglePayProviderDetails::GooglePayMerchantDetails(merchant_details) => {
match (
merchant_details
.merchant_info
.tokenization_specification
.parameters
.private_key,
google_pay_root_signing_keys,
merchant_details
.merchant_info
.tokenization_specification
.parameters
.recipient_id,
) {
(Some(google_pay_private_key), Some(google_pay_root_signing_keys), Some(google_pay_recipient_id)) => {
Some(GooglePayPaymentProcessingDetails {
google_pay_private_key,
google_pay_root_signing_keys,
google_pay_recipient_id
})
}
_ => {
logger::warn!("One or more of the following fields are missing in GooglePayMerchantDetails: google_pay_private_key, google_pay_root_signing_keys, google_pay_recipient_id");
None
}
}
}
}
}
)
}
None => None,
}
}
fn is_payment_method_type_allowed_for_connector(
current_pm_type: Option<storage::enums::PaymentMethodType>,
pm_type_filter: Option<PaymentMethodTypeTokenFilter>,
) -> bool {
match (current_pm_type).zip(pm_type_filter) {
Some((pm_type, type_filter)) => match type_filter {
PaymentMethodTypeTokenFilter::AllAccepted => true,
PaymentMethodTypeTokenFilter::EnableOnly(enabled) => enabled.contains(&pm_type),
PaymentMethodTypeTokenFilter::DisableOnly(disabled) => !disabled.contains(&pm_type),
},
None => true, // Allow all types if payment_method_type is not present
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn decide_payment_method_tokenize_action(
state: &SessionState,
connector_name: &str,
payment_method: storage::enums::PaymentMethod,
payment_intent_data: payments::PaymentIntent,
pm_parent_token: Option<&str>,
is_connector_tokenization_enabled: bool,
) -> RouterResult<TokenizationAction> {
if matches!(
payment_intent_data.split_payments,
Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(_))
) {
Ok(TokenizationAction::TokenizeInConnector)
} else {
match pm_parent_token {
None => Ok(if is_connector_tokenization_enabled {
TokenizationAction::TokenizeInConnectorAndRouter
} else {
TokenizationAction::TokenizeInRouter
}),
Some(token) => {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!(
"pm_token_{}_{}_{}",
token.to_owned(),
payment_method,
connector_name
);
let connector_token_option = redis_conn
.get_key::<Option<String>>(&key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?;
match connector_token_option {
Some(connector_token) => {
Ok(TokenizationAction::ConnectorToken(connector_token))
}
None => Ok(if is_connector_tokenization_enabled {
TokenizationAction::TokenizeInConnectorAndRouter
} else {
TokenizationAction::TokenizeInRouter
}),
}
}
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct PazePaymentProcessingDetails {
pub paze_private_key: Secret<String>,
pub paze_private_key_passphrase: Secret<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GooglePayPaymentProcessingDetails {
pub google_pay_private_key: Secret<String>,
pub google_pay_root_signing_keys: Secret<String>,
pub google_pay_recipient_id: Secret<String>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub enum TokenizationAction {
TokenizeInRouter,
TokenizeInConnector,
TokenizeInConnectorAndRouter,
ConnectorToken(String),
SkipConnectorTokenization,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub enum TokenizationAction {
TokenizeInConnector,
SkipConnectorTokenization,
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn get_connector_tokenization_action_when_confirm_true<F, Req, D>(
state: &SessionState,
operation: &BoxedOperation<'_, F, Req, D>,
payment_data: &mut D,
validate_result: &operations::ValidateResult,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(D, TokenizationAction)>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let connector = payment_data.get_payment_attempt().connector.to_owned();
let is_mandate = payment_data
.get_mandate_id()
.as_ref()
.and_then(|inner| inner.mandate_reference_id.as_ref())
.map(|mandate_reference| match mandate_reference {
api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true,
api_models::payments::MandateReferenceId::NetworkMandateId(_)
| api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_) => false,
})
.unwrap_or(false);
let payment_data_and_tokenization_action = match connector {
Some(_) if is_mandate => (
payment_data.to_owned(),
TokenizationAction::SkipConnectorTokenization,
),
Some(connector) if is_operation_confirm(&operation) => {
let payment_method = payment_data
.get_payment_attempt()
.payment_method
.get_required_value("payment_method")?;
let payment_method_type = payment_data.get_payment_attempt().payment_method_type;
let mandate_flow_enabled = payment_data
.get_payment_attempt()
.setup_future_usage_applied;
let is_connector_tokenization_enabled =
is_payment_method_tokenization_enabled_for_connector(
state,
&connector,
payment_method,
payment_method_type,
payment_data.get_payment_method_token(),
mandate_flow_enabled,
)?;
let payment_method_action = decide_payment_method_tokenize_action(
state,
&connector,
payment_method,
payment_data.get_payment_intent().clone(),
payment_data.get_token(),
is_connector_tokenization_enabled,
)
.await?;
let connector_tokenization_action = match payment_method_action {
TokenizationAction::TokenizeInRouter => {
let (_operation, payment_method_data, pm_id) = operation
.to_domain()?
.make_pm_data(
state,
payment_data,
validate_result.storage_scheme,
merchant_key_store,
customer,
business_profile,
should_retry_with_pan,
)
.await?;
payment_data.set_payment_method_data(payment_method_data);
payment_data.set_payment_method_id_in_attempt(pm_id);
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::TokenizeInConnector => TokenizationAction::TokenizeInConnector,
TokenizationAction::TokenizeInConnectorAndRouter => {
let (_operation, payment_method_data, pm_id) = operation
.to_domain()?
.make_pm_data(
state,
payment_data,
validate_result.storage_scheme,
merchant_key_store,
customer,
business_profile,
should_retry_with_pan,
)
.await?;
payment_data.set_payment_method_data(payment_method_data);
payment_data.set_payment_method_id_in_attempt(pm_id);
TokenizationAction::TokenizeInConnector
}
TokenizationAction::ConnectorToken(token) => {
payment_data.set_pm_token(token);
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::SkipConnectorTokenization => {
TokenizationAction::SkipConnectorTokenization
}
};
(payment_data.to_owned(), connector_tokenization_action)
}
_ => (
payment_data.to_owned(),
TokenizationAction::SkipConnectorTokenization,
),
};
Ok(payment_data_and_tokenization_action)
}
#[cfg(feature = "v2")]
pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, D>(
state: &SessionState,
operation: &BoxedOperation<'_, F, Req, D>,
payment_data: &mut D,
validate_result: &operations::ValidateResult,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
) -> RouterResult<D>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
todo!()
}
#[cfg(feature = "v1")]
pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F, Req, D>(
state: &SessionState,
operation: &BoxedOperation<'_, F, Req, D>,
payment_data: &mut D,
validate_result: &operations::ValidateResult,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
) -> RouterResult<D>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
// On confirm is false and only router related
let is_external_authentication_requested = payment_data
.get_payment_intent()
.request_external_three_ds_authentication;
let payment_data =
if !is_operation_confirm(operation) || is_external_authentication_requested == Some(true) {
let (_operation, payment_method_data, pm_id) = operation
.to_domain()?
.make_pm_data(
state,
payment_data,
validate_result.storage_scheme,
merchant_key_store,
customer,
business_profile,
false,
)
.await?;
payment_data.set_payment_method_data(payment_method_data);
if let Some(payment_method_id) = pm_id {
payment_data.set_payment_method_id_in_attempt(Some(payment_method_id));
}
payment_data
} else {
payment_data
};
Ok(payment_data.to_owned())
}
#[derive(Clone)]
pub struct MandateConnectorDetails {
pub connector: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
}
#[derive(Clone)]
pub struct PaymentData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: storage::PaymentIntent,
pub payment_attempt: storage::PaymentAttempt,
pub multiple_capture_data: Option<types::MultipleCaptureData>,
pub amount: api::Amount,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub mandate_connector: Option<MandateConnectorDetails>,
pub currency: storage_enums::Currency,
pub setup_mandate: Option<MandateData>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub address: PaymentAddress,
pub token: Option<String>,
pub token_data: Option<storage::PaymentTokenData>,
pub confirm: Option<bool>,
pub force_sync: Option<bool>,
pub all_keys_required: Option<bool>,
pub payment_method_data: Option<domain::PaymentMethodData>,
pub payment_method_token: Option<PaymentMethodToken>,
pub payment_method_info: Option<domain::PaymentMethod>,
pub refunds: Vec<diesel_refund::Refund>,
pub disputes: Vec<storage::Dispute>,
pub attempts: Option<Vec<storage::PaymentAttempt>>,
pub sessions_token: Vec<api::SessionToken>,
pub card_cvc: Option<Secret<String>>,
pub email: Option<pii::Email>,
pub creds_identifier: Option<String>,
pub pm_token: Option<String>,
pub connector_customer_id: Option<String>,
pub recurring_mandate_payment_data:
Option<hyperswitch_domain_models::router_data::RecurringMandatePaymentData>,
pub ephemeral_key: Option<ephemeral_key::EphemeralKey>,
pub redirect_response: Option<api_models::payments::RedirectResponse>,
pub surcharge_details: Option<types::SurchargeDetails>,
pub frm_message: Option<FraudCheck>,
pub payment_link_data: Option<api_models::payments::PaymentLinkResponse>,
pub incremental_authorization_details: Option<IncrementalAuthorizationDetails>,
pub authorizations: Vec<diesel_models::authorization::Authorization>,
pub authentication: Option<domain::authentication::AuthenticationStore>,
pub recurring_details: Option<RecurringDetails>,
pub poll_config: Option<router_types::PollConfig>,
pub tax_data: Option<TaxData>,
pub session_id: Option<String>,
pub service_details: Option<api_models::payments::CtpServiceDetails>,
pub card_testing_guard_data:
Option<hyperswitch_domain_models::card_testing_guard_data::CardTestingGuardData>,
pub vault_operation: Option<domain_payments::VaultOperation>,
pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>,
pub whole_connector_response: Option<Secret<String>>,
pub is_manual_retry_enabled: Option<bool>,
pub is_l2_l3_enabled: bool,
}
#[cfg(feature = "v1")]
#[derive(Clone)]
pub struct PaymentEligibilityData {
pub payment_method_data: Option<domain::PaymentMethodData>,
pub payment_intent: storage::PaymentIntent,
pub browser_info: Option<pii::SecretSerdeValue>,
}
#[cfg(feature = "v1")]
impl PaymentEligibilityData {
pub async fn from_request(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payments_eligibility_request: &api_models::payments::PaymentsEligibilityRequest,
) -> CustomResult<Self, errors::ApiErrorResponse> {
let key_manager_state = &(state).into();
let payment_method_data = payments_eligibility_request
.payment_method_data
.payment_method_data
.clone()
.map(domain::PaymentMethodData::from);
let browser_info = payments_eligibility_request
.browser_info
.clone()
.map(|browser_info| {
serde_json::to_value(browser_info)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode payout method data")
})
.transpose()?
.map(pii::SecretSerdeValue::new);
let payment_intent = state
.store
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payments_eligibility_request.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
Ok(Self {
payment_method_data,
browser_info,
payment_intent,
})
}
}
#[derive(Clone, serde::Serialize, Debug)]
pub struct TaxData {
pub shipping_details: hyperswitch_domain_models::address::Address,
pub payment_method_type: enums::PaymentMethodType,
}
#[derive(Clone, serde::Serialize, Debug)]
pub struct PaymentEvent {
payment_intent: storage::PaymentIntent,
payment_attempt: storage::PaymentAttempt,
}
impl<F: Clone> PaymentData<F> {
// Get the method by which a card is discovered during a payment
#[cfg(feature = "v1")]
fn get_card_discovery_for_card_payment_method(&self) -> Option<common_enums::CardDiscovery> {
match self.payment_attempt.payment_method {
Some(storage_enums::PaymentMethod::Card) => {
if self
.token_data
.as_ref()
.map(storage::PaymentTokenData::is_permanent_card)
.unwrap_or(false)
{
Some(common_enums::CardDiscovery::SavedCard)
} else if self.service_details.is_some() {
Some(common_enums::CardDiscovery::ClickToPay)
} else {
Some(common_enums::CardDiscovery::Manual)
}
}
_ => None,
}
}
fn to_event(&self) -> PaymentEvent {
PaymentEvent {
payment_intent: self.payment_intent.clone(),
payment_attempt: self.payment_attempt.clone(),
}
}
}
impl EventInfo for PaymentEvent {
type Data = Self;
fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> {
Ok(self.clone())
}
fn key(&self) -> String {
"payment".to_string()
}
}
#[derive(Debug, Default, Clone)]
pub struct IncrementalAuthorizationDetails {
pub additional_amount: MinorUnit,
pub total_amount: MinorUnit,
pub reason: Option<String>,
pub authorization_id: Option<String>,
}
pub async fn get_payment_link_response_from_id(
state: &SessionState,
payment_link_id: &str,
) -> CustomResult<api_models::payments::PaymentLinkResponse, errors::ApiErrorResponse> {
let db = &*state.store;
let payment_link_object = db
.find_payment_link_by_payment_link_id(payment_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
Ok(api_models::payments::PaymentLinkResponse {
link: payment_link_object.link_to_pay.clone(),
secure_link: payment_link_object.secure_link,
payment_link_id: payment_link_object.payment_link_id,
})
}
#[cfg(feature = "v1")]
pub fn if_not_create_change_operation<'a, Op, F>(
status: storage_enums::IntentStatus,
confirm: Option<bool>,
current: &'a Op,
) -> BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>
where
F: Send + Clone + Sync,
Op: Operation<F, api::PaymentsRequest, Data = PaymentData<F>> + Send + Sync,
&'a Op: Operation<F, api::PaymentsRequest, Data = PaymentData<F>>,
PaymentStatus: Operation<F, api::PaymentsRequest, Data = PaymentData<F>>,
&'a PaymentStatus: Operation<F, api::PaymentsRequest, Data = PaymentData<F>>,
{
if confirm.unwrap_or(false) {
Box::new(PaymentConfirm)
} else {
match status {
storage_enums::IntentStatus::RequiresConfirmation
| storage_enums::IntentStatus::RequiresCustomerAction
| storage_enums::IntentStatus::RequiresPaymentMethod => Box::new(current),
_ => Box::new(&PaymentStatus),
}
}
}
#[cfg(feature = "v1")]
pub fn is_confirm<'a, F: Clone + Send, R, Op>(
operation: &'a Op,
confirm: Option<bool>,
) -> BoxedOperation<'a, F, R, PaymentData<F>>
where
PaymentConfirm: Operation<F, R, Data = PaymentData<F>>,
&'a PaymentConfirm: Operation<F, R, Data = PaymentData<F>>,
Op: Operation<F, R, Data = PaymentData<F>> + Send + Sync,
&'a Op: Operation<F, R, Data = PaymentData<F>>,
{
if confirm.unwrap_or(false) {
Box::new(&PaymentConfirm)
} else {
Box::new(operation)
}
}
#[cfg(feature = "v1")]
pub fn should_call_connector<Op: Debug, F: Clone, D>(operation: &Op, payment_data: &D) -> bool
where
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
match format!("{operation:?}").as_str() {
"PaymentConfirm" => true,
"PaymentStart" => {
!matches!(
payment_data.get_payment_intent().status,
storage_enums::IntentStatus::Failed | storage_enums::IntentStatus::Succeeded
) && payment_data
.get_payment_attempt()
.authentication_data
.is_none()
}
"PaymentStatus" => {
payment_data.get_all_keys_required().unwrap_or(false)
|| matches!(
payment_data.get_payment_intent().status,
storage_enums::IntentStatus::Processing
| storage_enums::IntentStatus::RequiresCustomerAction
| storage_enums::IntentStatus::RequiresMerchantAction
| storage_enums::IntentStatus::RequiresCapture
| storage_enums::IntentStatus::PartiallyCapturedAndCapturable
) && payment_data.get_force_sync().unwrap_or(false)
}
"PaymentCancel" => matches!(
payment_data.get_payment_intent().status,
storage_enums::IntentStatus::RequiresCapture
| storage_enums::IntentStatus::PartiallyCapturedAndCapturable
),
"PaymentCancelPostCapture" => matches!(
payment_data.get_payment_intent().status,
storage_enums::IntentStatus::Succeeded
| storage_enums::IntentStatus::PartiallyCaptured
| storage_enums::IntentStatus::PartiallyCapturedAndCapturable
),
"PaymentCapture" => {
matches!(
payment_data.get_payment_intent().status,
storage_enums::IntentStatus::RequiresCapture
| storage_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| storage_enums::IntentStatus::PartiallyCapturedAndCapturable
) || (matches!(
payment_data.get_payment_intent().status,
storage_enums::IntentStatus::Processing
) && matches!(
payment_data.get_capture_method(),
Some(storage_enums::CaptureMethod::ManualMultiple)
))
}
"CompleteAuthorize" => true,
"PaymentApprove" => true,
"PaymentReject" => true,
"PaymentSession" => true,
"PaymentSessionUpdate" => true,
"PaymentPostSessionTokens" => true,
"PaymentUpdateMetadata" => true,
"PaymentExtendAuthorization" => matches!(
payment_data.get_payment_intent().status,
storage_enums::IntentStatus::RequiresCapture
| storage_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
),
"PaymentIncrementalAuthorization" => matches!(
payment_data.get_payment_intent().status,
storage_enums::IntentStatus::RequiresCapture
),
_ => false,
}
}
pub fn is_operation_confirm<Op: Debug>(operation: &Op) -> bool {
matches!(format!("{operation:?}").as_str(), "PaymentConfirm")
}
pub fn is_operation_complete_authorize<Op: Debug>(operation: &Op) -> bool {
matches!(format!("{operation:?}").as_str(), "CompleteAuthorize")
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn list_payments(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: api::PaymentListConstraints,
) -> RouterResponse<api::PaymentListResponse> {
helpers::validate_payment_list_request(&constraints)?;
let merchant_id = merchant_context.get_merchant_account().get_id();
let db = state.store.as_ref();
let payment_intents = helpers::filter_by_constraints(
&state,
&(constraints, profile_id_list).try_into()?,
merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let collected_futures = payment_intents.into_iter().map(|pi| {
async {
match db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&pi.payment_id,
merchant_id,
&pi.active_attempt.get_id(),
// since OLAP doesn't have KV. Force to get the data from PSQL.
storage_enums::MerchantStorageScheme::PostgresOnly,
)
.await
{
Ok(pa) => Some(Ok((pi, pa))),
Err(error) => {
if matches!(
error.current_context(),
errors::StorageError::ValueNotFound(_)
) {
logger::warn!(
?error,
"payment_attempts missing for payment_id : {:?}",
pi.payment_id,
);
return None;
}
Some(Err(error))
}
}
}
});
//If any of the response are Err, we will get Result<Err(_)>
let pi_pa_tuple_vec: Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _> =
join_all(collected_futures)
.await
.into_iter()
.flatten() //Will ignore `None`, will only flatten 1 level
.collect::<Result<Vec<(storage::PaymentIntent, storage::PaymentAttempt)>, _>>();
//Will collect responses in same order async, leading to sorted responses
//Converting Intent-Attempt array to Response if no error
let data: Vec<api::PaymentsResponse> = pi_pa_tuple_vec
.change_context(errors::ApiErrorResponse::InternalServerError)?
.into_iter()
.map(ForeignFrom::foreign_from)
.collect();
Ok(services::ApplicationResponse::Json(
api::PaymentListResponse {
size: data.len(),
data,
},
))
}
#[cfg(all(feature = "v2", feature = "olap"))]
pub async fn list_payments(
state: SessionState,
merchant_context: domain::MerchantContext,
constraints: api::PaymentListConstraints,
) -> RouterResponse<payments_api::PaymentListResponse> {
common_utils::metrics::utils::record_operation_time(
async {
let limit = &constraints.limit;
helpers::validate_payment_list_request_for_joins(*limit)?;
let db: &dyn StorageInterface = state.store.as_ref();
let fetch_constraints = constraints.clone().into();
let list: Vec<(storage::PaymentIntent, Option<storage::PaymentAttempt>)> = db
.get_filtered_payment_intents_attempt(
&(&state).into(),
merchant_context.get_merchant_account().get_id(),
&fetch_constraints,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let data: Vec<api_models::payments::PaymentsListResponseItem> =
list.into_iter().map(ForeignFrom::foreign_from).collect();
let active_attempt_ids = db
.get_filtered_active_attempt_ids_for_total_count(
merchant_context.get_merchant_account().get_id(),
&fetch_constraints,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while retrieving active_attempt_ids for merchant")?;
let total_count = if constraints.has_no_attempt_filters() {
i64::try_from(active_attempt_ids.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while converting from usize to i64")
} else {
let active_attempt_ids = active_attempt_ids
.into_iter()
.flatten()
.collect::<Vec<String>>();
db.get_total_count_of_filtered_payment_attempts(
merchant_context.get_merchant_account().get_id(),
&active_attempt_ids,
constraints.connector,
constraints.payment_method_type,
constraints.payment_method_subtype,
constraints.authentication_type,
constraints.merchant_connector_id,
constraints.card_network,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while retrieving total count of payment attempts")
}?;
Ok(services::ApplicationResponse::Json(
api_models::payments::PaymentListResponse {
count: data.len(),
total_count,
data,
},
))
},
&metrics::PAYMENT_LIST_LATENCY,
router_env::metric_attributes!((
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
)),
)
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn apply_filters_on_payments(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: api::PaymentListFilterConstraints,
) -> RouterResponse<api::PaymentListResponseV2> {
common_utils::metrics::utils::record_operation_time(
async {
let limit = &constraints.limit;
helpers::validate_payment_list_request_for_joins(*limit)?;
let db: &dyn StorageInterface = state.store.as_ref();
let pi_fetch_constraints = (constraints.clone(), profile_id_list.clone()).try_into()?;
let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db
.get_filtered_payment_intents_attempt(
&(&state).into(),
merchant_context.get_merchant_account().get_id(),
&pi_fetch_constraints,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let data: Vec<api::PaymentsResponse> =
list.into_iter().map(ForeignFrom::foreign_from).collect();
let active_attempt_ids = db
.get_filtered_active_attempt_ids_for_total_count(
merchant_context.get_merchant_account().get_id(),
&pi_fetch_constraints,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let total_count = if constraints.has_no_attempt_filters() {
i64::try_from(active_attempt_ids.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while converting from usize to i64")
} else {
db.get_total_count_of_filtered_payment_attempts(
merchant_context.get_merchant_account().get_id(),
&active_attempt_ids,
constraints.connector,
constraints.payment_method,
constraints.payment_method_type,
constraints.authentication_type,
constraints.merchant_connector_id,
constraints.card_network,
constraints.card_discovery,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
}?;
Ok(services::ApplicationResponse::Json(
api::PaymentListResponseV2 {
count: data.len(),
total_count,
data,
},
))
},
&metrics::PAYMENT_LIST_LATENCY,
router_env::metric_attributes!((
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
)),
)
.await
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn get_filters_for_payments(
state: SessionState,
merchant_context: domain::MerchantContext,
time_range: common_utils::types::TimeRange,
) -> RouterResponse<api::PaymentListFilters> {
let db = state.store.as_ref();
let pi = db
.filter_payment_intents_by_time_range_constraints(
&(&state).into(),
merchant_context.get_merchant_account().get_id(),
&time_range,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let filters = db
.get_filters_for_payments(
pi.as_slice(),
merchant_context.get_merchant_account().get_id(),
// since OLAP doesn't have KV. Force to get the data from PSQL.
storage_enums::MerchantStorageScheme::PostgresOnly,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
Ok(services::ApplicationResponse::Json(
api::PaymentListFilters {
connector: filters.connector,
currency: filters.currency,
status: filters.status,
payment_method: filters.payment_method,
payment_method_type: filters.payment_method_type,
authentication_type: filters.authentication_type,
},
))
}
#[cfg(feature = "olap")]
pub async fn get_payment_filters(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<id_type::ProfileId>>,
) -> RouterResponse<api::PaymentListFiltersV2> {
let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
super::admin::list_payment_connectors(
state,
merchant_context.get_merchant_account().get_id().to_owned(),
profile_id_list,
)
.await?
{
data
} else {
return Err(errors::ApiErrorResponse::InternalServerError.into());
};
let mut connector_map: HashMap<String, Vec<MerchantConnectorInfo>> = HashMap::new();
let mut payment_method_types_map: HashMap<
enums::PaymentMethod,
HashSet<enums::PaymentMethodType>,
> = HashMap::new();
// populate connector map
merchant_connector_accounts
.iter()
.filter_map(|merchant_connector_account| {
merchant_connector_account
.connector_label
.as_ref()
.map(|label| {
let info = merchant_connector_account.to_merchant_connector_info(label);
(merchant_connector_account.get_connector_name(), info)
})
})
.for_each(|(connector_name, info)| {
connector_map
.entry(connector_name.to_string())
.or_default()
.push(info);
});
// populate payment method type map
merchant_connector_accounts
.iter()
.flat_map(|merchant_connector_account| {
merchant_connector_account.payment_methods_enabled.as_ref()
})
.map(|payment_methods_enabled| {
payment_methods_enabled
.iter()
.filter_map(|payment_method_enabled| {
payment_method_enabled
.get_payment_method_type()
.map(|types_vec| {
(
payment_method_enabled.get_payment_method(),
types_vec.clone(),
)
})
})
})
.for_each(|payment_methods_enabled| {
payment_methods_enabled.for_each(
|(payment_method_option, payment_method_types_vec)| {
if let Some(payment_method) = payment_method_option {
payment_method_types_map
.entry(payment_method)
.or_default()
.extend(payment_method_types_vec.iter().filter_map(
|req_payment_method_types| {
req_payment_method_types.get_payment_method_type()
},
));
}
},
);
});
Ok(services::ApplicationResponse::Json(
api::PaymentListFiltersV2 {
connector: connector_map,
currency: enums::Currency::iter().collect(),
status: enums::IntentStatus::iter().collect(),
payment_method: payment_method_types_map,
authentication_type: enums::AuthenticationType::iter().collect(),
card_network: enums::CardNetwork::iter().collect(),
card_discovery: enums::CardDiscovery::iter().collect(),
},
))
}
#[cfg(feature = "olap")]
pub async fn get_aggregates_for_payments(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<id_type::ProfileId>>,
time_range: common_utils::types::TimeRange,
) -> RouterResponse<api::PaymentsAggregateResponse> {
let db = state.store.as_ref();
let intent_status_with_count = db
.get_intent_status_with_count(
merchant_context.get_merchant_account().get_id(),
profile_id_list,
&time_range,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let mut status_map: HashMap<enums::IntentStatus, i64> =
intent_status_with_count.into_iter().collect();
for status in enums::IntentStatus::iter() {
status_map.entry(status).or_default();
}
Ok(services::ApplicationResponse::Json(
api::PaymentsAggregateResponse {
status_with_count: status_map,
},
))
}
#[cfg(feature = "v1")]
pub async fn add_process_sync_task(
db: &dyn StorageInterface,
payment_attempt: &storage::PaymentAttempt,
schedule_time: time::PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
let tracking_data = api::PaymentsRetrieveRequest {
force_sync: true,
merchant_id: Some(payment_attempt.merchant_id.clone()),
resource_id: api::PaymentIdType::PaymentAttemptId(payment_attempt.get_id().to_owned()),
..Default::default()
};
let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow;
let task = "PAYMENTS_SYNC";
let tag = ["SYNC", "PAYMENT"];
let process_tracker_id = pt_utils::get_process_tracker_id(
runner,
task,
payment_attempt.get_id(),
&payment_attempt.merchant_id,
);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
schedule_time,
common_types::consts::API_VERSION,
)
.map_err(errors::StorageError::from)?;
db.insert_process(process_tracker_entry).await?;
Ok(())
}
#[cfg(feature = "v2")]
pub async fn reset_process_sync_task(
db: &dyn StorageInterface,
payment_attempt: &storage::PaymentAttempt,
schedule_time: time::PrimitiveDateTime,
) -> Result<(), errors::ProcessTrackerError> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn reset_process_sync_task(
db: &dyn StorageInterface,
payment_attempt: &storage::PaymentAttempt,
schedule_time: time::PrimitiveDateTime,
) -> Result<(), errors::ProcessTrackerError> {
let runner = storage::ProcessTrackerRunner::PaymentsSyncWorkflow;
let task = "PAYMENTS_SYNC";
let process_tracker_id = pt_utils::get_process_tracker_id(
runner,
task,
payment_attempt.get_id(),
&payment_attempt.merchant_id,
);
let psync_process = db
.find_process_by_id(&process_tracker_id)
.await?
.ok_or(errors::ProcessTrackerError::ProcessFetchingFailed)?;
db.as_scheduler()
.reset_process(psync_process, schedule_time)
.await?;
Ok(())
}
#[cfg(feature = "v1")]
pub fn update_straight_through_routing<F, D>(
payment_data: &mut D,
request_straight_through: serde_json::Value,
) -> CustomResult<(), errors::ParsingError>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let _: api_models::routing::StaticRoutingAlgorithm = request_straight_through
.clone()
.parse_value("RoutingAlgorithm")
.attach_printable("Invalid straight through routing rules format")?;
payment_data.set_straight_through_algorithm_in_payment_attempt(request_straight_through);
Ok(())
}
#[cfg(feature = "v1")]
pub fn is_pre_network_tokenization_enabled(
state: &SessionState,
business_profile: &domain::Profile,
customer_acceptance: Option<Secret<serde_json::Value>>,
connector_name: enums::Connector,
) -> bool {
let ntid_supported_connectors = &state
.conf
.network_transaction_id_supported_connectors
.connector_list;
let is_nt_supported_connector = ntid_supported_connectors.contains(&connector_name);
business_profile.is_network_tokenization_enabled
&& business_profile.is_pre_network_tokenization_enabled
&& customer_acceptance.is_some()
&& is_nt_supported_connector
}
#[cfg(feature = "v1")]
pub async fn get_vault_operation_for_pre_network_tokenization(
state: &SessionState,
customer_id: id_type::CustomerId,
card_data: &hyperswitch_domain_models::payment_method_data::Card,
) -> payments::VaultOperation {
let pre_tokenization_response =
tokenization::pre_payment_tokenization(state, customer_id, card_data)
.await
.ok();
match pre_tokenization_response {
Some((Some(token_response), Some(token_ref))) => {
let token_data = domain::NetworkTokenData::from(token_response);
let network_token_data_for_vault = payments::NetworkTokenDataForVault {
network_token_data: token_data.clone(),
network_token_req_ref_id: token_ref,
};
payments::VaultOperation::SaveCardAndNetworkTokenData(Box::new(
payments::CardAndNetworkTokenDataForVault {
card_data: card_data.clone(),
network_token: network_token_data_for_vault.clone(),
},
))
}
Some((None, Some(token_ref))) => {
payments::VaultOperation::SaveCardData(payments::CardDataForVault {
card_data: card_data.clone(),
network_token_req_ref_id: Some(token_ref),
})
}
_ => payments::VaultOperation::SaveCardData(payments::CardDataForVault {
card_data: card_data.clone(),
network_token_req_ref_id: None,
}),
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn get_connector_choice<F, Req, D>(
operation: &BoxedOperation<'_, F, Req, D>,
state: &SessionState,
req: &Req,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<Option<ConnectorCallType>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let connector_choice = operation
.to_domain()?
.get_connector(
merchant_context,
&state.clone(),
req,
payment_data.get_payment_intent(),
)
.await?;
let connector = if should_call_connector(operation, payment_data) {
Some(match connector_choice {
api::ConnectorChoice::SessionMultiple(connectors) => {
let routing_output = perform_session_token_routing(
state.clone(),
merchant_context,
business_profile,
payment_data,
connectors,
)
.await?;
ConnectorCallType::SessionMultiple(routing_output)
}
api::ConnectorChoice::StraightThrough(straight_through) => {
connector_selection(
state,
merchant_context,
business_profile,
payment_data,
Some(straight_through),
eligible_connectors,
mandate_type,
)
.await?
}
api::ConnectorChoice::Decide => {
connector_selection(
state,
merchant_context,
business_profile,
payment_data,
None,
eligible_connectors,
mandate_type,
)
.await?
}
})
} else if let api::ConnectorChoice::StraightThrough(algorithm) = connector_choice {
update_straight_through_routing(payment_data, algorithm)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update straight through routing algorithm")?;
None
} else {
None
};
Ok(connector)
}
async fn get_eligible_connector_for_nti<T: core_routing::GetRoutableConnectorsForChoice, F, D>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &D,
connector_choice: T,
business_profile: &domain::Profile,
) -> RouterResult<(
api_models::payments::MandateReferenceId,
hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
api::ConnectorData,
)>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
// Since this flow will only be used in the MIT flow, recurring details are mandatory.
let recurring_payment_details = payment_data
.get_recurring_details()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("Failed to fetch recurring details for mit")?;
let (mandate_reference_id, card_details_for_network_transaction_id)= hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId::get_nti_and_card_details_for_mit_flow(recurring_payment_details.clone()).get_required_value("network transaction id and card details").attach_printable("Failed to fetch network transaction id and card details for mit")?;
helpers::validate_card_expiry(
&card_details_for_network_transaction_id.card_exp_month,
&card_details_for_network_transaction_id.card_exp_year,
)?;
let network_transaction_id_supported_connectors = &state
.conf
.network_transaction_id_supported_connectors
.connector_list
.iter()
.map(|value| value.to_string())
.collect::<HashSet<_>>();
let eligible_connector_data_list = connector_choice
.get_routable_connectors(&*state.store, business_profile)
.await?
.filter_network_transaction_id_flow_supported_connectors(
network_transaction_id_supported_connectors.to_owned(),
)
.construct_dsl_and_perform_eligibility_analysis(
state,
key_store,
payment_data,
business_profile.get_id(),
)
.await
.attach_printable("Failed to fetch eligible connector data")?;
let eligible_connector_data = eligible_connector_data_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable(
"No eligible connector found for the network transaction id based mit flow",
)?;
Ok((
mandate_reference_id,
card_details_for_network_transaction_id,
eligible_connector_data.clone(),
))
}
pub async fn set_eligible_connector_for_nti_in_payment_data<F, D>(
state: &SessionState,
business_profile: &domain::Profile,
key_store: &domain::MerchantKeyStore,
payment_data: &mut D,
connector_choice: api::ConnectorChoice,
) -> RouterResult<api::ConnectorData>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let (mandate_reference_id, card_details_for_network_transaction_id, eligible_connector_data) =
match connector_choice {
api::ConnectorChoice::StraightThrough(straight_through) => {
get_eligible_connector_for_nti(
state,
key_store,
payment_data,
core_routing::StraightThroughAlgorithmTypeSingle(straight_through),
business_profile,
)
.await?
}
api::ConnectorChoice::Decide => {
get_eligible_connector_for_nti(
state,
key_store,
payment_data,
core_routing::DecideConnector,
business_profile,
)
.await?
}
api::ConnectorChoice::SessionMultiple(_) => {
Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Invalid routing rule configured for nti and card details based mit flow",
)?
}
};
// Set the eligible connector in the attempt
payment_data
.set_connector_in_payment_attempt(Some(eligible_connector_data.connector_name.to_string()));
// Set `NetworkMandateId` as the MandateId
payment_data.set_mandate_id(payments_api::MandateIds {
mandate_id: None,
mandate_reference_id: Some(mandate_reference_id),
});
// Set the card details received in the recurring details within the payment method data.
payment_data.set_payment_method_data(Some(
hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(card_details_for_network_transaction_id),
));
Ok(eligible_connector_data)
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn connector_selection<F, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
request_straight_through: Option<serde_json::Value>,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let request_straight_through: Option<api::routing::StraightThroughAlgorithm> =
request_straight_through
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid straight through routing rules format")?;
let mut routing_data = storage::RoutingData {
routed_through: payment_data.get_payment_attempt().connector.clone(),
merchant_connector_id: payment_data
.get_payment_attempt()
.merchant_connector_id
.clone(),
algorithm: request_straight_through.clone(),
routing_info: payment_data
.get_payment_attempt()
.straight_through_algorithm
.clone()
.map(|val| val.parse_value("PaymentRoutingInfo"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid straight through algorithm format found in payment attempt")?
.unwrap_or(storage::PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
}),
};
let decided_connector = decide_connector(
state.clone(),
merchant_context,
business_profile,
payment_data,
request_straight_through,
&mut routing_data,
eligible_connectors,
mandate_type,
)
.await?;
let encoded_info = routing_data
.routing_info
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error serializing payment routing info to serde value")?;
payment_data.set_connector_in_payment_attempt(routing_data.routed_through);
payment_data.set_merchant_connector_id_in_attempt(routing_data.merchant_connector_id);
payment_data.set_straight_through_algorithm_in_payment_attempt(encoded_info);
Ok(decided_connector)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn connector_selection<F, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let mut routing_data = storage::RoutingData {
routed_through: payment_data.get_payment_attempt().connector.clone(),
merchant_connector_id: payment_data
.get_payment_attempt()
.merchant_connector_id
.clone(),
pre_routing_connector_choice: payment_data.get_pre_routing_result().and_then(
|pre_routing_results| {
pre_routing_results
.get(&payment_data.get_payment_attempt().payment_method_subtype)
.cloned()
},
),
algorithm_requested: payment_data
.get_payment_intent()
.routing_algorithm_id
.clone(),
};
let payment_dsl_input = core_routing::PaymentsDslInput::new(
None,
payment_data.get_payment_attempt(),
payment_data.get_payment_intent(),
payment_data.get_payment_method_data(),
payment_data.get_address(),
None,
payment_data.get_currency(),
);
let decided_connector = decide_connector(
state.clone(),
merchant_context,
business_profile,
&mut routing_data,
payment_dsl_input,
mandate_type,
)
.await?;
payment_data.set_connector_in_payment_attempt(routing_data.routed_through);
payment_data.set_merchant_connector_id_in_attempt(routing_data.merchant_connector_id);
Ok(decided_connector)
}
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "v2")]
pub async fn decide_connector(
state: SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
routing_data: &mut storage::RoutingData,
payment_dsl_input: core_routing::PaymentsDslInput<'_>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType> {
// If the connector was already decided previously, use the same connector
// This is in case of flows like payments_sync, payments_cancel where the successive operations
// with the connector have to be made using the same connector account.
let predetermined_info_cloned = routing_data
.routed_through
.as_ref()
.zip(routing_data.merchant_connector_id.as_ref())
.map(|(cn_ref, mci_ref)| (cn_ref.clone(), mci_ref.clone()));
match (
predetermined_info_cloned,
routing_data.pre_routing_connector_choice.as_ref(),
) {
// Condition 1: Connector was already decided previously
(Some((owned_connector_name, owned_merchant_connector_id)), _) => {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&owned_connector_name,
api::GetToken::Connector,
Some(owned_merchant_connector_id.clone()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received in 'routed_through'")
.map(|connector_data| {
routing_data.routed_through = Some(owned_connector_name);
ConnectorCallType::PreDetermined(connector_data.into())
})
}
// Condition 2: Pre-routing connector choice
(None, Some(routable_connector_choice)) => {
let routable_connector_list = match routable_connector_choice {
storage::PreRoutingConnectorChoice::Single(routable_connector) => {
vec![routable_connector.clone()]
}
storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
routable_connector_list.clone()
}
};
routable_connector_list
.first()
.ok_or_else(|| {
report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("No first routable connector in pre_routing_connector_choice")
})
.and_then(|first_routable_connector| {
routing_data.routed_through = Some(first_routable_connector.connector.to_string());
routing_data
.merchant_connector_id
.clone_from(&first_routable_connector.merchant_connector_id);
let pre_routing_connector_data_list_result: RouterResult<Vec<api::ConnectorData>> = routable_connector_list
.iter()
.map(|connector_choice| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_choice.connector.to_string(),
api::GetToken::Connector,
connector_choice.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received while processing pre_routing_connector_choice")
})
.collect::<Result<Vec<_>, _>>(); // Collects into RouterResult<Vec<ConnectorData>>
pre_routing_connector_data_list_result
.and_then(|list| {
list.first()
.cloned()
.ok_or_else(|| {
report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("Empty pre_routing_connector_data_list after mapping")
})
.map(|first_data| ConnectorCallType::PreDetermined(first_data.into()))
})
})
}
(None, None) => {
route_connector_v2_for_payments(
&state,
merchant_context,
business_profile,
payment_dsl_input,
routing_data,
mandate_type,
)
.await
}
}
}
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "v1")]
pub async fn decide_connector<F, D>(
state: SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
request_straight_through: Option<api::routing::StraightThroughAlgorithm>,
routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
// If the connector was already decided previously, use the same connector
// This is in case of flows like payments_sync, payments_cancel where the successive operations
// with the connector have to be made using the same connector account.
if let Some(ref connector_name) = payment_data.get_payment_attempt().connector {
// Connector was already decided previously, use the same connector
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
payment_data
.get_payment_attempt()
.merchant_connector_id
.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received in 'routed_through'")?;
routing_data.routed_through = Some(connector_name.clone());
logger::debug!("euclid_routing: predetermined connector present in attempt");
return Ok(ConnectorCallType::PreDetermined(connector_data.into()));
}
if let Some(mandate_connector_details) = payment_data.get_mandate_connector().as_ref() {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&mandate_connector_details.connector,
api::GetToken::Connector,
mandate_connector_details.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received in 'routed_through'")?;
routing_data.routed_through = Some(mandate_connector_details.connector.clone());
routing_data
.merchant_connector_id
.clone_from(&mandate_connector_details.merchant_connector_id);
logger::debug!("euclid_routing: predetermined mandate connector");
return Ok(ConnectorCallType::PreDetermined(connector_data.into()));
}
if let Some((pre_routing_results, storage_pm_type)) =
routing_data.routing_info.pre_routing_results.as_ref().zip(
payment_data
.get_payment_attempt()
.payment_method_type
.as_ref(),
)
{
if let (Some(routable_connector_choice), None) = (
pre_routing_results.get(storage_pm_type),
&payment_data.get_token_data(),
) {
let routable_connector_list = match routable_connector_choice {
storage::PreRoutingConnectorChoice::Single(routable_connector) => {
vec![routable_connector.clone()]
}
storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
routable_connector_list.clone()
}
};
let mut pre_routing_connector_data_list = vec![];
let first_routable_connector = routable_connector_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
routing_data.routed_through = Some(first_routable_connector.connector.to_string());
routing_data
.merchant_connector_id
.clone_from(&first_routable_connector.merchant_connector_id);
for connector_choice in routable_connector_list.clone() {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_choice.connector.to_string(),
api::GetToken::Connector,
connector_choice.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?
.into();
pre_routing_connector_data_list.push(connector_data);
}
#[cfg(feature = "retry")]
let should_do_retry = retry::config_should_call_gsm(
&*state.store,
merchant_context.get_merchant_account().get_id(),
business_profile,
)
.await;
#[cfg(feature = "retry")]
if payment_data.get_payment_attempt().payment_method_type
== Some(storage_enums::PaymentMethodType::ApplePay)
&& should_do_retry
{
let retryable_connector_data = helpers::get_apple_pay_retryable_connectors(
&state,
merchant_context,
payment_data,
&pre_routing_connector_data_list,
first_routable_connector
.merchant_connector_id
.clone()
.as_ref(),
business_profile.clone(),
)
.await?;
if let Some(connector_data_list) = retryable_connector_data {
if connector_data_list.len() > 1 {
logger::info!("Constructed apple pay retryable connector list");
return Ok(ConnectorCallType::Retryable(connector_data_list));
}
}
}
logger::debug!("euclid_routing: pre-routing connector present");
let first_pre_routing_connector_data_list = pre_routing_connector_data_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?;
return Ok(ConnectorCallType::PreDetermined(
first_pre_routing_connector_data_list.clone(),
));
}
}
if let Some(routing_algorithm) = request_straight_through {
let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(
&routing_algorithm,
payment_data.get_creds_identifier(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed execution of straight through routing")?;
payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::StraightThroughRouting,
));
if check_eligibility {
let transaction_data = core_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(),
);
connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
merchant_context.get_merchant_key_store(),
connectors,
&TransactionData::Payment(transaction_data),
eligible_connectors,
business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
}
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id.clone(),
)
.map(|connector_data| connector_data.into())
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
logger::debug!("euclid_routing: straight through connector present");
return decide_multiplex_connector_for_normal_or_recurring_payment(
&state,
payment_data,
routing_data,
connector_data,
mandate_type,
business_profile.is_connector_agnostic_mit_enabled,
business_profile.is_network_tokenization_enabled,
)
.await;
}
if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm {
let (mut connectors, check_eligibility) = routing::perform_straight_through_routing(
routing_algorithm,
payment_data.get_creds_identifier(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
let transaction_data = core_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(),
);
connectors = routing::perform_eligibility_analysis_with_fallback(
&state,
merchant_context.get_merchant_key_store(),
connectors,
&TransactionData::Payment(transaction_data),
eligible_connectors,
business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
}
logger::debug!("euclid_routing: single connector present in algorithm data");
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id,
)
.map(|connector_data| connector_data.into())
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
return decide_multiplex_connector_for_normal_or_recurring_payment(
&state,
payment_data,
routing_data,
connector_data,
mandate_type,
business_profile.is_connector_agnostic_mit_enabled,
business_profile.is_network_tokenization_enabled,
)
.await;
}
let new_pd = payment_data.clone();
let transaction_data = core_routing::PaymentsDslInput::new(
new_pd.get_setup_mandate(),
new_pd.get_payment_attempt(),
new_pd.get_payment_intent(),
new_pd.get_payment_method_data(),
new_pd.get_address(),
new_pd.get_recurring_details(),
new_pd.get_currency(),
);
route_connector_v1_for_payments(
&state,
merchant_context,
business_profile,
payment_data,
transaction_data,
routing_data,
eligible_connectors,
mandate_type,
)
.await
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>(
state: &SessionState,
payment_data: &mut D,
routing_data: &mut storage::RoutingData,
connectors: Vec<api::ConnectorRoutingData>,
mandate_type: Option<api::MandateTransactionType>,
is_connector_agnostic_mit_enabled: Option<bool>,
is_network_tokenization_enabled: bool,
) -> RouterResult<ConnectorCallType>
where
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
match (
payment_data.get_payment_intent().setup_future_usage,
payment_data.get_token_data().as_ref(),
payment_data.get_recurring_details().as_ref(),
payment_data.get_payment_intent().off_session,
mandate_type,
) {
(
Some(storage_enums::FutureUsage::OffSession),
Some(_),
None,
None,
Some(api::MandateTransactionType::RecurringMandateTransaction),
)
| (
None,
None,
Some(RecurringDetails::PaymentMethodId(_)),
Some(true),
Some(api::MandateTransactionType::RecurringMandateTransaction),
)
| (None, Some(_), None, Some(true), _) => {
logger::debug!("euclid_routing: performing routing for token-based MIT flow");
let payment_method_info = payment_data
.get_payment_method_info()
.get_required_value("payment_method_info")?
.clone();
let retryable_connectors =
join_all(connectors.into_iter().map(|connector_routing_data| {
let payment_method = payment_method_info.clone();
async move {
let action_types = get_all_action_types(
state,
is_connector_agnostic_mit_enabled,
is_network_tokenization_enabled,
&payment_method.clone(),
connector_routing_data.connector_data.clone(),
)
.await;
action_types
.into_iter()
.map(|action_type| api::ConnectorRoutingData {
connector_data: connector_routing_data.connector_data.clone(),
action_type: Some(action_type),
network: connector_routing_data.network.clone(),
})
.collect::<Vec<_>>()
}
}))
.await
.into_iter()
.flatten()
.collect::<Vec<_>>();
let chosen_connector_routing_data = retryable_connectors
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("no eligible connector found for token-based MIT payment")?;
let mandate_reference_id = get_mandate_reference_id(
chosen_connector_routing_data.action_type.clone(),
chosen_connector_routing_data.clone(),
payment_data,
&payment_method_info,
)?;
routing_data.routed_through = Some(
chosen_connector_routing_data
.connector_data
.connector_name
.to_string(),
);
routing_data.merchant_connector_id.clone_from(
&chosen_connector_routing_data
.connector_data
.merchant_connector_id,
);
payment_data.set_mandate_id(payments_api::MandateIds {
mandate_id: None,
mandate_reference_id,
});
Ok(ConnectorCallType::Retryable(retryable_connectors))
}
(
None,
None,
Some(RecurringDetails::ProcessorPaymentToken(_token)),
Some(true),
Some(api::MandateTransactionType::RecurringMandateTransaction),
) => {
if let Some(connector) = connectors.first() {
let connector = &connector.connector_data;
routing_data.routed_through = Some(connector.connector_name.clone().to_string());
routing_data
.merchant_connector_id
.clone_from(&connector.merchant_connector_id);
Ok(ConnectorCallType::PreDetermined(
api::ConnectorData {
connector: connector.connector.clone(),
connector_name: connector.connector_name,
get_token: connector.get_token.clone(),
merchant_connector_id: connector.merchant_connector_id.clone(),
}
.into(),
))
} else {
logger::error!(
"euclid_routing: no eligible connector found for the ppt_mandate payment"
);
Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration.into())
}
}
_ => {
helpers::override_setup_future_usage_to_on_session(&*state.store, payment_data).await?;
let first_choice = connectors
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("no eligible connector found for payment")?
.clone();
routing_data.routed_through =
Some(first_choice.connector_data.connector_name.to_string());
routing_data.merchant_connector_id = first_choice.connector_data.merchant_connector_id;
Ok(ConnectorCallType::Retryable(connectors))
}
}
}
#[cfg(feature = "v1")]
pub fn get_mandate_reference_id<F: Clone, D>(
action_type: Option<ActionType>,
connector_routing_data: api::ConnectorRoutingData,
payment_data: &mut D,
payment_method_info: &domain::PaymentMethod,
) -> RouterResult<Option<api_models::payments::MandateReferenceId>>
where
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let mandate_reference_id = match action_type {
Some(ActionType::NetworkTokenWithNetworkTransactionId(network_token_data)) => {
logger::info!("using network token with network_transaction_id for MIT flow");
Some(payments_api::MandateReferenceId::NetworkTokenWithNTI(
network_token_data.into(),
))
}
Some(ActionType::CardWithNetworkTransactionId(network_transaction_id)) => {
logger::info!("using card with network_transaction_id for MIT flow");
Some(payments_api::MandateReferenceId::NetworkMandateId(
network_transaction_id,
))
}
Some(ActionType::ConnectorMandate(connector_mandate_details)) => {
logger::info!("using connector_mandate_id for MIT flow");
let merchant_connector_id = connector_routing_data
.connector_data
.merchant_connector_id
.as_ref()
.ok_or_else(|| {
report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("No eligible connector found for token-based MIT flow: no connector mandate details")
})?;
let mandate_reference_record = connector_mandate_details
.get(merchant_connector_id)
.ok_or_else(|| {
report!(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("No mandate record found for merchant connector ID")
})?;
if let Some(mandate_currency) =
mandate_reference_record.original_payment_authorized_currency
{
if mandate_currency != payment_data.get_currency() {
return Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Cross currency mandates not supported".into(),
}));
}
}
payment_data.set_recurring_mandate_payment_data(mandate_reference_record.into());
Some(payments_api::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
Some(mandate_reference_record.connector_mandate_id.clone()),
Some(payment_method_info.get_id().clone()),
None,
mandate_reference_record.mandate_metadata.clone(),
mandate_reference_record
.connector_mandate_request_reference_id
.clone(),
),
))
}
None => None,
};
Ok(mandate_reference_id)
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>(
state: &SessionState,
payment_data: &mut D,
routing_data: &mut storage::RoutingData,
connectors: Vec<api::ConnectorRoutingData>,
is_connector_agnostic_mit_enabled: Option<bool>,
payment_method_info: &domain::PaymentMethod,
) -> RouterResult<ConnectorCallType>
where
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let connector_common_mandate_details = payment_method_info
.get_common_mandate_reference()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the common mandate reference")?;
let connector_mandate_details = connector_common_mandate_details.payments.clone();
let mut connector_choice = None;
for connector_info in connectors {
let connector_data = connector_info.connector_data;
let merchant_connector_id = connector_data
.merchant_connector_id
.as_ref()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find the merchant connector id")?;
if connector_mandate_details
.clone()
.map(|connector_mandate_details| {
connector_mandate_details.contains_key(merchant_connector_id)
})
.unwrap_or(false)
{
logger::info!("euclid_routing: using connector_mandate_id for MIT flow");
if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() {
if let Some(mandate_reference_record) = connector_mandate_details.clone()
.get_required_value("connector_mandate_details")
.change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?
.get(merchant_connector_id)
{
common_utils::fp_utils::when(
mandate_reference_record
.original_payment_authorized_currency
.map(|mandate_currency| mandate_currency != payment_data.get_currency())
.unwrap_or(false),
|| {
Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
reason: "cross currency mandates not supported".into()
}))
},
)?;
let mandate_reference_id = Some(payments_api::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
Some(mandate_reference_record.connector_mandate_id.clone()),
Some(payment_method_info.get_id().clone()),
// update_history
None,
mandate_reference_record.mandate_metadata.clone(),
mandate_reference_record.connector_mandate_request_reference_id.clone(),
)
));
payment_data.set_recurring_mandate_payment_data(
mandate_reference_record.into(),
);
connector_choice = Some((connector_data, mandate_reference_id.clone()));
break;
}
}
} else if is_network_transaction_id_flow(
state,
is_connector_agnostic_mit_enabled,
connector_data.connector_name,
payment_method_info,
) {
logger::info!("using network_transaction_id for MIT flow");
let network_transaction_id = payment_method_info
.network_transaction_id
.as_ref()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the network transaction id")?;
let mandate_reference_id = Some(payments_api::MandateReferenceId::NetworkMandateId(
network_transaction_id.to_string(),
));
connector_choice = Some((connector_data, mandate_reference_id.clone()));
break;
} else {
continue;
}
}
let (chosen_connector_data, mandate_reference_id) = connector_choice
.get_required_value("connector_choice")
.change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("no eligible connector found for token-based MIT payment")?;
routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string());
routing_data
.merchant_connector_id
.clone_from(&chosen_connector_data.merchant_connector_id);
payment_data.set_mandate_id(payments_api::MandateIds {
mandate_id: None,
mandate_reference_id,
});
Ok(ConnectorCallType::PreDetermined(
chosen_connector_data.into(),
))
}
pub fn filter_ntid_supported_connectors(
connectors: Vec<api::ConnectorRoutingData>,
ntid_supported_connectors: &HashSet<enums::Connector>,
) -> Vec<api::ConnectorRoutingData> {
connectors
.into_iter()
.filter(|data| ntid_supported_connectors.contains(&data.connector_data.connector_name))
.collect()
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)]
pub struct NetworkTokenExpiry {
pub token_exp_month: Option<Secret<String>>,
pub token_exp_year: Option<Secret<String>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)]
pub struct NTWithNTIRef {
pub network_transaction_id: String,
pub token_exp_month: Option<Secret<String>>,
pub token_exp_year: Option<Secret<String>>,
}
impl From<NTWithNTIRef> for payments_api::NetworkTokenWithNTIRef {
fn from(network_token_data: NTWithNTIRef) -> Self {
Self {
network_transaction_id: network_token_data.network_transaction_id,
token_exp_month: network_token_data.token_exp_month,
token_exp_year: network_token_data.token_exp_year,
}
}
}
// This represents the recurring details of a connector which will be used for retries
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub enum ActionType {
NetworkTokenWithNetworkTransactionId(NTWithNTIRef),
CardWithNetworkTransactionId(String), // Network Transaction Id
#[cfg(feature = "v1")]
ConnectorMandate(hyperswitch_domain_models::mandates::PaymentsMandateReference),
}
pub fn filter_network_tokenization_supported_connectors(
connectors: Vec<api::ConnectorRoutingData>,
network_tokenization_supported_connectors: &HashSet<enums::Connector>,
) -> Vec<api::ConnectorRoutingData> {
connectors
.into_iter()
.filter(|data| {
network_tokenization_supported_connectors.contains(&data.connector_data.connector_name)
})
.collect()
}
#[cfg(feature = "v1")]
#[derive(Default)]
pub struct ActionTypesBuilder {
action_types: Vec<ActionType>,
}
#[cfg(feature = "v1")]
impl ActionTypesBuilder {
pub fn new() -> Self {
Self {
action_types: Vec::new(),
}
}
pub fn with_mandate_flow(
mut self,
is_mandate_flow: bool,
connector_mandate_details: Option<
hyperswitch_domain_models::mandates::PaymentsMandateReference,
>,
) -> Self {
if is_mandate_flow {
self.action_types.extend(
connector_mandate_details
.map(|details| ActionType::ConnectorMandate(details.to_owned())),
);
}
self
}
pub async fn with_network_tokenization(
mut self,
state: &SessionState,
is_network_token_with_ntid_flow: IsNtWithNtiFlow,
is_nt_with_ntid_supported_connector: bool,
payment_method_info: &domain::PaymentMethod,
) -> Self {
match is_network_token_with_ntid_flow {
IsNtWithNtiFlow::NtWithNtiSupported(network_transaction_id)
if is_nt_with_ntid_supported_connector =>
{
self.action_types.extend(
network_tokenization::do_status_check_for_network_token(
state,
payment_method_info,
)
.await
.inspect_err(|e| {
logger::error!("Status check for network token failed: {:?}", e)
})
.ok()
.map(|(token_exp_month, token_exp_year)| {
ActionType::NetworkTokenWithNetworkTransactionId(NTWithNTIRef {
token_exp_month,
token_exp_year,
network_transaction_id,
})
}),
);
}
_ => (),
}
self
}
pub fn with_card_network_transaction_id(
mut self,
is_card_with_ntid_flow: bool,
payment_method_info: &domain::PaymentMethod,
) -> Self {
if is_card_with_ntid_flow {
self.action_types.extend(
payment_method_info
.network_transaction_id
.as_ref()
.map(|ntid| ActionType::CardWithNetworkTransactionId(ntid.clone())),
);
}
self
}
pub fn build(self) -> Vec<ActionType> {
self.action_types
}
}
#[cfg(feature = "v1")]
pub async fn get_all_action_types(
state: &SessionState,
is_connector_agnostic_mit_enabled: Option<bool>,
is_network_tokenization_enabled: bool,
payment_method_info: &domain::PaymentMethod,
connector: api::ConnectorData,
) -> Vec<ActionType> {
let merchant_connector_id = connector.merchant_connector_id.as_ref();
//fetch connectors that support ntid flow
let ntid_supported_connectors = &state
.conf
.network_transaction_id_supported_connectors
.connector_list;
//fetch connectors that support network tokenization flow
let network_tokenization_supported_connectors = &state
.conf
.network_tokenization_supported_connectors
.connector_list;
let is_network_token_with_ntid_flow = is_network_token_with_network_transaction_id_flow(
is_connector_agnostic_mit_enabled,
is_network_tokenization_enabled,
payment_method_info,
);
let is_card_with_ntid_flow = is_network_transaction_id_flow(
state,
is_connector_agnostic_mit_enabled,
connector.connector_name,
payment_method_info,
);
let payments_mandate_reference = payment_method_info
.get_common_mandate_reference()
.map_err(|err| {
logger::warn!("Error getting connector mandate details: {:?}", err);
err
})
.ok()
.and_then(|details| details.payments);
let is_mandate_flow = payments_mandate_reference
.clone()
.zip(merchant_connector_id)
.map(|(details, merchant_connector_id)| details.contains_key(merchant_connector_id))
.unwrap_or(false);
let is_nt_with_ntid_supported_connector = ntid_supported_connectors
.contains(&connector.connector_name)
&& network_tokenization_supported_connectors.contains(&connector.connector_name);
ActionTypesBuilder::new()
.with_mandate_flow(is_mandate_flow, payments_mandate_reference)
.with_network_tokenization(
state,
is_network_token_with_ntid_flow,
is_nt_with_ntid_supported_connector,
payment_method_info,
)
.await
.with_card_network_transaction_id(is_card_with_ntid_flow, payment_method_info)
.build()
}
pub fn is_network_transaction_id_flow(
state: &SessionState,
is_connector_agnostic_mit_enabled: Option<bool>,
connector: enums::Connector,
payment_method_info: &domain::PaymentMethod,
) -> bool {
let ntid_supported_connectors = &state
.conf
.network_transaction_id_supported_connectors
.connector_list;
is_connector_agnostic_mit_enabled == Some(true)
&& payment_method_info.get_payment_method_type() == Some(storage_enums::PaymentMethod::Card)
&& ntid_supported_connectors.contains(&connector)
&& payment_method_info.network_transaction_id.is_some()
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)]
pub enum IsNtWithNtiFlow {
NtWithNtiSupported(String), //Network token with Network transaction id supported flow
NTWithNTINotSupported, //Network token with Network transaction id not supported
}
pub fn is_network_token_with_network_transaction_id_flow(
is_connector_agnostic_mit_enabled: Option<bool>,
is_network_tokenization_enabled: bool,
payment_method_info: &domain::PaymentMethod,
) -> IsNtWithNtiFlow {
match (
is_connector_agnostic_mit_enabled,
is_network_tokenization_enabled,
payment_method_info.get_payment_method_type(),
payment_method_info.network_transaction_id.clone(),
payment_method_info.network_token_locker_id.is_some(),
payment_method_info
.network_token_requestor_reference_id
.is_some(),
) {
(
Some(true),
true,
Some(storage_enums::PaymentMethod::Card),
Some(network_transaction_id),
true,
true,
) => IsNtWithNtiFlow::NtWithNtiSupported(network_transaction_id),
_ => IsNtWithNtiFlow::NTWithNTINotSupported,
}
}
pub fn should_add_task_to_process_tracker<F: Clone, D: OperationSessionGetters<F>>(
payment_data: &D,
) -> bool {
let connector = payment_data.get_payment_attempt().connector.as_deref();
!matches!(
(
payment_data.get_payment_attempt().get_payment_method(),
connector
),
(
Some(storage_enums::PaymentMethod::BankTransfer),
Some("stripe")
)
)
}
#[cfg(feature = "v1")]
pub async fn perform_session_token_routing<F, D>(
state: SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
connectors: api::SessionConnectorDatas,
) -> RouterResult<api::SessionConnectorDatas>
where
F: Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F>,
{
let chosen = connectors.apply_filter_for_session_routing();
let sfr = SessionFlowRoutingInput {
state: &state,
country: payment_data
.get_address()
.get_payment_method_billing()
.and_then(|address| address.address.as_ref())
.and_then(|details| details.country),
key_store: merchant_context.get_merchant_key_store(),
merchant_account: merchant_context.get_merchant_account(),
payment_attempt: payment_data.get_payment_attempt(),
payment_intent: payment_data.get_payment_intent(),
chosen,
};
let (result, routing_approach) = self_routing::perform_session_flow_routing(
sfr,
business_profile,
&enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing session flow routing")?;
payment_data.set_routing_approach_in_attempt(routing_approach);
let final_list = connectors.filter_and_validate_for_session_flow(&result)?;
Ok(final_list)
}
pub struct SessionTokenRoutingResult {
pub final_result: api::SessionConnectorDatas,
pub routing_result:
FxHashMap<common_enums::PaymentMethodType, Vec<api::routing::SessionRoutingChoice>>,
}
#[cfg(feature = "v2")]
pub async fn perform_session_token_routing<F, D>(
state: SessionState,
business_profile: &domain::Profile,
merchant_context: domain::MerchantContext,
payment_data: &D,
connectors: api::SessionConnectorDatas,
) -> RouterResult<SessionTokenRoutingResult>
where
F: Clone,
D: OperationSessionGetters<F>,
{
let chosen = connectors.apply_filter_for_session_routing();
let sfr = SessionFlowRoutingInput {
country: payment_data
.get_payment_intent()
.billing_address
.as_ref()
.and_then(|address| address.get_inner().address.as_ref())
.and_then(|details| details.country),
payment_intent: payment_data.get_payment_intent(),
chosen,
};
let result = self_routing::perform_session_flow_routing(
&state,
merchant_context.get_merchant_key_store(),
sfr,
business_profile,
&enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing session flow routing")?;
let final_list = connectors.filter_and_validate_for_session_flow(&result)?;
Ok(SessionTokenRoutingResult {
final_result: final_list,
routing_result: result,
})
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn route_connector_v2_for_payments(
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
transaction_data: core_routing::PaymentsDslInput<'_>,
routing_data: &mut storage::RoutingData,
_mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType> {
let routing_algorithm_id = routing_data
.algorithm_requested
.as_ref()
.or(business_profile.routing_algorithm_id.as_ref());
let (connectors, _) = routing::perform_static_routing_v1(
state,
merchant_context.get_merchant_account().get_id(),
routing_algorithm_id,
business_profile,
&TransactionData::Payment(transaction_data.clone()),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
merchant_context.get_merchant_key_store(),
connectors,
&TransactionData::Payment(transaction_data),
None,
business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
connectors
.first()
.map(|conn| {
routing_data.routed_through = Some(conn.connector.to_string());
routing_data.merchant_connector_id = conn.merchant_connector_id.clone();
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id.clone(),
)
})
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?
.map(|connector_data| ConnectorCallType::PreDetermined(connector_data.into()))
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn route_connector_v1_for_payments<F, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut D,
transaction_data: core_routing::PaymentsDslInput<'_>,
routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
mandate_type: Option<api::MandateTransactionType>,
) -> RouterResult<ConnectorCallType>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let routing_algorithm_id = {
let routing_algorithm = business_profile.routing_algorithm.clone();
let algorithm_ref = routing_algorithm
.map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode merchant routing algorithm ref")?
.unwrap_or_default();
algorithm_ref.algorithm_id
};
let (connectors, routing_approach) = routing::perform_static_routing_v1(
state,
merchant_context.get_merchant_account().get_id(),
routing_algorithm_id.as_ref(),
business_profile,
&TransactionData::Payment(transaction_data.clone()),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
payment_data.set_routing_approach_in_attempt(routing_approach);
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
let payment_attempt = transaction_data.payment_attempt.clone();
let connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
merchant_context.get_merchant_key_store(),
connectors,
&TransactionData::Payment(transaction_data),
eligible_connectors,
business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
// dynamic success based connector selection
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
let connectors = if let Some(algo) = business_profile.dynamic_routing_algorithm.clone() {
let dynamic_routing_config: api_models::routing::DynamicRoutingAlgorithmRef = algo
.parse_value("DynamicRoutingAlgorithmRef")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?;
let dynamic_split = api_models::routing::RoutingVolumeSplit {
routing_type: api_models::routing::RoutingType::Dynamic,
split: dynamic_routing_config
.dynamic_routing_volume_split
.unwrap_or_default(),
};
let static_split: api_models::routing::RoutingVolumeSplit =
api_models::routing::RoutingVolumeSplit {
routing_type: api_models::routing::RoutingType::Static,
split: consts::DYNAMIC_ROUTING_MAX_VOLUME
- dynamic_routing_config
.dynamic_routing_volume_split
.unwrap_or_default(),
};
let volume_split_vec = vec![dynamic_split, static_split];
let routing_choice = routing::perform_dynamic_routing_volume_split(volume_split_vec, None)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to perform volume split on routing type")?;
if routing_choice.routing_type.is_dynamic_routing() {
if state.conf.open_router.dynamic_routing_enabled {
routing::perform_dynamic_routing_with_open_router(
state,
connectors.clone(),
business_profile,
payment_attempt,
payment_data,
)
.await
.map_err(|e| logger::error!(open_routing_error=?e))
.unwrap_or(connectors)
} else {
let dynamic_routing_config_params_interpolator =
routing_helpers::DynamicRoutingConfigParamsInterpolator::new(
payment_data.get_payment_attempt().payment_method,
payment_data.get_payment_attempt().payment_method_type,
payment_data.get_payment_attempt().authentication_type,
payment_data.get_payment_attempt().currency,
payment_data
.get_billing_address()
.and_then(|address| address.address)
.and_then(|address| address.country),
payment_data
.get_payment_attempt()
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
payment_data
.get_payment_attempt()
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_isin"))
.and_then(|card_isin| card_isin.as_str())
.map(|card_isin| card_isin.to_string()),
);
routing::perform_dynamic_routing_with_intelligent_router(
state,
connectors.clone(),
business_profile,
dynamic_routing_config_params_interpolator,
payment_data,
)
.await
.map_err(|e| logger::error!(dynamic_routing_error=?e))
.unwrap_or(connectors)
}
} else {
connectors
}
} else {
connectors
};
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id,
)
.map(|connector_data| connector_data.into())
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
decide_multiplex_connector_for_normal_or_recurring_payment(
state,
payment_data,
routing_data,
connector_data,
mandate_type,
business_profile.is_connector_agnostic_mit_enabled,
business_profile.is_network_tokenization_enabled,
)
.await
}
#[cfg(feature = "payouts")]
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn route_connector_v1_for_payouts(
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
transaction_data: &payouts::PayoutData,
routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
) -> RouterResult<ConnectorCallType> {
todo!()
}
#[cfg(feature = "payouts")]
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn route_connector_v1_for_payouts(
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
transaction_data: &payouts::PayoutData,
routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
) -> RouterResult<ConnectorCallType> {
let routing_algorithm_id = {
let routing_algorithm = business_profile.payout_routing_algorithm.clone();
let algorithm_ref = routing_algorithm
.map(|ra| ra.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode merchant routing algorithm ref")?
.unwrap_or_default();
algorithm_ref.algorithm_id
};
let (connectors, _) = routing::perform_static_routing_v1(
state,
merchant_context.get_merchant_account().get_id(),
routing_algorithm_id.as_ref(),
business_profile,
&TransactionData::Payout(transaction_data),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
merchant_context.get_merchant_key_store(),
connectors,
&TransactionData::Payout(transaction_data),
eligible_connectors,
business_profile,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
let first_connector_choice = connectors
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("Empty connector list returned")?
.clone();
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id,
)
.map(|connector_data| connector_data.into())
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
routing_data.routed_through = Some(first_connector_choice.connector.to_string());
routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id;
Ok(ConnectorCallType::Retryable(connector_data))
}
#[cfg(feature = "v2")]
pub async fn payment_external_authentication(
_state: SessionState,
_merchant_context: domain::MerchantContext,
_req: api_models::payments::PaymentsExternalAuthenticationRequest,
) -> RouterResponse<api_models::payments::PaymentsExternalAuthenticationResponse> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn payment_external_authentication<F: Clone + Sync>(
state: SessionState,
merchant_context: domain::MerchantContext,
req: api_models::payments::PaymentsExternalAuthenticationRequest,
) -> RouterResponse<api_models::payments::PaymentsExternalAuthenticationResponse> {
use super::unified_authentication_service::types::ExternalAuthentication;
use crate::core::unified_authentication_service::{
types::UnifiedAuthenticationService, utils::external_authentication_update_trackers,
};
let db = &*state.store;
let key_manager_state = &(&state).into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = req.payment_id;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
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(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
if payment_attempt.external_three_ds_authentication_attempted != Some(true) {
Err(errors::ApiErrorResponse::PreconditionFailed {
message:
"You cannot authenticate this payment because payment_attempt.external_three_ds_authentication_attempted is false".to_owned(),
})?
}
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[storage_enums::IntentStatus::RequiresCustomerAction],
"authenticate",
)?;
let optional_customer = match &payment_intent.customer_id {
Some(customer_id) => Some(
state
.store
.find_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("error while finding customer with customer_id {customer_id:?}")
})?,
),
None => None,
};
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount();
let shipping_address = helpers::create_or_find_address_for_payment_by_request(
&state,
None,
payment_intent.shipping_address_id.as_deref(),
merchant_id,
payment_intent.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
storage_scheme,
)
.await?;
let billing_address = helpers::create_or_find_address_for_payment_by_request(
&state,
None,
payment_attempt
.payment_method_billing_address_id
.as_deref()
.or(payment_intent.billing_address_id.as_deref()),
merchant_id,
payment_intent.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
storage_scheme,
)
.await?;
let authentication_connector = payment_attempt
.authentication_connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("authentication_connector not found in payment_attempt")?;
let merchant_connector_account = helpers::get_merchant_connector_account(
&state,
merchant_id,
None,
merchant_context.get_merchant_key_store(),
profile_id,
authentication_connector.as_str(),
None,
)
.await?;
let authentication = db
.find_authentication_by_merchant_id_authentication_id(
merchant_id,
&payment_attempt
.authentication_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing authentication_id in payment_attempt")?,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while fetching authentication record")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_method_details = helpers::get_payment_method_details_from_payment_token(
&state,
&payment_attempt,
&payment_intent,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await?
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing payment_method_details")?;
let browser_info: Option<BrowserInformation> = payment_attempt
.browser_info
.clone()
.map(|browser_information| browser_information.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let payment_connector_name = payment_attempt
.connector
.as_ref()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing connector in payment_attempt")?;
let return_url = Some(helpers::create_authorize_url(
&state.base_url,
&payment_attempt.clone(),
payment_connector_name,
));
let mca_id_option = merchant_connector_account.get_mca_id(); // Bind temporary value
let merchant_connector_account_id_or_connector_name = mca_id_option
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(&authentication_connector);
let webhook_url = helpers::create_webhook_url(
&state.base_url,
merchant_id,
merchant_connector_account_id_or_connector_name,
);
let authentication_details = business_profile
.authentication_connector_details
.clone()
.get_required_value("authentication_connector_details")
.attach_printable("authentication_connector_details not configured by the merchant")?;
let authentication_response = if helpers::is_merchant_eligible_authentication_service(
merchant_context.get_merchant_account().get_id(),
&state,
)
.await?
{
let auth_response =
<ExternalAuthentication as UnifiedAuthenticationService>::authentication(
&state,
&business_profile,
&payment_method_details.1,
browser_info,
Some(amount),
Some(currency),
authentication::MessageCategory::Payment,
req.device_channel,
authentication.clone(),
return_url,
req.sdk_information,
req.threeds_method_comp_ind,
optional_customer.and_then(|customer| customer.email.map(pii::Email::from)),
webhook_url,
&merchant_connector_account,
&authentication_connector,
Some(payment_intent.payment_id),
)
.await?;
let authentication = external_authentication_update_trackers(
&state,
auth_response,
authentication.clone(),
None,
merchant_context.get_merchant_key_store(),
None,
None,
None,
None,
)
.await?;
authentication::AuthenticationResponse::try_from(authentication)?
} else {
Box::pin(authentication_core::perform_authentication(
&state,
business_profile.merchant_id,
authentication_connector,
payment_method_details.0,
payment_method_details.1,
billing_address
.as_ref()
.map(|address| address.into())
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "billing_address",
})?,
shipping_address.as_ref().map(|address| address.into()),
browser_info,
merchant_connector_account,
Some(amount),
Some(currency),
authentication::MessageCategory::Payment,
req.device_channel,
authentication,
return_url,
req.sdk_information,
req.threeds_method_comp_ind,
optional_customer.and_then(|customer| customer.email.map(pii::Email::from)),
webhook_url,
authentication_details.three_ds_requestor_url.clone(),
payment_intent.psd2_sca_exemption_type,
payment_intent.payment_id,
payment_intent.force_3ds_challenge_trigger.unwrap_or(false),
merchant_context.get_merchant_key_store(),
))
.await?
};
Ok(services::ApplicationResponse::Json(
api_models::payments::PaymentsExternalAuthenticationResponse {
transaction_status: authentication_response.trans_status,
acs_url: authentication_response
.acs_url
.as_ref()
.map(ToString::to_string),
challenge_request: authentication_response.challenge_request,
// If challenge_request_key is None, we send "creq" as a static value which is standard 3DS challenge form field name
challenge_request_key: authentication_response
.challenge_request_key
.or(Some(consts::CREQ_CHALLENGE_REQUEST_KEY.to_string())),
acs_reference_number: authentication_response.acs_reference_number,
acs_trans_id: authentication_response.acs_trans_id,
three_dsserver_trans_id: authentication_response.three_dsserver_trans_id,
acs_signed_content: authentication_response.acs_signed_content,
three_ds_requestor_url: authentication_details.three_ds_requestor_url,
three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url,
},
))
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
pub async fn payment_start_redirection(
state: SessionState,
merchant_context: domain::MerchantContext,
req: api_models::payments::PaymentStartRedirectionRequest,
) -> RouterResponse<serde_json::Value> {
let db = &*state.store;
let key_manager_state = &(&state).into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
&req.id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
//TODO: send valid html error pages in this case, or atleast redirect to valid html error pages
utils::when(
payment_intent.status != storage_enums::IntentStatus::RequiresCustomerAction,
|| {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: "PaymentStartRedirection".to_string(),
field_name: "status".to_string(),
current_value: payment_intent.status.to_string(),
states: ["requires_customer_action".to_string()].join(", "),
})
},
)?;
let payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_intent
.active_attempt_id
.as_ref()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing active attempt in payment_intent")?,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while fetching payment_attempt")?;
let redirection_data = payment_attempt
.redirection_data
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing authentication_data in payment_attempt")?;
Ok(services::ApplicationResponse::Form(Box::new(
services::RedirectionFormData {
redirect_form: redirection_data,
payment_method_data: None,
amount: payment_attempt.amount_details.get_net_amount().to_string(),
currency: payment_intent.amount_details.currency.to_string(),
},
)))
}
#[instrument(skip_all)]
pub async fn get_extended_card_info(
state: SessionState,
merchant_id: id_type::MerchantId,
payment_id: id_type::PaymentId,
) -> RouterResponse<payments_api::ExtendedCardInfoResponse> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = helpers::get_redis_key_for_extended_card_info(&merchant_id, &payment_id);
let payload = redis_conn
.get_key::<String>(&key.into())
.await
.change_context(errors::ApiErrorResponse::ExtendedCardInfoNotFound)?;
Ok(services::ApplicationResponse::Json(
payments_api::ExtendedCardInfoResponse { payload },
))
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub async fn payments_manual_update(
state: SessionState,
req: api_models::payments::PaymentsManualUpdateRequest,
) -> RouterResponse<api_models::payments::PaymentsManualUpdateResponse> {
let api_models::payments::PaymentsManualUpdateRequest {
payment_id,
attempt_id,
merchant_id,
attempt_status,
error_code,
error_message,
error_reason,
connector_transaction_id,
} = req;
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the key store by merchant_id")?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the merchant_account by merchant_id")?;
let payment_attempt = state
.store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_id,
&merchant_id,
&attempt_id.clone(),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable(
"Error while fetching the payment_attempt by payment_id, merchant_id and attempt_id",
)?;
let payment_intent = state
.store
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Error while fetching the payment_intent by payment_id, merchant_id")?;
let option_gsm = if let Some(((code, message), connector_name)) = error_code
.as_ref()
.zip(error_message.as_ref())
.zip(payment_attempt.connector.as_ref())
{
helpers::get_gsm_record(
&state,
Some(code.to_string()),
Some(message.to_string()),
connector_name.to_string(),
// We need to get the unified_code and unified_message of the Authorize flow
"Authorize".to_string(),
)
.await
} else {
None
};
// Update the payment_attempt
let attempt_update = storage::PaymentAttemptUpdate::ManualUpdate {
status: attempt_status,
error_code,
error_message,
error_reason,
updated_by: merchant_account.storage_scheme.to_string(),
unified_code: option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone()),
unified_message: option_gsm.and_then(|gsm| gsm.unified_message),
connector_transaction_id,
};
let updated_payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_attempt.clone(),
attempt_update,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Error while updating the payment_attempt")?;
// If the payment_attempt is active attempt for an intent, update the intent status
if payment_intent.active_attempt.get_id() == payment_attempt.attempt_id {
let intent_status = enums::IntentStatus::foreign_from(updated_payment_attempt.status);
let payment_intent_update = storage::PaymentIntentUpdate::ManualUpdate {
status: Some(intent_status),
updated_by: merchant_account.storage_scheme.to_string(),
};
state
.store
.update_payment_intent(
key_manager_state,
payment_intent,
payment_intent_update,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Error while updating payment_intent")?;
}
Ok(services::ApplicationResponse::Json(
api_models::payments::PaymentsManualUpdateResponse {
payment_id: updated_payment_attempt.payment_id,
attempt_id: updated_payment_attempt.attempt_id,
merchant_id: updated_payment_attempt.merchant_id,
attempt_status: updated_payment_attempt.status,
error_code: updated_payment_attempt.error_code,
error_message: updated_payment_attempt.error_message,
error_reason: updated_payment_attempt.error_reason,
connector_transaction_id: updated_payment_attempt.connector_transaction_id,
},
))
}
// Trait for Eligibility Checks
#[cfg(feature = "v1")]
#[async_trait::async_trait]
trait EligibilityCheck {
type Output;
// Determine if the check should be run based on the runtime checks
async fn should_run(
&self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
) -> CustomResult<bool, errors::ApiErrorResponse>;
// Run the actual check and return the SDK Next Action if applicable
async fn execute_check(
&self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_elgibility_data: &PaymentEligibilityData,
business_profile: &domain::Profile,
) -> CustomResult<Self::Output, errors::ApiErrorResponse>;
fn transform(output: Self::Output) -> Option<api_models::payments::SdkNextAction>;
}
// Result of an Eligibility Check
#[cfg(feature = "v1")]
#[derive(Debug, Clone)]
pub enum CheckResult {
Allow,
Deny { message: String },
}
#[cfg(feature = "v1")]
impl From<CheckResult> for Option<api_models::payments::SdkNextAction> {
fn from(result: CheckResult) -> Self {
match result {
CheckResult::Allow => None,
CheckResult::Deny { message } => Some(api_models::payments::SdkNextAction {
next_action: api_models::payments::NextActionCall::Deny { message },
}),
}
}
}
// Perform Blocklist Check for the Card Number provided in Payment Method Data
#[cfg(feature = "v1")]
struct BlockListCheck;
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl EligibilityCheck for BlockListCheck {
type Output = CheckResult;
async fn should_run(
&self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
) -> CustomResult<bool, errors::ApiErrorResponse> {
let merchant_id = merchant_context.get_merchant_account().get_id();
let blocklist_enabled_key = merchant_id.get_blocklist_guard_key();
let blocklist_guard_enabled = state
.store
.find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string()))
.await;
Ok(match blocklist_guard_enabled {
Ok(config) => serde_json::from_str(&config.config).unwrap_or(false),
// If it is not present in db we are defaulting it to false
Err(inner) => {
if !inner.current_context().is_db_not_found() {
logger::error!("Error fetching guard blocklist enabled config {:?}", inner);
}
false
}
})
}
async fn execute_check(
&self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_elgibility_data: &PaymentEligibilityData,
_business_profile: &domain::Profile,
) -> CustomResult<CheckResult, errors::ApiErrorResponse> {
let should_payment_be_blocked = blocklist_utils::should_payment_be_blocked(
state,
merchant_context,
&payment_elgibility_data.payment_method_data,
)
.await?;
if should_payment_be_blocked {
Ok(CheckResult::Deny {
message: "Card number is blocklisted".to_string(),
})
} else {
Ok(CheckResult::Allow)
}
}
fn transform(output: CheckResult) -> Option<api_models::payments::SdkNextAction> {
output.into()
}
}
// Perform Card Testing Gaurd Check
#[cfg(feature = "v1")]
struct CardTestingCheck;
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl EligibilityCheck for CardTestingCheck {
type Output = CheckResult;
async fn should_run(
&self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
) -> CustomResult<bool, errors::ApiErrorResponse> {
// This check is always run as there is no runtime config enablement
Ok(true)
}
async fn execute_check(
&self,
state: &SessionState,
_merchant_context: &domain::MerchantContext,
payment_elgibility_data: &PaymentEligibilityData,
business_profile: &domain::Profile,
) -> CustomResult<CheckResult, errors::ApiErrorResponse> {
match &payment_elgibility_data.payment_method_data {
Some(domain::PaymentMethodData::Card(card)) => {
match card_testing_guard_utils::validate_card_testing_guard_checks(
state,
payment_elgibility_data
.browser_info
.as_ref()
.map(|browser_info| browser_info.peek()),
card.card_number.clone(),
&payment_elgibility_data.payment_intent.customer_id,
business_profile,
)
.await
{
// If validation succeeds, allow the payment
Ok(_) => Ok(CheckResult::Allow),
// If validation fails, check the error type
Err(e) => match e.current_context() {
// If it's a PreconditionFailed error, deny with message
errors::ApiErrorResponse::PreconditionFailed { message } => {
Ok(CheckResult::Deny {
message: message.to_string(),
})
}
// For any other error, propagate it
_ => Err(e),
},
}
}
// If payment method is not card, allow
_ => Ok(CheckResult::Allow),
}
}
fn transform(output: CheckResult) -> Option<api_models::payments::SdkNextAction> {
output.into()
}
}
// Eligibility Pipeline to run all the eligibility checks in sequence
#[cfg(feature = "v1")]
pub struct EligibilityHandler {
state: SessionState,
merchant_context: domain::MerchantContext,
payment_eligibility_data: PaymentEligibilityData,
business_profile: domain::Profile,
}
#[cfg(feature = "v1")]
impl EligibilityHandler {
fn new(
state: SessionState,
merchant_context: domain::MerchantContext,
payment_eligibility_data: PaymentEligibilityData,
business_profile: domain::Profile,
) -> Self {
Self {
state,
merchant_context,
payment_eligibility_data,
business_profile,
}
}
async fn run_check<C: EligibilityCheck>(
&self,
check: C,
) -> CustomResult<Option<api_models::payments::SdkNextAction>, errors::ApiErrorResponse> {
let should_run = check
.should_run(&self.state, &self.merchant_context)
.await?;
Ok(match should_run {
true => check
.execute_check(
&self.state,
&self.merchant_context,
&self.payment_eligibility_data,
&self.business_profile,
)
.await
.map(C::transform)?,
false => None,
})
}
}
#[cfg(all(feature = "oltp", feature = "v1"))]
pub async fn payments_submit_eligibility(
state: SessionState,
merchant_context: domain::MerchantContext,
req: api_models::payments::PaymentsEligibilityRequest,
payment_id: id_type::PaymentId,
) -> RouterResponse<api_models::payments::PaymentsEligibilityResponse> {
let key_manager_state = &(&state).into();
let payment_eligibility_data =
PaymentEligibilityData::from_request(&state, &merchant_context, &req).await?;
let profile_id = payment_eligibility_data
.payment_intent
.profile_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let eligibility_handler = EligibilityHandler::new(
state,
merchant_context,
payment_eligibility_data,
business_profile,
);
// Run the checks in sequence, short-circuiting on the first that returns a next action
let sdk_next_action = eligibility_handler
.run_check(BlockListCheck)
.await
.transpose()
.async_or_else(|| async {
eligibility_handler
.run_check(CardTestingCheck)
.await
.transpose()
})
.await
.transpose()?
.unwrap_or(api_models::payments::SdkNextAction {
next_action: api_models::payments::NextActionCall::Confirm,
});
Ok(services::ApplicationResponse::Json(
api_models::payments::PaymentsEligibilityResponse {
payment_id,
sdk_next_action,
},
))
}
pub trait PaymentMethodChecker<F> {
fn should_update_in_post_update_tracker(&self) -> bool;
fn should_update_in_update_tracker(&self) -> bool;
}
#[cfg(feature = "v1")]
impl<F: Clone> PaymentMethodChecker<F> for PaymentData<F> {
fn should_update_in_post_update_tracker(&self) -> bool {
let payment_method_type = self
.payment_intent
.tax_details
.as_ref()
.and_then(|tax_details| tax_details.payment_method_type.as_ref().map(|pmt| pmt.pmt));
matches!(
payment_method_type,
Some(storage_enums::PaymentMethodType::Paypal)
)
}
fn should_update_in_update_tracker(&self) -> bool {
let payment_method_type = self
.payment_intent
.tax_details
.as_ref()
.and_then(|tax_details| tax_details.payment_method_type.as_ref().map(|pmt| pmt.pmt));
matches!(
payment_method_type,
Some(storage_enums::PaymentMethodType::ApplePay)
| Some(storage_enums::PaymentMethodType::GooglePay)
)
}
}
pub trait OperationSessionGetters<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt;
#[cfg(feature = "v2")]
fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt>;
fn get_payment_intent(&self) -> &storage::PaymentIntent;
#[cfg(feature = "v2")]
fn get_client_secret(&self) -> &Option<Secret<String>>;
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod>;
fn get_payment_method_token(&self) -> Option<&PaymentMethodToken>;
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds>;
fn get_address(&self) -> &PaymentAddress;
fn get_creds_identifier(&self) -> Option<&str>;
fn get_token(&self) -> Option<&str>;
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData>;
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse>;
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey>;
fn get_setup_mandate(&self) -> Option<&MandateData>;
fn get_poll_config(&self) -> Option<router_types::PollConfig>;
fn get_authentication(
&self,
) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore>;
fn get_frm_message(&self) -> Option<FraudCheck>;
fn get_refunds(&self) -> Vec<diesel_refund::Refund>;
fn get_disputes(&self) -> Vec<storage::Dispute>;
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization>;
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>>;
fn get_recurring_details(&self) -> Option<&RecurringDetails>;
// TODO: this should be a mandatory field, should we throw an error instead of returning an Option?
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId>;
fn get_currency(&self) -> storage_enums::Currency;
fn get_amount(&self) -> api::Amount;
fn get_payment_attempt_connector(&self) -> Option<&str>;
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address>;
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData>;
fn get_sessions_token(&self) -> Vec<api::SessionToken>;
fn get_token_data(&self) -> Option<&storage::PaymentTokenData>;
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails>;
fn get_force_sync(&self) -> Option<bool>;
#[cfg(feature = "v1")]
fn get_all_keys_required(&self) -> Option<bool>;
fn get_capture_method(&self) -> Option<enums::CaptureMethod>;
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId>;
#[cfg(feature = "v2")]
fn get_merchant_connector_details(
&self,
) -> Option<common_types::domain::MerchantConnectorAuthDetails>;
fn get_connector_customer_id(&self) -> Option<String>;
#[cfg(feature = "v1")]
fn get_whole_connector_response(&self) -> Option<Secret<String>>;
#[cfg(feature = "v1")]
fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation>;
#[cfg(feature = "v2")]
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt>;
#[cfg(feature = "v2")]
fn get_pre_routing_result(
&self,
) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>>;
#[cfg(feature = "v2")]
fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails>;
#[cfg(feature = "v1")]
fn get_click_to_pay_service_details(&self) -> Option<&api_models::payments::CtpServiceDetails>;
#[cfg(feature = "v1")]
fn get_is_manual_retry_enabled(&self) -> Option<bool>;
}
pub trait OperationSessionSetters<F> {
// Setter functions for PaymentData
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent);
#[cfg(feature = "v2")]
fn set_client_secret(&mut self, client_secret: Option<Secret<String>>);
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt);
fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>);
fn set_payment_method_token(&mut self, payment_method_token: Option<PaymentMethodToken>);
fn set_email_if_not_present(&mut self, email: pii::Email);
fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>);
fn set_pm_token(&mut self, token: String);
fn set_connector_customer_id(&mut self, customer_id: Option<String>);
fn push_sessions_token(&mut self, token: api::SessionToken);
fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>);
fn set_merchant_connector_id_in_attempt(
&mut self,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
);
fn set_card_network(&mut self, card_network: enums::CardNetwork);
fn set_co_badged_card_data(
&mut self,
debit_routing_output: &api_models::open_router::DebitRoutingOutput,
);
#[cfg(feature = "v1")]
fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod);
fn set_frm_message(&mut self, frm_message: FraudCheck);
fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus);
fn set_authentication_type_in_attempt(
&mut self,
authentication_type: Option<enums::AuthenticationType>,
);
fn set_recurring_mandate_payment_data(
&mut self,
recurring_mandate_payment_data:
hyperswitch_domain_models::router_data::RecurringMandatePaymentData,
);
fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds);
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
);
#[cfg(feature = "v1")]
fn set_straight_through_algorithm_in_payment_attempt(
&mut self,
straight_through_algorithm: serde_json::Value,
);
#[cfg(feature = "v2")]
fn set_prerouting_algorithm_in_payment_intent(
&mut self,
straight_through_algorithm: storage::PaymentRoutingInfo,
);
fn set_connector_in_payment_attempt(&mut self, connector: Option<String>);
#[cfg(feature = "v1")]
fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation);
#[cfg(feature = "v2")]
fn set_connector_request_reference_id(&mut self, reference_id: Option<String>);
fn set_connector_response_reference_id(&mut self, reference_id: Option<String>);
#[cfg(feature = "v2")]
fn set_vault_session_details(
&mut self,
external_vault_session_details: Option<api::VaultSessionDetails>,
);
fn set_routing_approach_in_attempt(&mut self, routing_approach: Option<enums::RoutingApproach>);
fn set_connector_request_reference_id_in_payment_attempt(
&mut self,
connector_request_reference_id: String,
);
#[cfg(feature = "v2")]
fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>);
}
#[cfg(feature = "v1")]
impl<F: Clone> OperationSessionGetters<F> for PaymentData<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
&self.payment_attempt
}
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
}
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> {
self.payment_method_info.as_ref()
}
fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {
self.payment_method_token.as_ref()
}
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {
self.mandate_id.as_ref()
}
// what is this address find out and not required remove this
fn get_address(&self) -> &PaymentAddress {
&self.address
}
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> {
self.payment_attempt.merchant_connector_id.clone()
}
fn get_creds_identifier(&self) -> Option<&str> {
self.creds_identifier.as_deref()
}
fn get_token(&self) -> Option<&str> {
self.token.as_deref()
}
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> {
self.multiple_capture_data.as_ref()
}
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> {
self.payment_link_data.clone()
}
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> {
self.ephemeral_key.clone()
}
fn get_setup_mandate(&self) -> Option<&MandateData> {
self.setup_mandate.as_ref()
}
fn get_poll_config(&self) -> Option<router_types::PollConfig> {
self.poll_config.clone()
}
fn get_authentication(
&self,
) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore>
{
self.authentication.as_ref()
}
fn get_frm_message(&self) -> Option<FraudCheck> {
self.frm_message.clone()
}
fn get_refunds(&self) -> Vec<diesel_refund::Refund> {
self.refunds.clone()
}
fn get_disputes(&self) -> Vec<storage::Dispute> {
self.disputes.clone()
}
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> {
self.authorizations.clone()
}
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> {
self.attempts.clone()
}
fn get_recurring_details(&self) -> Option<&RecurringDetails> {
self.recurring_details.as_ref()
}
#[cfg(feature = "v1")]
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> {
self.payment_intent.profile_id.as_ref()
}
#[cfg(feature = "v2")]
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> {
Some(&self.payment_intent.profile_id)
}
fn get_currency(&self) -> storage_enums::Currency {
self.currency
}
fn get_amount(&self) -> api::Amount {
self.amount
}
fn get_payment_attempt_connector(&self) -> Option<&str> {
self.payment_attempt.connector.as_deref()
}
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> {
self.address.get_payment_method_billing().cloned()
}
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> {
self.payment_method_data.as_ref()
}
fn get_sessions_token(&self) -> Vec<api::SessionToken> {
self.sessions_token.clone()
}
fn get_token_data(&self) -> Option<&storage::PaymentTokenData> {
self.token_data.as_ref()
}
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> {
self.mandate_connector.as_ref()
}
fn get_force_sync(&self) -> Option<bool> {
self.force_sync
}
fn get_all_keys_required(&self) -> Option<bool> {
self.all_keys_required
}
fn get_whole_connector_response(&self) -> Option<Secret<String>> {
self.whole_connector_response.clone()
}
#[cfg(feature = "v1")]
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.payment_attempt.capture_method
}
#[cfg(feature = "v1")]
fn get_vault_operation(&self) -> Option<&domain_payments::VaultOperation> {
self.vault_operation.as_ref()
}
fn get_connector_customer_id(&self) -> Option<String> {
self.connector_customer_id.clone()
}
fn get_click_to_pay_service_details(&self) -> Option<&api_models::payments::CtpServiceDetails> {
self.service_details.as_ref()
}
fn get_is_manual_retry_enabled(&self) -> Option<bool> {
self.is_manual_retry_enabled
}
// #[cfg(feature = "v2")]
// fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
// Some(self.payment_intent.capture_method)
// }
// #[cfg(feature = "v2")]
// fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {
// todo!();
// }
}
#[cfg(feature = "v1")]
impl<F: Clone> OperationSessionSetters<F> for PaymentData<F> {
// Setters Implementation
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) {
self.payment_attempt = payment_attempt;
}
fn set_payment_method_data(&mut self, payment_method_data: Option<domain::PaymentMethodData>) {
self.payment_method_data = payment_method_data;
}
fn set_payment_method_token(&mut self, payment_method_token: Option<PaymentMethodToken>) {
self.payment_method_token = payment_method_token;
}
fn set_payment_method_id_in_attempt(&mut self, payment_method_id: Option<String>) {
self.payment_attempt.payment_method_id = payment_method_id;
}
fn set_email_if_not_present(&mut self, email: pii::Email) {
self.email = self.email.clone().or(Some(email));
}
fn set_pm_token(&mut self, token: String) {
self.pm_token = Some(token);
}
fn set_connector_customer_id(&mut self, customer_id: Option<String>) {
self.connector_customer_id = customer_id;
}
fn push_sessions_token(&mut self, token: api::SessionToken) {
self.sessions_token.push(token);
}
fn set_surcharge_details(&mut self, surcharge_details: Option<types::SurchargeDetails>) {
self.surcharge_details = surcharge_details;
}
fn set_merchant_connector_id_in_attempt(
&mut self,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
) {
self.payment_attempt.merchant_connector_id = merchant_connector_id;
}
fn set_card_network(&mut self, card_network: enums::CardNetwork) {
match &mut self.payment_method_data {
Some(domain::PaymentMethodData::Card(card)) => {
logger::debug!("Setting card network: {:?}", card_network);
card.card_network = Some(card_network);
}
Some(domain::PaymentMethodData::Wallet(wallet_data)) => match wallet_data {
hyperswitch_domain_models::payment_method_data::WalletData::ApplePay(wallet) => {
logger::debug!("Setting Apple Pay card network: {:?}", card_network);
wallet.payment_method.network = card_network.to_string();
}
_ => {
logger::debug!("Wallet type does not support setting card network.");
}
},
_ => {
logger::warn!("Payment method data does not support setting card network.");
}
}
}
fn set_co_badged_card_data(
&mut self,
debit_routing_output: &api_models::open_router::DebitRoutingOutput,
) {
let co_badged_card_data =
api_models::payment_methods::CoBadgedCardData::from(debit_routing_output);
let card_type = debit_routing_output
.card_type
.clone()
.to_string()
.to_uppercase();
if let Some(domain::PaymentMethodData::Card(card)) = &mut self.payment_method_data {
card.co_badged_card_data = Some(co_badged_card_data);
card.card_type = Some(card_type);
logger::debug!("set co-badged card data in payment method data");
};
}
#[cfg(feature = "v1")]
fn set_capture_method_in_attempt(&mut self, capture_method: enums::CaptureMethod) {
self.payment_attempt.capture_method = Some(capture_method);
}
fn set_frm_message(&mut self, frm_message: FraudCheck) {
self.frm_message = Some(frm_message);
}
fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) {
self.payment_intent.status = status;
}
fn set_authentication_type_in_attempt(
&mut self,
authentication_type: Option<enums::AuthenticationType>,
) {
self.payment_attempt.authentication_type = authentication_type;
}
fn set_recurring_mandate_payment_data(
&mut self,
recurring_mandate_payment_data:
hyperswitch_domain_models::router_data::RecurringMandatePaymentData,
) {
self.recurring_mandate_payment_data = Some(recurring_mandate_payment_data);
}
fn set_mandate_id(&mut self, mandate_id: api_models::payments::MandateIds) {
self.mandate_id = Some(mandate_id);
}
#[cfg(feature = "v1")]
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
) {
self.payment_intent.setup_future_usage = Some(setup_future_usage);
}
#[cfg(feature = "v2")]
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
) {
self.payment_intent.setup_future_usage = setup_future_usage;
}
#[cfg(feature = "v1")]
fn set_straight_through_algorithm_in_payment_attempt(
&mut self,
straight_through_algorithm: serde_json::Value,
) {
self.payment_attempt.straight_through_algorithm = Some(straight_through_algorithm);
}
fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) {
self.payment_attempt.connector = connector;
}
fn set_vault_operation(&mut self, vault_operation: domain_payments::VaultOperation) {
self.vault_operation = Some(vault_operation);
}
fn set_routing_approach_in_attempt(
&mut self,
routing_approach: Option<enums::RoutingApproach>,
) {
self.payment_attempt.routing_approach = routing_approach;
}
fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) {
self.payment_attempt.connector_response_reference_id = reference_id;
}
fn set_connector_request_reference_id_in_payment_attempt(
&mut self,
connector_request_reference_id: String,
) {
self.payment_attempt.connector_request_reference_id = Some(connector_request_reference_id);
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionGetters<F> for PaymentIntentData<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
todo!()
}
#[cfg(feature = "v2")]
fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> {
todo!()
}
fn get_client_secret(&self) -> &Option<Secret<String>> {
&self.client_secret
}
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
}
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> {
todo!()
}
fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {
todo!()
}
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {
todo!()
}
// what is this address find out and not required remove this
fn get_address(&self) -> &PaymentAddress {
todo!()
}
fn get_creds_identifier(&self) -> Option<&str> {
todo!()
}
fn get_token(&self) -> Option<&str> {
todo!()
}
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> {
todo!()
}
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> {
todo!()
}
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> {
todo!()
}
fn get_setup_mandate(&self) -> Option<&MandateData> {
todo!()
}
fn get_poll_config(&self) -> Option<router_types::PollConfig> {
todo!()
}
fn get_authentication(
&self,
) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore>
{
todo!()
}
fn get_frm_message(&self) -> Option<FraudCheck> {
todo!()
}
fn get_refunds(&self) -> Vec<diesel_refund::Refund> {
todo!()
}
fn get_disputes(&self) -> Vec<storage::Dispute> {
todo!()
}
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> {
todo!()
}
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> {
todo!()
}
fn get_recurring_details(&self) -> Option<&RecurringDetails> {
todo!()
}
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> {
Some(&self.payment_intent.profile_id)
}
fn get_currency(&self) -> storage_enums::Currency {
self.payment_intent.amount_details.currency
}
fn get_amount(&self) -> api::Amount {
todo!()
}
fn get_payment_attempt_connector(&self) -> Option<&str> {
todo!()
}
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> {
todo!()
}
fn get_connector_customer_id(&self) -> Option<String> {
self.connector_customer_id.clone()
}
fn get_merchant_connector_details(
&self,
) -> Option<common_types::domain::MerchantConnectorAuthDetails> {
todo!()
}
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> {
todo!()
}
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> {
todo!()
}
fn get_sessions_token(&self) -> Vec<api::SessionToken> {
self.sessions_token.clone()
}
fn get_token_data(&self) -> Option<&storage::PaymentTokenData> {
todo!()
}
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> {
todo!()
}
fn get_force_sync(&self) -> Option<bool> {
todo!()
}
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
todo!()
}
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {
todo!();
}
fn get_pre_routing_result(
&self,
) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> {
None
}
fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {
self.vault_session_details.clone()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionSetters<F> for PaymentIntentData<F> {
fn set_prerouting_algorithm_in_payment_intent(
&mut self,
straight_through_algorithm: storage::PaymentRoutingInfo,
) {
self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm);
}
// Setters Implementation
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) {
self.client_secret = client_secret;
}
fn set_payment_attempt(&mut self, _payment_attempt: storage::PaymentAttempt) {
todo!()
}
fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) {
todo!()
}
fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {
todo!()
}
fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {
todo!()
}
fn set_card_network(&mut self, card_network: enums::CardNetwork) {
todo!()
}
fn set_co_badged_card_data(
&mut self,
debit_routing_output: &api_models::open_router::DebitRoutingOutput,
) {
todo!()
}
fn set_email_if_not_present(&mut self, _email: pii::Email) {
todo!()
}
fn set_pm_token(&mut self, _token: String) {
todo!()
}
fn set_connector_customer_id(&mut self, customer_id: Option<String>) {
self.connector_customer_id = customer_id;
}
fn push_sessions_token(&mut self, token: api::SessionToken) {
self.sessions_token.push(token);
}
fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) {
todo!()
}
fn set_merchant_connector_id_in_attempt(
&mut self,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
) {
todo!()
}
fn set_frm_message(&mut self, _frm_message: FraudCheck) {
todo!()
}
fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) {
self.payment_intent.status = status;
}
fn set_authentication_type_in_attempt(
&mut self,
_authentication_type: Option<enums::AuthenticationType>,
) {
todo!()
}
fn set_recurring_mandate_payment_data(
&mut self,
_recurring_mandate_payment_data:
hyperswitch_domain_models::router_data::RecurringMandatePaymentData,
) {
todo!()
}
fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) {
todo!()
}
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
) {
self.payment_intent.setup_future_usage = setup_future_usage;
}
fn set_connector_in_payment_attempt(&mut self, _connector: Option<String>) {
todo!()
}
fn set_connector_request_reference_id(&mut self, reference_id: Option<String>) {
todo!()
}
fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) {
todo!()
}
fn set_vault_session_details(
&mut self,
vault_session_details: Option<api::VaultSessionDetails>,
) {
self.vault_session_details = vault_session_details;
}
fn set_routing_approach_in_attempt(
&mut self,
routing_approach: Option<enums::RoutingApproach>,
) {
todo!()
}
fn set_connector_request_reference_id_in_payment_attempt(
&mut self,
connector_request_reference_id: String,
) {
todo!()
}
fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionGetters<F> for PaymentConfirmData<F> {
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
&self.payment_attempt
}
#[cfg(feature = "v2")]
fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> {
todo!()
}
fn get_client_secret(&self) -> &Option<Secret<String>> {
todo!()
}
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
}
fn get_merchant_connector_details(
&self,
) -> Option<common_types::domain::MerchantConnectorAuthDetails> {
self.merchant_connector_details.clone()
}
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> {
todo!()
}
fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {
todo!()
}
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {
todo!()
}
fn get_address(&self) -> &PaymentAddress {
&self.payment_address
}
fn get_creds_identifier(&self) -> Option<&str> {
None
}
fn get_token(&self) -> Option<&str> {
todo!()
}
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> {
todo!()
}
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> {
todo!()
}
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> {
todo!()
}
fn get_setup_mandate(&self) -> Option<&MandateData> {
todo!()
}
fn get_poll_config(&self) -> Option<router_types::PollConfig> {
todo!()
}
fn get_authentication(
&self,
) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore>
{
todo!()
}
fn get_frm_message(&self) -> Option<FraudCheck> {
todo!()
}
fn get_refunds(&self) -> Vec<diesel_refund::Refund> {
todo!()
}
fn get_disputes(&self) -> Vec<storage::Dispute> {
todo!()
}
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> {
todo!()
}
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> {
todo!()
}
fn get_recurring_details(&self) -> Option<&RecurringDetails> {
todo!()
}
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> {
Some(&self.payment_intent.profile_id)
}
fn get_currency(&self) -> storage_enums::Currency {
self.payment_intent.amount_details.currency
}
fn get_amount(&self) -> api::Amount {
todo!()
}
fn get_payment_attempt_connector(&self) -> Option<&str> {
self.payment_attempt.connector.as_deref()
}
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> {
self.payment_attempt.merchant_connector_id.clone()
}
fn get_connector_customer_id(&self) -> Option<String> {
todo!()
}
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> {
todo!()
}
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> {
self.payment_method_data.as_ref()
}
fn get_sessions_token(&self) -> Vec<api::SessionToken> {
todo!()
}
fn get_token_data(&self) -> Option<&storage::PaymentTokenData> {
todo!()
}
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> {
todo!()
}
fn get_force_sync(&self) -> Option<bool> {
todo!()
}
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
todo!()
}
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {
Some(&self.payment_attempt)
}
fn get_pre_routing_result(
&self,
) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> {
self.get_payment_intent()
.prerouting_algorithm
.clone()
.and_then(|pre_routing_algorithm| pre_routing_algorithm.pre_routing_results)
}
fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionSetters<F> for PaymentConfirmData<F> {
#[cfg(feature = "v2")]
fn set_prerouting_algorithm_in_payment_intent(
&mut self,
straight_through_algorithm: storage::PaymentRoutingInfo,
) {
self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm);
}
// Setters Implementation
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) {
todo!()
}
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) {
self.payment_attempt = payment_attempt;
}
fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) {
todo!()
}
fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {
todo!()
}
fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {
todo!()
}
fn set_email_if_not_present(&mut self, _email: pii::Email) {
todo!()
}
fn set_pm_token(&mut self, _token: String) {
todo!()
}
fn set_connector_customer_id(&mut self, _customer_id: Option<String>) {
// TODO: handle this case. Should we add connector_customer_id in paymentConfirmData?
}
fn push_sessions_token(&mut self, _token: api::SessionToken) {
todo!()
}
fn set_card_network(&mut self, card_network: enums::CardNetwork) {
todo!()
}
fn set_co_badged_card_data(
&mut self,
debit_routing_output: &api_models::open_router::DebitRoutingOutput,
) {
todo!()
}
fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) {
todo!()
}
#[track_caller]
fn set_merchant_connector_id_in_attempt(
&mut self,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
) {
self.payment_attempt.merchant_connector_id = merchant_connector_id;
}
fn set_frm_message(&mut self, _frm_message: FraudCheck) {
todo!()
}
fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) {
self.payment_intent.status = status;
}
fn set_authentication_type_in_attempt(
&mut self,
_authentication_type: Option<enums::AuthenticationType>,
) {
todo!()
}
fn set_recurring_mandate_payment_data(
&mut self,
_recurring_mandate_payment_data:
hyperswitch_domain_models::router_data::RecurringMandatePaymentData,
) {
todo!()
}
fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) {
todo!()
}
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
) {
self.payment_intent.setup_future_usage = setup_future_usage;
}
fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) {
self.payment_attempt.connector = connector;
}
fn set_connector_request_reference_id(&mut self, reference_id: Option<String>) {
self.payment_attempt.connector_request_reference_id = reference_id;
}
fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) {
self.payment_attempt.connector_response_reference_id = reference_id;
}
fn set_vault_session_details(
&mut self,
external_vault_session_details: Option<api::VaultSessionDetails>,
) {
todo!()
}
fn set_routing_approach_in_attempt(
&mut self,
routing_approach: Option<enums::RoutingApproach>,
) {
todo!()
}
fn set_connector_request_reference_id_in_payment_attempt(
&mut self,
connector_request_reference_id: String,
) {
todo!()
}
fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionGetters<F> for PaymentStatusData<F> {
#[track_caller]
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
&self.payment_attempt
}
#[cfg(feature = "v2")]
fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> {
todo!()
}
fn get_client_secret(&self) -> &Option<Secret<String>> {
todo!()
}
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
}
fn get_merchant_connector_details(
&self,
) -> Option<common_types::domain::MerchantConnectorAuthDetails> {
self.merchant_connector_details.clone()
}
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> {
todo!()
}
fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {
todo!()
}
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {
todo!()
}
fn get_address(&self) -> &PaymentAddress {
&self.payment_address
}
fn get_creds_identifier(&self) -> Option<&str> {
None
}
fn get_token(&self) -> Option<&str> {
todo!()
}
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> {
todo!()
}
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> {
todo!()
}
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> {
todo!()
}
fn get_setup_mandate(&self) -> Option<&MandateData> {
todo!()
}
fn get_poll_config(&self) -> Option<router_types::PollConfig> {
todo!()
}
fn get_authentication(
&self,
) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore>
{
todo!()
}
fn get_frm_message(&self) -> Option<FraudCheck> {
todo!()
}
fn get_refunds(&self) -> Vec<diesel_refund::Refund> {
todo!()
}
fn get_disputes(&self) -> Vec<storage::Dispute> {
todo!()
}
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> {
todo!()
}
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> {
todo!()
}
fn get_recurring_details(&self) -> Option<&RecurringDetails> {
todo!()
}
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> {
Some(&self.payment_intent.profile_id)
}
fn get_currency(&self) -> storage_enums::Currency {
self.payment_intent.amount_details.currency
}
fn get_amount(&self) -> api::Amount {
todo!()
}
fn get_payment_attempt_connector(&self) -> Option<&str> {
todo!()
}
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> {
todo!()
}
fn get_connector_customer_id(&self) -> Option<String> {
todo!()
}
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> {
todo!()
}
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> {
todo!()
}
fn get_sessions_token(&self) -> Vec<api::SessionToken> {
todo!()
}
fn get_token_data(&self) -> Option<&storage::PaymentTokenData> {
todo!()
}
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> {
todo!()
}
fn get_force_sync(&self) -> Option<bool> {
todo!()
}
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
todo!()
}
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {
Some(&self.payment_attempt)
}
fn get_pre_routing_result(
&self,
) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> {
None
}
fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionSetters<F> for PaymentStatusData<F> {
#[cfg(feature = "v2")]
fn set_prerouting_algorithm_in_payment_intent(
&mut self,
straight_through_algorithm: storage::PaymentRoutingInfo,
) {
self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm);
}
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) {
todo!()
}
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) {
self.payment_attempt = payment_attempt;
}
fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) {
todo!()
}
fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {
todo!()
}
fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {
todo!()
}
fn set_email_if_not_present(&mut self, _email: pii::Email) {
todo!()
}
fn set_card_network(&mut self, card_network: enums::CardNetwork) {
todo!()
}
fn set_co_badged_card_data(
&mut self,
debit_routing_output: &api_models::open_router::DebitRoutingOutput,
) {
todo!()
}
fn set_pm_token(&mut self, _token: String) {
todo!()
}
fn set_connector_customer_id(&mut self, _customer_id: Option<String>) {
// TODO: handle this case. Should we add connector_customer_id in paymentConfirmData?
}
fn push_sessions_token(&mut self, _token: api::SessionToken) {
todo!()
}
fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) {
todo!()
}
#[track_caller]
fn set_merchant_connector_id_in_attempt(
&mut self,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
) {
todo!()
}
fn set_frm_message(&mut self, _frm_message: FraudCheck) {
todo!()
}
fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) {
self.payment_intent.status = status;
}
fn set_authentication_type_in_attempt(
&mut self,
_authentication_type: Option<enums::AuthenticationType>,
) {
todo!()
}
fn set_recurring_mandate_payment_data(
&mut self,
_recurring_mandate_payment_data:
hyperswitch_domain_models::router_data::RecurringMandatePaymentData,
) {
todo!()
}
fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) {
todo!()
}
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
) {
self.payment_intent.setup_future_usage = setup_future_usage;
}
fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) {
self.payment_attempt.connector = connector;
}
fn set_connector_request_reference_id(&mut self, reference_id: Option<String>) {
todo!()
}
fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) {
todo!()
}
fn set_vault_session_details(
&mut self,
external_vault_session_details: Option<api::VaultSessionDetails>,
) {
todo!()
}
fn set_routing_approach_in_attempt(
&mut self,
routing_approach: Option<enums::RoutingApproach>,
) {
todo!()
}
fn set_connector_request_reference_id_in_payment_attempt(
&mut self,
connector_request_reference_id: String,
) {
todo!()
}
fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionGetters<F> for PaymentCaptureData<F> {
#[track_caller]
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
&self.payment_attempt
}
#[cfg(feature = "v2")]
fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> {
todo!()
}
fn get_client_secret(&self) -> &Option<Secret<String>> {
todo!()
}
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
}
fn get_merchant_connector_details(
&self,
) -> Option<common_types::domain::MerchantConnectorAuthDetails> {
todo!()
}
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> {
todo!()
}
fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {
todo!()
}
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {
todo!()
}
// what is this address find out and not required remove this
fn get_address(&self) -> &PaymentAddress {
todo!()
}
fn get_creds_identifier(&self) -> Option<&str> {
None
}
fn get_token(&self) -> Option<&str> {
todo!()
}
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> {
todo!()
}
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> {
todo!()
}
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> {
todo!()
}
fn get_setup_mandate(&self) -> Option<&MandateData> {
todo!()
}
fn get_poll_config(&self) -> Option<router_types::PollConfig> {
todo!()
}
fn get_authentication(
&self,
) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore>
{
todo!()
}
fn get_frm_message(&self) -> Option<FraudCheck> {
todo!()
}
fn get_refunds(&self) -> Vec<diesel_refund::Refund> {
todo!()
}
fn get_disputes(&self) -> Vec<storage::Dispute> {
todo!()
}
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> {
todo!()
}
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> {
todo!()
}
fn get_recurring_details(&self) -> Option<&RecurringDetails> {
todo!()
}
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> {
Some(&self.payment_intent.profile_id)
}
fn get_currency(&self) -> storage_enums::Currency {
self.payment_intent.amount_details.currency
}
fn get_amount(&self) -> api::Amount {
todo!()
}
fn get_payment_attempt_connector(&self) -> Option<&str> {
todo!()
}
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> {
todo!()
}
fn get_connector_customer_id(&self) -> Option<String> {
todo!()
}
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> {
todo!()
}
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> {
todo!()
}
fn get_sessions_token(&self) -> Vec<api::SessionToken> {
todo!()
}
fn get_token_data(&self) -> Option<&storage::PaymentTokenData> {
todo!()
}
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> {
todo!()
}
fn get_force_sync(&self) -> Option<bool> {
todo!()
}
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
todo!()
}
#[cfg(feature = "v2")]
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {
Some(&self.payment_attempt)
}
fn get_pre_routing_result(
&self,
) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> {
None
}
fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionSetters<F> for PaymentCaptureData<F> {
#[cfg(feature = "v2")]
fn set_prerouting_algorithm_in_payment_intent(
&mut self,
straight_through_algorithm: storage::PaymentRoutingInfo,
) {
self.payment_intent.prerouting_algorithm = Some(straight_through_algorithm);
}
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
fn set_client_secret(&mut self, client_secret: Option<Secret<String>>) {
todo!()
}
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) {
self.payment_attempt = payment_attempt;
}
fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) {
todo!()
}
fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {
todo!()
}
fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {
todo!()
}
fn set_card_network(&mut self, card_network: enums::CardNetwork) {
todo!()
}
fn set_co_badged_card_data(
&mut self,
debit_routing_output: &api_models::open_router::DebitRoutingOutput,
) {
todo!()
}
fn set_email_if_not_present(&mut self, _email: pii::Email) {
todo!()
}
fn set_pm_token(&mut self, _token: String) {
todo!()
}
fn set_connector_customer_id(&mut self, _customer_id: Option<String>) {
// TODO: handle this case. Should we add connector_customer_id in paymentConfirmData?
}
fn push_sessions_token(&mut self, _token: api::SessionToken) {
todo!()
}
fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) {
todo!()
}
#[track_caller]
fn set_merchant_connector_id_in_attempt(
&mut self,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
) {
todo!()
}
fn set_frm_message(&mut self, _frm_message: FraudCheck) {
todo!()
}
fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) {
self.payment_intent.status = status;
}
fn set_authentication_type_in_attempt(
&mut self,
_authentication_type: Option<enums::AuthenticationType>,
) {
todo!()
}
fn set_recurring_mandate_payment_data(
&mut self,
_recurring_mandate_payment_data:
hyperswitch_domain_models::router_data::RecurringMandatePaymentData,
) {
todo!()
}
fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) {
todo!()
}
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
) {
self.payment_intent.setup_future_usage = setup_future_usage;
}
fn set_connector_in_payment_attempt(&mut self, connector: Option<String>) {
todo!()
}
fn set_connector_request_reference_id(&mut self, reference_id: Option<String>) {
todo!()
}
fn set_connector_response_reference_id(&mut self, reference_id: Option<String>) {
todo!()
}
fn set_vault_session_details(
&mut self,
external_vault_session_details: Option<api::VaultSessionDetails>,
) {
todo!()
}
fn set_routing_approach_in_attempt(
&mut self,
routing_approach: Option<enums::RoutingApproach>,
) {
todo!()
}
fn set_connector_request_reference_id_in_payment_attempt(
&mut self,
connector_request_reference_id: String,
) {
todo!()
}
fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionGetters<F> for PaymentAttemptListData<F> {
#[track_caller]
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
todo!()
}
#[cfg(feature = "v2")]
fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> {
&self.payment_attempt_list
}
fn get_client_secret(&self) -> &Option<Secret<String>> {
todo!()
}
fn get_payment_intent(&self) -> &storage::PaymentIntent {
todo!()
}
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> {
todo!()
}
fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {
todo!()
}
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {
todo!()
}
// what is this address find out and not required remove this
fn get_address(&self) -> &PaymentAddress {
todo!()
}
fn get_creds_identifier(&self) -> Option<&str> {
None
}
fn get_token(&self) -> Option<&str> {
todo!()
}
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> {
todo!()
}
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> {
todo!()
}
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> {
todo!()
}
fn get_setup_mandate(&self) -> Option<&MandateData> {
todo!()
}
fn get_poll_config(&self) -> Option<router_types::PollConfig> {
todo!()
}
fn get_authentication(
&self,
) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore>
{
todo!()
}
fn get_frm_message(&self) -> Option<FraudCheck> {
todo!()
}
fn get_refunds(&self) -> Vec<diesel_refund::Refund> {
todo!()
}
fn get_disputes(&self) -> Vec<storage::Dispute> {
todo!()
}
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> {
todo!()
}
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> {
todo!()
}
fn get_recurring_details(&self) -> Option<&RecurringDetails> {
todo!()
}
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> {
todo!()
}
fn get_currency(&self) -> storage_enums::Currency {
todo!()
}
fn get_amount(&self) -> api::Amount {
todo!()
}
fn get_payment_attempt_connector(&self) -> Option<&str> {
todo!()
}
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> {
todo!()
}
fn get_connector_customer_id(&self) -> Option<String> {
todo!()
}
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> {
todo!()
}
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> {
todo!()
}
fn get_sessions_token(&self) -> Vec<api::SessionToken> {
todo!()
}
fn get_token_data(&self) -> Option<&storage::PaymentTokenData> {
todo!()
}
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> {
todo!()
}
fn get_force_sync(&self) -> Option<bool> {
todo!()
}
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
todo!()
}
#[cfg(feature = "v2")]
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {
todo!()
}
fn get_pre_routing_result(
&self,
) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> {
None
}
fn get_merchant_connector_details(
&self,
) -> Option<common_types::domain::MerchantConnectorAuthDetails> {
todo!()
}
fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionGetters<F> for PaymentCancelData<F> {
#[track_caller]
fn get_payment_attempt(&self) -> &storage::PaymentAttempt {
&self.payment_attempt
}
fn list_payments_attempts(&self) -> &Vec<storage::PaymentAttempt> {
todo!()
}
fn get_client_secret(&self) -> &Option<Secret<String>> {
todo!()
}
fn get_payment_intent(&self) -> &storage::PaymentIntent {
&self.payment_intent
}
fn get_merchant_connector_details(
&self,
) -> Option<common_types::domain::MerchantConnectorAuthDetails> {
todo!()
}
fn get_payment_method_info(&self) -> Option<&domain::PaymentMethod> {
todo!()
}
fn get_payment_method_token(&self) -> Option<&PaymentMethodToken> {
todo!()
}
fn get_mandate_id(&self) -> Option<&payments_api::MandateIds> {
todo!()
}
// what is this address find out and not required remove this
fn get_address(&self) -> &PaymentAddress {
todo!()
}
fn get_creds_identifier(&self) -> Option<&str> {
None
}
fn get_token(&self) -> Option<&str> {
todo!()
}
fn get_multiple_capture_data(&self) -> Option<&types::MultipleCaptureData> {
todo!()
}
fn get_payment_link_data(&self) -> Option<api_models::payments::PaymentLinkResponse> {
todo!()
}
fn get_ephemeral_key(&self) -> Option<ephemeral_key::EphemeralKey> {
todo!()
}
fn get_setup_mandate(&self) -> Option<&MandateData> {
todo!()
}
fn get_poll_config(&self) -> Option<router_types::PollConfig> {
todo!()
}
fn get_authentication(
&self,
) -> Option<&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore>
{
todo!()
}
fn get_frm_message(&self) -> Option<FraudCheck> {
todo!()
}
fn get_refunds(&self) -> Vec<diesel_refund::Refund> {
todo!()
}
fn get_disputes(&self) -> Vec<storage::Dispute> {
todo!()
}
fn get_authorizations(&self) -> Vec<diesel_models::authorization::Authorization> {
todo!()
}
fn get_attempts(&self) -> Option<Vec<storage::PaymentAttempt>> {
todo!()
}
fn get_recurring_details(&self) -> Option<&RecurringDetails> {
todo!()
}
fn get_payment_intent_profile_id(&self) -> Option<&id_type::ProfileId> {
todo!()
}
fn get_currency(&self) -> storage_enums::Currency {
todo!()
}
fn get_amount(&self) -> api::Amount {
todo!()
}
fn get_payment_attempt_connector(&self) -> Option<&str> {
todo!()
}
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> {
todo!()
}
fn get_connector_customer_id(&self) -> Option<String> {
todo!()
}
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> {
todo!()
}
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> {
todo!()
}
fn get_sessions_token(&self) -> Vec<api::SessionToken> {
todo!()
}
fn get_token_data(&self) -> Option<&storage::PaymentTokenData> {
todo!()
}
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> {
todo!()
}
fn get_force_sync(&self) -> Option<bool> {
todo!()
}
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
todo!()
}
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {
None
}
fn get_pre_routing_result(
&self,
) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> {
None
}
fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> OperationSessionSetters<F> for PaymentCancelData<F> {
fn set_payment_intent(&mut self, payment_intent: storage::PaymentIntent) {
self.payment_intent = payment_intent;
}
fn set_client_secret(&mut self, _client_secret: Option<Secret<String>>) {
todo!()
}
fn set_payment_attempt(&mut self, payment_attempt: storage::PaymentAttempt) {
self.payment_attempt = payment_attempt;
}
fn set_payment_method_data(&mut self, _payment_method_data: Option<domain::PaymentMethodData>) {
todo!()
}
fn set_payment_method_token(&mut self, _payment_method_token: Option<PaymentMethodToken>) {
todo!()
}
fn set_email_if_not_present(&mut self, _email: pii::Email) {
todo!()
}
fn set_payment_method_id_in_attempt(&mut self, _payment_method_id: Option<String>) {
todo!()
}
fn set_pm_token(&mut self, _token: String) {
!todo!()
}
fn set_connector_customer_id(&mut self, _customer_id: Option<String>) {
// TODO: handle this case. Should we add connector_customer_id in PaymentCancelData?
}
fn push_sessions_token(&mut self, _token: api::SessionToken) {
todo!()
}
fn set_surcharge_details(&mut self, _surcharge_details: Option<types::SurchargeDetails>) {
todo!()
}
fn set_merchant_connector_id_in_attempt(
&mut self,
_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
) {
todo!()
}
fn set_card_network(&mut self, _card_network: enums::CardNetwork) {
todo!()
}
fn set_co_badged_card_data(
&mut self,
_debit_routing_output: &api_models::open_router::DebitRoutingOutput,
) {
todo!()
}
fn set_frm_message(&mut self, _frm_message: FraudCheck) {
todo!()
}
fn set_payment_intent_status(&mut self, status: storage_enums::IntentStatus) {
self.payment_intent.status = status;
}
fn set_authentication_type_in_attempt(
&mut self,
_authentication_type: Option<enums::AuthenticationType>,
) {
todo!()
}
fn set_recurring_mandate_payment_data(
&mut self,
_recurring_mandate_payment_data:
hyperswitch_domain_models::router_data::RecurringMandatePaymentData,
) {
todo!()
}
fn set_mandate_id(&mut self, _mandate_id: api_models::payments::MandateIds) {
todo!()
}
fn set_setup_future_usage_in_payment_intent(
&mut self,
setup_future_usage: storage_enums::FutureUsage,
) {
todo!()
}
fn set_prerouting_algorithm_in_payment_intent(
&mut self,
prerouting_algorithm: storage::PaymentRoutingInfo,
) {
self.payment_intent.prerouting_algorithm = Some(prerouting_algorithm);
}
fn set_connector_in_payment_attempt(&mut self, _connector: Option<String>) {
todo!()
}
fn set_connector_request_reference_id(&mut self, _reference_id: Option<String>) {
todo!()
}
fn set_connector_response_reference_id(&mut self, _reference_id: Option<String>) {
todo!()
}
fn set_vault_session_details(
&mut self,
_external_vault_session_details: Option<api::VaultSessionDetails>,
) {
todo!()
}
fn set_routing_approach_in_attempt(
&mut self,
_routing_approach: Option<enums::RoutingApproach>,
) {
todo!()
}
fn set_connector_request_reference_id_in_payment_attempt(
&mut self,
_connector_request_reference_id: String,
) {
todo!()
}
fn set_cancellation_reason(&mut self, cancellation_reason: Option<String>) {
self.payment_attempt.cancellation_reason = cancellation_reason;
}
}
| crates/router/src/core/payments.rs | router::src::core::payments | 94,802 | true |
// File: crates/router/src/core/encryption.rs
// Module: router::src::core::encryption
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;
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(
&state.into(),
&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: 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: key_encoded,
};
transfer_key_to_key_manager(&state.into(), req).await
}))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(|v| v.len())
}
| crates/router/src/core/encryption.rs | router::src::core::encryption | 523 | true |
// File: crates/router/src/core/disputes.rs
// Module: router::src::core::disputes
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 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,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_account().get_id(),
&req.dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id,
})?;
core_utils::validate_profile_id_from_auth_layer(profile_id.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(
&(&state).into(),
&dispute.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
dispute.merchant_connector_id.clone(),
)?;
let connector_integration: services::BoxedDisputeConnectorIntegrationInterface<
api::Dsync,
DisputeSyncData,
DisputeSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data = core_utils::construct_dispute_sync_router_data(
&state,
&payment_intent,
&payment_attempt,
&merchant_context,
&dispute,
)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_dispute_failed_response()
.attach_printable("Failed while calling accept dispute connector api")?;
let 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(
&(&state).into(),
merchant_context.get_merchant_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,
merchant_context,
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,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
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,
merchant_context: domain::MerchantContext,
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,
merchant_context.get_merchant_account().get_id().to_owned(),
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,
merchant_context: domain::MerchantContext,
profile_id: Option<common_utils::id_type::ProfileId>,
req: disputes::DisputeId,
) -> RouterResponse<dispute_models::DisputeResponse> {
let db = &state.store;
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
merchant_context.get_merchant_account().get_id(),
&req.dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id,
})?;
core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?;
let dispute_id = dispute.dispute_id.clone();
common_utils::fp_utils::when(
!core_utils::should_proceed_with_accept_dispute(
dispute.dispute_stage,
dispute.dispute_status,
),
|| {
metrics::ACCEPT_DISPUTE_STATUS_VALIDATION_FAILURE_METRIC.add(1, &[]);
Err(errors::ApiErrorResponse::DisputeStatusValidationFailed {
reason: format!(
"This dispute cannot be accepted because the dispute is in {} stage and has {} status",
dispute.dispute_stage, dispute.dispute_status
),
})
},
)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
&dispute.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
dispute.merchant_connector_id.clone(),
)?;
let connector_integration: services::BoxedDisputeConnectorIntegrationInterface<
api::Accept,
AcceptDisputeRequestData,
AcceptDisputeResponse,
> = connector_data.connector.get_connector_integration();
let router_data = core_utils::construct_accept_dispute_router_data(
&state,
&payment_intent,
&payment_attempt,
&merchant_context,
&dispute,
)
.await?;
let response = services::execute_connector_processing_step(
&state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_dispute_failed_response()
.attach_printable("Failed while calling accept dispute connector api")?;
let accept_dispute_response =
response
.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: dispute.connector.clone(),
status_code: err.status_code,
reason: err.reason,
})?;
let update_dispute = diesel_models::dispute::DisputeUpdate::StatusUpdate {
dispute_status: accept_dispute_response.dispute_status,
connector_status: accept_dispute_response.connector_status.clone(),
};
let updated_dispute = db
.update_dispute(dispute.clone(), update_dispute)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("Unable to update dispute with dispute_id: {dispute_id}")
})?;
let dispute_response = api_models::disputes::DisputeResponse::foreign_from(updated_dispute);
Ok(services::ApplicationResponse::Json(dispute_response))
}
#[cfg(feature = "v2")]
#[instrument(skip(state))]
pub async fn submit_evidence(
state: SessionState,
merchant_context: domain::MerchantContext,
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,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_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, &merchant_context, req, &dispute).await?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
&dispute.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
dispute.merchant_connector_id.clone(),
)?;
let connector_integration: services::BoxedDisputeConnectorIntegrationInterface<
api::Evidence,
SubmitEvidenceRequestData,
SubmitEvidenceResponse,
> = connector_data.connector.get_connector_integration();
let router_data = core_utils::construct_submit_evidence_router_data(
&state,
&payment_intent,
&payment_attempt,
&merchant_context,
&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,
&merchant_context,
&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,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_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(),
merchant_context,
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,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_account().get_id(),
&req.dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id,
})?;
core_utils::validate_profile_id_from_auth_layer(profile_id, &dispute)?;
let dispute_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, merchant_context, dispute_evidence).await?;
Ok(services::ApplicationResponse::Json(dispute_evidence_vec))
}
pub async fn delete_evidence(
state: SessionState,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
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,
merchant_context,
connector_id,
fetch_dispute_request,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn fetch_disputes_from_connector(
state: SessionState,
merchant_context: domain::MerchantContext,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
req: FetchDisputesRequestData,
) -> RouterResponse<FetchDisputesResponse> {
let db = &*state.store;
let key_manager_state = &(&state).into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let merchant_connector_account = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
&merchant_connector_id,
merchant_context.get_merchant_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(),
&merchant_context,
)
.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,
)
.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(
state: &SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
option_dispute: Option<diesel_models::dispute::Dispute>,
dispute_details: DisputeSyncResponse,
payment_attempt: domain::PaymentAttempt,
connector_name: &str,
) -> errors::CustomResult<api_models::disputes::DisputeResponse, errors::ApiErrorResponse> {
let dispute_data = DisputePayload::from(dispute_details.clone());
let dispute_object = webhooks::incoming::get_or_update_dispute_object(
state.clone(),
option_dispute,
dispute_data,
merchant_context.get_merchant_account().get_id(),
&merchant_context.get_merchant_account().organization_id,
&payment_attempt,
dispute_details.dispute_status,
&business_profile,
connector_name,
)
.await?;
let disputes_response: dispute_models::DisputeResponse = dispute_object.clone().foreign_into();
let event_type: storage_enums::EventType = dispute_details.dispute_status.into();
Box::pin(webhooks::create_event_and_trigger_outgoing_webhook(
state.clone(),
merchant_context,
business_profile,
event_type,
storage_enums::EventClass::Disputes,
dispute_object.dispute_id.clone(),
storage_enums::EventObjectType::DisputeDetails,
api::OutgoingWebhookContent::DisputeDetails(Box::new(disputes_response.clone())),
Some(dispute_object.created_at),
))
.await?;
Ok(disputes_response)
}
#[cfg(feature = "v1")]
pub async fn add_process_dispute_task_to_pt(
db: &dyn StorageInterface,
connector_name: &str,
dispute_payload: &DisputeSyncResponse,
merchant_id: common_utils::id_type::MerchantId,
schedule_time: Option<time::PrimitiveDateTime>,
) -> common_utils::errors::CustomResult<(), errors::StorageError> {
match schedule_time {
Some(time) => {
TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", "dispute_process")),
);
let tracking_data = disputes::ProcessDisputePTData {
connector_name: connector_name.to_string(),
dispute_payload: dispute_payload.clone(),
merchant_id: merchant_id.clone(),
};
let runner = common_enums::ProcessTrackerRunner::ProcessDisputeWorkflow;
let task = "DISPUTE_PROCESS";
let tag = ["PROCESS", "DISPUTE"];
let process_tracker_id = scheduler::utils::get_process_tracker_id(
runner,
task,
&dispute_payload.connector_dispute_id.clone(),
&merchant_id,
);
let process_tracker_entry = diesel_models::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
time,
common_types::consts::API_VERSION,
)
.map_err(errors::StorageError::from)?;
db.insert_process(process_tracker_entry).await?;
Ok(())
}
None => Ok(()),
}
}
#[cfg(feature = "v1")]
pub async fn add_dispute_list_task_to_pt(
db: &dyn StorageInterface,
connector_name: &str,
merchant_id: common_utils::id_type::MerchantId,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
profile_id: common_utils::id_type::ProfileId,
fetch_request: FetchDisputesRequestData,
) -> common_utils::errors::CustomResult<(), errors::StorageError> {
TASKS_ADDED_COUNT.add(1, router_env::metric_attributes!(("flow", "dispute_list")));
let tracking_data = disputes::DisputeListPTData {
connector_name: connector_name.to_string(),
merchant_id: merchant_id.clone(),
merchant_connector_id: merchant_connector_id.clone(),
created_from: fetch_request.created_from,
created_till: fetch_request.created_till,
profile_id,
};
let runner = common_enums::ProcessTrackerRunner::DisputeListWorkflow;
let task = "DISPUTE_LIST";
let tag = ["LIST", "DISPUTE"];
let process_tracker_id = scheduler::utils::get_process_tracker_id_for_dispute_list(
runner,
&merchant_connector_id,
fetch_request.created_from,
&merchant_id,
);
let process_tracker_entry = diesel_models::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
fetch_request.created_from,
common_types::consts::API_VERSION,
)
.map_err(errors::StorageError::from)?;
db.insert_process(process_tracker_entry).await?;
Ok(())
}
#[cfg(feature = "v1")]
pub async fn schedule_dispute_sync_task(
state: &SessionState,
business_profile: &domain::Profile,
mca: &domain::MerchantConnectorAccount,
) -> common_utils::errors::CustomResult<(), errors::ApiErrorResponse> {
let connector = api::enums::Connector::from_str(&mca.connector_name).change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
},
)?;
if core_utils::should_add_dispute_sync_task_to_pt(state, connector) {
let offset_date_time = time::OffsetDateTime::now_utc();
let created_from =
time::PrimitiveDateTime::new(offset_date_time.date(), offset_date_time.time());
let dispute_polling_interval = *business_profile
.dispute_polling_interval
.unwrap_or_default()
.deref();
let created_till = created_from
.checked_add(time::Duration::hours(i64::from(dispute_polling_interval)))
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let m_db = state.clone().store;
let connector_name = mca.connector_name.clone();
let merchant_id = mca.merchant_id.clone();
let merchant_connector_id = mca.merchant_connector_id.clone();
let business_profile_id = business_profile.get_id().clone();
tokio::spawn(
async move {
add_dispute_list_task_to_pt(
&*m_db,
&connector_name,
merchant_id.clone(),
merchant_connector_id.clone(),
business_profile_id,
FetchDisputesRequestData {
created_from,
created_till,
},
)
.await
.map_err(|error| {
logger::error!("Failed to add dispute list task to process tracker: {error}")
})
}
.in_current_span(),
);
}
Ok(())
}
| crates/router/src/core/disputes.rs | router::src::core::disputes | 8,144 | true |
// File: crates/router/src/core/unified_authentication_service.rs
// Module: router::src::core::unified_authentication_service
pub mod types;
use std::str::FromStr;
pub mod utils;
#[cfg(feature = "v1")]
use api_models::authentication::{
AuthenticationEligibilityRequest, AuthenticationEligibilityResponse,
AuthenticationSyncPostUpdateRequest, AuthenticationSyncRequest, AuthenticationSyncResponse,
};
use api_models::{
authentication::{
AcquirerDetails, AuthenticationAuthenticateRequest, AuthenticationAuthenticateResponse,
AuthenticationCreateRequest, AuthenticationResponse,
},
payments,
};
#[cfg(feature = "v1")]
use common_utils::{ext_traits::ValueExt, types::keymanager::ToEncryptable};
use diesel_models::authentication::{Authentication, AuthenticationNew};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse,
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,
payments::helpers,
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,
};
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<&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,
};
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: Authentication,
return_url: Option<String>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
webhook_url: String,
) -> RouterResult<UasAuthenticationRequestData> {
Ok(UasAuthenticationRequestData {
browser_details,
transaction_details: TransactionDetails {
amount,
currency,
device_channel: Some(device_channel),
message_category: Some(message_category),
},
pre_authentication_data: PreAuthenticationData {
threeds_server_transaction_id: authentication.threeds_server_transaction_id.ok_or(
ApiErrorResponse::MissingRequiredField {
field_name: "authentication.threeds_server_transaction_id",
},
)?,
message_version: authentication.message_version.ok_or(
ApiErrorResponse::MissingRequiredField {
field_name: "authentication.message_version",
},
)?,
acquirer_bin: authentication.acquirer_bin,
acquirer_merchant_id: authentication.acquirer_merchant_id,
acquirer_country_code: authentication.acquirer_country_code,
connector_metadata: authentication.connector_metadata,
},
return_url,
sdk_information,
email,
threeds_method_comp_ind,
webhook_url,
})
}
#[allow(clippy::too_many_arguments)]
async fn authentication(
state: &SessionState,
business_profile: &domain::Profile,
payment_method: &common_enums::PaymentMethod,
browser_details: Option<BrowserInformation>,
amount: Option<common_utils::types::MinorUnit>,
currency: Option<common_enums::Currency>,
message_category: MessageCategory,
device_channel: payments::DeviceChannel,
authentication: Authentication,
return_url: Option<String>,
sdk_information: Option<payments::SdkInformation>,
threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
email: Option<common_utils::pii::Email>,
webhook_url: String,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
payment_id: Option<common_utils::id_type::PaymentId>,
) -> RouterResult<UasAuthenticationRouterData> {
let authentication_data =
<Self as UnifiedAuthenticationService>::get_authentication_request_data(
browser_details,
amount,
currency,
message_category,
device_channel,
authentication.clone(),
return_url,
sdk_information,
threeds_method_comp_ind,
email,
webhook_url,
)?;
let auth_router_data: UasAuthenticationRouterData = utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method.to_owned(),
business_profile.merchant_id.clone(),
None,
authentication_data,
merchant_connector_account,
Some(authentication.authentication_id.to_owned()),
payment_id,
)?;
Box::pin(utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
auth_router_data,
))
.await
}
fn get_post_authentication_request_data(
authentication: Option<Authentication>,
) -> RouterResult<UasPostAuthenticationRequestData> {
Ok(UasPostAuthenticationRequestData {
// authentication.threeds_server_transaction_id is mandatory for post-authentication in ExternalAuthentication
threeds_server_transaction_id: Some(
authentication
.and_then(|auth| auth.threeds_server_transaction_id)
.ok_or(ApiErrorResponse::MissingRequiredField {
field_name: "authentication.threeds_server_transaction_id",
})?,
),
})
}
async fn post_authentication(
state: &SessionState,
business_profile: &domain::Profile,
payment_id: Option<&common_utils::id_type::PaymentId>,
merchant_connector_account: &MerchantConnectorAccountType,
connector_name: &str,
authentication_id: &common_utils::id_type::AuthenticationId,
payment_method: common_enums::PaymentMethod,
_merchant_id: &common_utils::id_type::MerchantId,
authentication: Option<&Authentication>,
) -> RouterResult<UasPostAuthenticationRouterData> {
let authentication_data =
<Self as UnifiedAuthenticationService>::get_post_authentication_request_data(
authentication.cloned(),
)?;
let auth_router_data: UasPostAuthenticationRouterData = utils::construct_uas_router_data(
state,
connector_name.to_string(),
payment_method,
business_profile.merchant_id.clone(),
None,
authentication_data,
merchant_connector_account,
Some(authentication_id.clone()),
payment_id.cloned(),
)?;
utils::do_auth_connector_call(
state,
UNIFIED_AUTHENTICATION_SERVICE.to_string(),
auth_router_data,
)
.await
}
}
#[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>,
) -> RouterResult<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 new_authorization = AuthenticationNew {
authentication_id: authentication_id.to_owned(),
merchant_id,
authentication_connector,
connector_authentication_id: None,
payment_method_id: "".to_string(),
authentication_type: None,
authentication_status,
authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus::Unused,
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,
challenge_request_key: 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,
service_details: service_details_value,
organization_id,
authentication_client_secret,
force_3ds_challenge,
psd2_sca_exemption_type,
return_url,
amount,
currency,
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,
};
state
.store
.insert_authentication(new_authorization)
.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,
merchant_context: domain::MerchantContext,
req: AuthenticationCreateRequest,
) -> RouterResponse<AuthenticationResponse> {
let db = &*state.store;
let merchant_account = merchant_context.get_merchant_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(
&key_manager_state,
None,
None,
&merchant_context,
req.profile_id.as_ref(),
db,
true,
)
.await?;
let business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
merchant_context.get_merchant_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 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,
acquirer_merchant_id,
acquirer_country_code,
Some(req.amount),
Some(req.currency),
req.return_url,
req.profile_acquirer_id.clone(),
)
.await?;
let acquirer_details = Some(AcquirerDetails {
acquirer_bin: new_authentication.acquirer_bin.clone(),
acquirer_merchant_id: new_authentication.acquirer_merchant_id.clone(),
merchant_country_code: new_authentication.acquirer_country_code.clone(),
});
let amount = new_authentication
.amount
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("amount failed to get amount from authentication table")?;
let currency = new_authentication
.currency
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("currency failed to get currency from authentication table")?;
let response = AuthenticationResponse::foreign_try_from((
new_authentication.clone(),
amount,
currency,
profile_id,
acquirer_details,
new_authentication.profile_acquirer_id,
))?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
impl
ForeignTryFrom<(
Authentication,
common_utils::types::MinorUnit,
common_enums::Currency,
common_utils::id_type::ProfileId,
Option<AcquirerDetails>,
Option<common_utils::id_type::ProfileAcquirerId>,
)> for AuthenticationResponse
{
type Error = error_stack::Report<ApiErrorResponse>;
fn foreign_try_from(
(authentication, amount, currency, profile_id, acquirer_details, profile_acquirer_id): (
Authentication,
common_utils::types::MinorUnit,
common_enums::Currency,
common_utils::id_type::ProfileId,
Option<AcquirerDetails>,
Option<common_utils::id_type::ProfileAcquirerId>,
),
) -> Result<Self, Self::Error> {
let authentication_connector = authentication
.authentication_connector
.map(|connector| common_enums::AuthenticationConnectors::from_str(&connector))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Incorrect authentication connector stored in table")?;
Ok(Self {
authentication_id: authentication.authentication_id,
client_secret: authentication
.authentication_client_secret
.map(masking::Secret::new),
amount,
currency,
force_3ds_challenge: authentication.force_3ds_challenge,
merchant_id: authentication.merchant_id,
status: authentication.authentication_status,
authentication_connector,
return_url: authentication.return_url,
created_at: Some(authentication.created_at),
error_code: authentication.error_code,
error_message: authentication.error_message,
profile_id: Some(profile_id),
psd2_sca_exemption_type: authentication.psd2_sca_exemption_type,
acquirer_details,
profile_acquirer_id,
})
}
}
#[cfg(feature = "v1")]
impl
ForeignTryFrom<(
Authentication,
api_models::authentication::NextAction,
common_utils::id_type::ProfileId,
Option<payments::Address>,
Option<payments::Address>,
Option<payments::BrowserInformation>,
common_utils::crypto::OptionalEncryptableEmail,
)> for AuthenticationEligibilityResponse
{
type Error = error_stack::Report<ApiErrorResponse>;
fn foreign_try_from(
(authentication, next_action, profile_id, billing, shipping, browser_information, email): (
Authentication,
api_models::authentication::NextAction,
common_utils::id_type::ProfileId,
Option<payments::Address>,
Option<payments::Address>,
Option<payments::BrowserInformation>,
common_utils::crypto::OptionalEncryptableEmail,
),
) -> Result<Self, Self::Error> {
let authentication_connector = authentication
.authentication_connector
.map(|connector| common_enums::AuthenticationConnectors::from_str(&connector))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Incorrect authentication connector stored in table")?;
let three_ds_method_url = authentication
.three_ds_method_url
.map(|url| url::Url::parse(&url))
.transpose()
.map_err(error_stack::Report::from)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse three_ds_method_url")?;
let three_ds_data = Some(api_models::authentication::ThreeDsData {
three_ds_server_transaction_id: authentication.threeds_server_transaction_id,
maximum_supported_3ds_version: authentication.maximum_supported_version,
connector_authentication_id: authentication.connector_authentication_id,
three_ds_method_data: authentication.three_ds_method_data,
three_ds_method_url,
message_version: authentication.message_version,
directory_server_id: authentication.directory_server_id,
});
let acquirer_details = AcquirerDetails {
acquirer_bin: authentication.acquirer_bin,
acquirer_merchant_id: authentication.acquirer_merchant_id,
merchant_country_code: authentication.acquirer_country_code,
};
Ok(Self {
authentication_id: authentication.authentication_id,
next_action,
status: authentication.authentication_status,
eligibility_response_params: three_ds_data
.map(api_models::authentication::EligibilityResponseParams::ThreeDsData),
connector_metadata: authentication.connector_metadata,
profile_id,
error_message: authentication.error_message,
error_code: authentication.error_code,
billing,
shipping,
authentication_connector,
browser_information,
email,
acquirer_details: Some(acquirer_details),
})
}
}
#[cfg(feature = "v1")]
pub async fn authentication_eligibility_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: AuthenticationEligibilityRequest,
authentication_id: common_utils::id_type::AuthenticationId,
) -> RouterResponse<AuthenticationEligibilityResponse> {
let merchant_account = merchant_context.get_merchant_account();
let merchant_id = merchant_account.get_id();
let db = &*state.store;
let authentication = db
.find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)
.await
.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_owned(),
})?;
req.client_secret
.clone()
.map(|client_secret| {
utils::authenticate_authentication_client_secret_and_check_expiry(
client_secret.peek(),
&authentication,
)
})
.transpose()?;
ensure_not_terminal_status(authentication.trans_status.clone())?;
let key_manager_state = (&state).into();
let profile_id = core_utils::get_profile_id_from_business_details(
&key_manager_state,
None,
None,
&merchant_context,
req.profile_id.as_ref(),
db,
true,
)
.await?;
let business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let (authentication_connector, three_ds_connector_account) =
auth_utils::get_authentication_connector_data(
&state,
merchant_context.get_merchant_key_store(),
&business_profile,
authentication.authentication_connector.clone(),
)
.await?;
let notification_url = match authentication_connector {
common_enums::AuthenticationConnectors::Juspaythreedsserver => {
Some(url::Url::parse(&format!(
"{base_url}/authentication/{merchant_id}/{authentication_id}/redirect",
base_url = state.base_url,
merchant_id = merchant_id.get_string_repr(),
authentication_id = authentication_id.get_string_repr()
)))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse notification url")?
}
_ => authentication
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse return url")?,
};
let authentication_connector_name = authentication_connector.to_string();
let payment_method_data = domain::PaymentMethodData::from(req.payment_method_data.clone());
let amount = authentication
.amount
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("no amount found in authentication table")?;
let acquirer_details = authentication
.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())
});
let metadata: Option<ThreeDsMetaData> = three_ds_connector_account
.get_metadata()
.map(|metadata| {
metadata.expose().parse_value("ThreeDsMetaData").inspect_err(|err| {
router_env::logger::warn!(parsing_error=?err,"Error while parsing ThreeDsMetaData");
})
})
.transpose()
.change_context(ApiErrorResponse::InternalServerError)?;
let merchant_country_code = authentication.acquirer_country_code.clone();
let merchant_details = Some(hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails {
merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()),
merchant_name: acquirer_details.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)),
merchant_category_code: business_profile.merchant_category_code.or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)),
endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix),
three_ds_requestor_url: business_profile.authentication_connector_details.map(|details| details.three_ds_requestor_url),
three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id),
three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name),
merchant_country_code: merchant_country_code.map(common_types::payments::MerchantCountryCode::new),
notification_url,
});
let domain_address = req
.billing
.clone()
.map(hyperswitch_domain_models::address::Address::from);
let pre_auth_response =
<ExternalAuthentication as UnifiedAuthenticationService>::pre_authentication(
&state,
merchant_id,
None,
Some(&payment_method_data),
req.payment_method_type,
&three_ds_connector_account,
&authentication_connector_name,
&authentication_id,
req.payment_method,
amount,
authentication.currency,
None,
merchant_details.as_ref(),
domain_address.as_ref(),
authentication.acquirer_bin.clone(),
authentication.acquirer_merchant_id.clone(),
)
.await?;
let billing_details_encoded = req
.billing
.clone()
.map(|billing| {
common_utils::ext_traits::Encode::encode_to_value(&billing)
.map(masking::Secret::<serde_json::Value>::new)
})
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode billing details to serde_json::Value")?;
let shipping_details_encoded = req
.shipping
.clone()
.map(|shipping| {
common_utils::ext_traits::Encode::encode_to_value(&shipping)
.map(masking::Secret::<serde_json::Value>::new)
})
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode shipping details to serde_json::Value")?;
let encrypted_data = domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication),
domain::types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication::to_encryptable(
hyperswitch_domain_models::authentication::UpdateEncryptableAuthentication {
billing_address: billing_details_encoded,
shipping_address: shipping_details_encoded,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt authentication data".to_string())?;
let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to get encrypted data for authentication after encryption")?;
let email_encrypted = req
.email
.clone()
.async_lift(|inner| async {
domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(Authentication),
domain::types::CryptoOperation::EncryptOptional(inner.map(|inner| inner.expose())),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt email")?;
let browser_info = req
.browser_information
.as_ref()
.map(common_utils::ext_traits::Encode::encode_to_value)
.transpose()
.change_context(ApiErrorResponse::InvalidDataValue {
field_name: "browser_information",
})?;
let updated_authentication = utils::external_authentication_update_trackers(
&state,
pre_auth_response,
authentication.clone(),
None,
merchant_context.get_merchant_key_store(),
encrypted_data
.billing_address
.map(common_utils::encryption::Encryption::from),
encrypted_data
.shipping_address
.map(common_utils::encryption::Encryption::from),
email_encrypted
.clone()
.map(common_utils::encryption::Encryption::from),
browser_info,
)
.await?;
let response = AuthenticationEligibilityResponse::foreign_try_from((
updated_authentication,
req.get_next_action_api(
state.base_url,
authentication_id.get_string_repr().to_string(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to get next action api")?,
profile_id,
req.get_billing_address(),
req.get_shipping_address(),
req.get_browser_information(),
email_encrypted,
))?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
#[cfg(feature = "v1")]
pub async fn authentication_authenticate_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: AuthenticationAuthenticateRequest,
auth_flow: AuthFlow,
) -> RouterResponse<AuthenticationAuthenticateResponse> {
let authentication_id = req.authentication_id.clone();
let merchant_account = merchant_context.get_merchant_account();
let merchant_id = merchant_account.get_id();
let db = &*state.store;
let authentication = db
.find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)
.await
.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_owned(),
})?;
req.client_secret
.map(|client_secret| {
utils::authenticate_authentication_client_secret_and_check_expiry(
client_secret.peek(),
&authentication,
)
})
.transpose()?;
ensure_not_terminal_status(authentication.trans_status.clone())?;
let key_manager_state = (&state).into();
let profile_id = authentication.profile_id.clone();
let business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let email_encrypted = authentication
.email
.clone()
.async_lift(|inner| async {
domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(Authentication),
domain::types::CryptoOperation::DecryptOptional(inner),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decrypt email from authentication table")?;
let browser_info = authentication
.browser_info
.clone()
.map(|browser_info| browser_info.parse_value::<BrowserInformation>("BrowserInformation"))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse browser information from authentication table")?;
let (authentication_connector, three_ds_connector_account) =
auth_utils::get_authentication_connector_data(
&state,
merchant_context.get_merchant_key_store(),
&business_profile,
authentication.authentication_connector.clone(),
)
.await?;
let authentication_details = business_profile
.authentication_connector_details
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("authentication_connector_details not configured by the merchant")?;
let connector_name_string = authentication_connector.to_string();
let mca_id_option = three_ds_connector_account.get_mca_id();
let merchant_connector_account_id_or_connector_name = mca_id_option
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(&connector_name_string);
let webhook_url = helpers::create_webhook_url(
&state.base_url,
merchant_id,
merchant_connector_account_id_or_connector_name,
);
let auth_response = <ExternalAuthentication as UnifiedAuthenticationService>::authentication(
&state,
&business_profile,
&common_enums::PaymentMethod::Card,
browser_info,
authentication.amount,
authentication.currency,
MessageCategory::Payment,
req.device_channel,
authentication.clone(),
None,
req.sdk_information,
req.threeds_method_comp_ind,
email_encrypted.map(common_utils::pii::Email::from),
webhook_url,
&three_ds_connector_account,
&authentication_connector.to_string(),
None,
)
.await?;
let authentication = utils::external_authentication_update_trackers(
&state,
auth_response,
authentication.clone(),
None,
merchant_context.get_merchant_key_store(),
None,
None,
None,
None,
)
.await?;
let (authentication_value, eci) = match auth_flow {
AuthFlow::Client => (None, None),
AuthFlow::Merchant => {
if let Some(common_enums::TransactionStatus::Success) = authentication.trans_status {
let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data(
&state,
authentication_id.get_string_repr(),
false,
merchant_context.get_merchant_key_store().key.get_inner(),
)
.await
.inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err))
.attach_printable("cavv not present after authentication status is success")?;
(
Some(masking::Secret::new(tokenised_data.value1)),
authentication.eci.clone(),
)
} else {
(None, None)
}
}
};
let response = AuthenticationAuthenticateResponse::foreign_try_from((
&authentication,
authentication_value,
eci,
authentication_details,
))?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
impl
ForeignTryFrom<(
&Authentication,
Option<masking::Secret<String>>,
Option<String>,
diesel_models::business_profile::AuthenticationConnectorDetails,
)> for AuthenticationAuthenticateResponse
{
type Error = error_stack::Report<ApiErrorResponse>;
fn foreign_try_from(
(authentication, authentication_value, eci, authentication_details): (
&Authentication,
Option<masking::Secret<String>>,
Option<String>,
diesel_models::business_profile::AuthenticationConnectorDetails,
),
) -> Result<Self, Self::Error> {
let authentication_connector = authentication
.authentication_connector
.as_ref()
.map(|connector| common_enums::AuthenticationConnectors::from_str(connector))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Incorrect authentication connector stored in table")?;
let acs_url = authentication
.acs_url
.clone()
.map(|acs_url| url::Url::parse(&acs_url))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse the url with param")?;
let acquirer_details = AcquirerDetails {
acquirer_bin: authentication.acquirer_bin.clone(),
acquirer_merchant_id: authentication.acquirer_merchant_id.clone(),
merchant_country_code: authentication.acquirer_country_code.clone(),
};
Ok(Self {
transaction_status: authentication.trans_status.clone(),
acs_url,
challenge_request: authentication.challenge_request.clone(),
acs_reference_number: authentication.acs_reference_number.clone(),
acs_trans_id: authentication.acs_trans_id.clone(),
three_ds_server_transaction_id: authentication.threeds_server_transaction_id.clone(),
acs_signed_content: authentication.acs_signed_content.clone(),
three_ds_requestor_url: authentication_details.three_ds_requestor_url.clone(),
three_ds_requestor_app_url: authentication_details.three_ds_requestor_app_url.clone(),
error_code: None,
error_message: authentication.error_message.clone(),
authentication_value,
status: authentication.authentication_status,
authentication_connector,
eci,
authentication_id: authentication.authentication_id.clone(),
acquirer_details: Some(acquirer_details),
})
}
}
#[cfg(feature = "v1")]
pub async fn authentication_sync_core(
state: SessionState,
merchant_context: domain::MerchantContext,
auth_flow: AuthFlow,
req: AuthenticationSyncRequest,
) -> RouterResponse<AuthenticationSyncResponse> {
let authentication_id = req.authentication_id;
let merchant_account = merchant_context.get_merchant_account();
let merchant_id = merchant_account.get_id();
let db = &*state.store;
let authentication = db
.find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)
.await
.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_owned(),
})?;
req.client_secret
.map(|client_secret| {
utils::authenticate_authentication_client_secret_and_check_expiry(
client_secret.peek(),
&authentication,
)
})
.transpose()?;
let key_manager_state = (&state).into();
let profile_id = authentication.profile_id.clone();
let business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let (authentication_connector, three_ds_connector_account) =
auth_utils::get_authentication_connector_data(
&state,
merchant_context.get_merchant_key_store(),
&business_profile,
authentication.authentication_connector.clone(),
)
.await?;
let updated_authentication = match authentication.trans_status.clone() {
Some(trans_status) if trans_status.clone().is_pending() => {
let post_auth_response = ExternalAuthentication::post_authentication(
&state,
&business_profile,
None,
&three_ds_connector_account,
&authentication_connector.to_string(),
&authentication_id,
common_enums::PaymentMethod::Card,
merchant_id,
Some(&authentication),
)
.await?;
utils::external_authentication_update_trackers(
&state,
post_auth_response,
authentication.clone(),
None,
merchant_context.get_merchant_key_store(),
None,
None,
None,
None,
)
.await?
}
_ => authentication,
};
let (authentication_value, eci) = match auth_flow {
AuthFlow::Client => (None, None),
AuthFlow::Merchant => {
if let Some(common_enums::TransactionStatus::Success) =
updated_authentication.trans_status
{
let tokenised_data = crate::core::payment_methods::vault::get_tokenized_data(
&state,
authentication_id.get_string_repr(),
false,
merchant_context.get_merchant_key_store().key.get_inner(),
)
.await
.inspect_err(|err| router_env::logger::error!(tokenized_data_result=?err))
.attach_printable("cavv not present after authentication status is success")?;
(
Some(masking::Secret::new(tokenised_data.value1)),
updated_authentication.eci.clone(),
)
} else {
(None, None)
}
}
};
let acquirer_details = Some(AcquirerDetails {
acquirer_bin: updated_authentication.acquirer_bin.clone(),
acquirer_merchant_id: updated_authentication.acquirer_merchant_id.clone(),
merchant_country_code: updated_authentication.acquirer_country_code.clone(),
});
let encrypted_data = domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::authentication::Authentication),
domain::types::CryptoOperation::BatchDecrypt(
hyperswitch_domain_models::authentication::EncryptedAuthentication::to_encryptable(
hyperswitch_domain_models::authentication::EncryptedAuthentication {
billing_address: updated_authentication.billing_address,
shipping_address: updated_authentication.shipping_address,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt authentication data".to_string())?;
let encrypted_data = hyperswitch_domain_models::authentication::FromRequestEncryptableAuthentication::from_encryptable(encrypted_data)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to get encrypted data for authentication after encryption")?;
let email_decrypted = updated_authentication
.email
.clone()
.async_lift(|inner| async {
domain::types::crypto_operation(
&key_manager_state,
common_utils::type_name!(Authentication),
domain::types::CryptoOperation::DecryptOptional(inner),
common_utils::types::keymanager::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt email")?;
let browser_info = updated_authentication
.browser_info
.clone()
.map(|browser_info| {
browser_info.parse_value::<payments::BrowserInformation>("BrowserInformation")
})
.transpose()
.change_context(ApiErrorResponse::InternalServerError)?;
let amount = updated_authentication
.amount
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("amount failed to get amount from authentication table")?;
let currency = updated_authentication
.currency
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("currency failed to get currency from authentication table")?;
let authentication_connector = updated_authentication
.authentication_connector
.map(|connector| common_enums::AuthenticationConnectors::from_str(&connector))
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Incorrect authentication connector stored in table")?;
let billing = encrypted_data
.billing_address
.map(|billing| {
billing
.into_inner()
.expose()
.parse_value::<payments::Address>("Address")
})
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse billing address")?;
let shipping = encrypted_data
.shipping_address
.map(|shipping| {
shipping
.into_inner()
.expose()
.parse_value::<payments::Address>("Address")
})
.transpose()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse shipping address")?;
let response = AuthenticationSyncResponse {
authentication_id: authentication_id.clone(),
merchant_id: merchant_id.clone(),
status: updated_authentication.authentication_status,
client_secret: updated_authentication
.authentication_client_secret
.map(masking::Secret::new),
amount,
currency,
authentication_connector,
force_3ds_challenge: updated_authentication.force_3ds_challenge,
return_url: updated_authentication.return_url.clone(),
created_at: updated_authentication.created_at,
profile_id: updated_authentication.profile_id.clone(),
psd2_sca_exemption_type: updated_authentication.psd2_sca_exemption_type,
acquirer_details,
error_message: updated_authentication.error_message.clone(),
error_code: updated_authentication.error_code.clone(),
authentication_value,
threeds_server_transaction_id: updated_authentication.threeds_server_transaction_id.clone(),
maximum_supported_3ds_version: updated_authentication.maximum_supported_version.clone(),
connector_authentication_id: updated_authentication.connector_authentication_id.clone(),
three_ds_method_data: updated_authentication.three_ds_method_data.clone(),
three_ds_method_url: updated_authentication.three_ds_method_url.clone(),
message_version: updated_authentication.message_version.clone(),
connector_metadata: updated_authentication.connector_metadata.clone(),
directory_server_id: updated_authentication.directory_server_id.clone(),
billing,
shipping,
browser_information: browser_info,
email: email_decrypted,
transaction_status: updated_authentication.trans_status.clone(),
acs_url: updated_authentication.acs_url.clone(),
challenge_request: updated_authentication.challenge_request.clone(),
acs_reference_number: updated_authentication.acs_reference_number.clone(),
acs_trans_id: updated_authentication.acs_trans_id.clone(),
acs_signed_content: updated_authentication.acs_signed_content,
three_ds_requestor_url: business_profile
.authentication_connector_details
.clone()
.map(|details| details.three_ds_requestor_url),
three_ds_requestor_app_url: business_profile
.authentication_connector_details
.and_then(|details| details.three_ds_requestor_app_url),
profile_acquirer_id: updated_authentication.profile_acquirer_id.clone(),
eci,
};
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
#[cfg(feature = "v1")]
pub async fn authentication_post_sync_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: AuthenticationSyncPostUpdateRequest,
) -> RouterResponse<()> {
let authentication_id = req.authentication_id;
let merchant_account = merchant_context.get_merchant_account();
let merchant_id = merchant_account.get_id();
let db = &*state.store;
let authentication = db
.find_authentication_by_merchant_id_authentication_id(merchant_id, &authentication_id)
.await
.to_not_found_response(ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_owned(),
})?;
ensure_not_terminal_status(authentication.trans_status.clone())?;
let key_manager_state = (&state).into();
let business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
merchant_context.get_merchant_key_store(),
&authentication.profile_id,
)
.await
.to_not_found_response(ApiErrorResponse::ProfileNotFound {
id: authentication.profile_id.get_string_repr().to_owned(),
})?;
let (authentication_connector, three_ds_connector_account) =
auth_utils::get_authentication_connector_data(
&state,
merchant_context.get_merchant_key_store(),
&business_profile,
authentication.authentication_connector.clone(),
)
.await?;
let post_auth_response =
<ExternalAuthentication as UnifiedAuthenticationService>::post_authentication(
&state,
&business_profile,
None,
&three_ds_connector_account,
&authentication_connector.to_string(),
&authentication_id,
common_enums::PaymentMethod::Card,
merchant_id,
Some(&authentication),
)
.await?;
let updated_authentication = utils::external_authentication_update_trackers(
&state,
post_auth_response,
authentication.clone(),
None,
merchant_context.get_merchant_key_store(),
None,
None,
None,
None,
)
.await?;
let authentication_details = business_profile
.authentication_connector_details
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("authentication_connector_details not configured by the merchant")?;
let authentication_response = AuthenticationAuthenticateResponse::foreign_try_from((
&updated_authentication,
None,
None,
authentication_details,
))?;
let redirect_response = helpers::get_handle_response_url_for_modular_authentication(
authentication_id,
&business_profile,
&authentication_response,
authentication_connector.to_string(),
authentication.return_url,
updated_authentication
.authentication_client_secret
.clone()
.map(masking::Secret::new)
.as_ref(),
updated_authentication.amount,
)?;
Ok(hyperswitch_domain_models::api::ApplicationResponse::JsonForRedirection(redirect_response))
}
fn ensure_not_terminal_status(
status: Option<common_enums::TransactionStatus>,
) -> Result<(), error_stack::Report<ApiErrorResponse>> {
status
.filter(|s| s.clone().is_terminal_state())
.map(|s| {
Err(error_stack::Report::new(
ApiErrorResponse::UnprocessableEntity {
message: format!(
"authentication status for the given authentication_id is already in {s}"
),
},
))
})
.unwrap_or(Ok(()))
}
| crates/router/src/core/unified_authentication_service.rs | router::src::core::unified_authentication_service | 12,879 | true |
// File: crates/router/src/core/blocklist.rs
// Module: router::src::core::blocklist
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,
merchant_context: domain::MerchantContext,
body: api_blocklist::AddToBlocklistRequest,
) -> RouterResponse<api_blocklist::AddToBlocklistResponse> {
utils::insert_entry_into_blocklist(
&state,
merchant_context.get_merchant_account().get_id(),
body,
)
.await
.map(services::ApplicationResponse::Json)
}
pub async fn remove_entry_from_blocklist(
state: SessionState,
merchant_context: domain::MerchantContext,
body: api_blocklist::DeleteFromBlocklistRequest,
) -> RouterResponse<api_blocklist::DeleteFromBlocklistResponse> {
utils::delete_entry_from_blocklist(
&state,
merchant_context.get_merchant_account().get_id(),
body,
)
.await
.map(services::ApplicationResponse::Json)
}
pub async fn list_blocklist_entries(
state: SessionState,
merchant_context: domain::MerchantContext,
query: api_blocklist::ListBlocklistQuery,
) -> RouterResponse<Vec<api_blocklist::BlocklistResponse>> {
utils::list_blocklist_entries_for_merchant(
&state,
merchant_context.get_merchant_account().get_id(),
query,
)
.await
.map(services::ApplicationResponse::Json)
}
pub async fn toggle_blocklist_guard(
state: SessionState,
merchant_context: domain::MerchantContext,
query: api_blocklist::ToggleBlocklistQuery,
) -> RouterResponse<api_blocklist::ToggleBlocklistResponse> {
utils::toggle_blocklist_guard_for_merchant(
&state,
merchant_context.get_merchant_account().get_id(),
query,
)
.await
.map(services::ApplicationResponse::Json)
}
| crates/router/src/core/blocklist.rs | router::src::core::blocklist | 460 | true |
// File: crates/router/src/core/user.rs
// Module: router::src::core::user
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 key_manager_state = &(&state).into();
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&user_from_token.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await;
let version = if let Ok(merchant_key_store) = merchant_key_store {
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
&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 {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User Inviting themselves".to_string(),
)
.into());
}
let 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 !role_info.is_invitable() {
return 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(),
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,
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(
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(
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,
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
role_info: roles::RoleInfo,
req_state: ReqState,
auth_id: &Option<String>,
) -> UserResult<InviteMultipleUserResponse> {
let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?;
new_user
.insert_user_in_db(state.global_store.as_ref())
.await
.change_context(UserErrors::InternalServerError)?;
let invitation_status = if cfg!(feature = "email") {
UserStatus::InvitationSent
} else {
UserStatus::Active
};
let now = common_utils::date_time::now();
let user_role = domain::NewUserRole {
user_id: new_user.get_user_id().to_owned(),
role_id: request.role_id.clone(),
status: invitation_status,
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")]
{
// TODO: Adding this to avoid clippy lints
// Will be adding actual usage for this variable later
let _ = req_state.clone();
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(new_user.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()),
};
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);
is_email_sent = send_email_result.is_ok();
}
#[cfg(not(feature = "email"))]
{
is_email_sent = false;
let invited_user_token = auth::UserFromToken {
user_id: new_user.get_user_id(),
merchant_id: user_from_token.merchant_id.clone(),
org_id: user_from_token.org_id.clone(),
role_id: request.role_id.clone(),
profile_id: user_from_token.profile_id.clone(),
tenant_id: user_from_token.tenant_id.clone(),
};
let set_metadata_request = SetMetaDataRequest::IsChangePasswordRequired;
dashboard_metadata::set_metadata(
state.clone(),
invited_user_token,
set_metadata_request,
req_state,
)
.await?;
}
Ok(InviteMultipleUserResponse {
is_email_sent,
password: new_user
.get_password()
.map(|password| password.get_secret()),
email: request.email.clone(),
error: None,
})
}
#[cfg(feature = "email")]
pub async fn resend_invite(
state: SessionState,
user_from_token: auth::UserFromToken,
request: user_api::ReInviteUserRequest,
auth_id: Option<String>,
) -> UserResponse<()> {
let invitee_email = domain::UserEmail::from_pii_email(request.email)?;
let user: domain::UserFromStorage = state
.global_store
.find_user_by_email(&invitee_email)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::InvalidRoleOperation)
.attach_printable("User not found in the records")
} else {
e.change_context(UserErrors::InternalServerError)
}
})?
.into();
let user_role = match state
.global_store
.find_user_role_by_user_id_and_lineage(
user.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(err) => {
if err.current_context().is_db_not_found() {
None
} else {
return Err(report!(UserErrors::InternalServerError));
}
}
};
let user_role = match user_role {
Some(user_role) => user_role,
None => state
.global_store
.find_user_role_by_user_id_and_lineage(
user.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
.to_not_found_response(UserErrors::InvalidRoleOperationWithMessage(
"User not found in records".to_string(),
))?,
};
if !matches!(user_role.status, UserStatus::InvitationSent) {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("User status is not InvitationSent".to_string());
}
let (entity_id, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
let invitee_role_info = 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)?;
let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
&state,
&user_from_token,
invitee_role_info.get_entity_type(),
)
.await?;
let email_contents = email_types::InviteUser {
recipient_email: invitee_email,
user_name: domain::UserName::new(user.get_name())?,
settings: state.conf.clone(),
entity: email_types::Entity {
entity_id,
entity_type,
},
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()),
};
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(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::StatusOk)
}
#[cfg(feature = "email")]
pub async fn accept_invite_from_email_token_only_flow(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
request: user_api::AcceptInviteFromEmailRequest,
) -> UserResponse<user_api::TokenResponse> {
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 entity = email_token.get_entity().ok_or(UserErrors::LinkInvalid)?;
let (org_id, merchant_id, profile_id) =
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.clone(),
entity.entity_type,
)
.await
.change_context(UserErrors::InternalServerError)?
.ok_or(UserErrors::InternalServerError)?;
let (update_v1_result, update_v2_result) = utils::user_role::update_v1_and_v2_user_roles_in_db(
&state,
user_from_db.get_user_id(),
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_from_db.get_user_id().to_owned(),
},
)
.await;
if update_v1_result
.as_ref()
.is_err_and(|err| !err.current_context().is_db_not_found())
|| update_v2_result
.as_ref()
.is_err_and(|err| !err.current_context().is_db_not_found())
{
return Err(report!(UserErrors::InternalServerError));
}
if update_v1_result.is_err() && update_v2_result.is_err() {
return Err(report!(UserErrors::InvalidRoleOperation))
.attach_printable("User not found in the organization")?;
}
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 current_flow = domain::CurrentFlow::new(
user_token,
domain::SPTFlow::AcceptInvitationFromEmail.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 create_internal_user(
state: SessionState,
request: user_api::CreateInternalUserRequest,
) -> UserResponse<()> {
let role_info = roles::RoleInfo::from_predefined_roles(request.role_id.as_str())
.ok_or(UserErrors::InvalidRoleId)?;
fp_utils::when(
role_info.is_internal().not()
|| request.role_id == common_utils::consts::ROLE_ID_INTERNAL_ADMIN,
|| Err(UserErrors::InvalidRoleId),
)?;
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&common_utils::id_type::MerchantId::get_internal_user_merchant_id(
consts::user_role::INTERNAL_USER_MERCHANT_ID,
),
&state.store.get_master_key().to_vec().into(),
)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::MerchantIdNotFound)
} else {
e.change_context(UserErrors::InternalServerError)
}
})?;
let default_tenant_id = common_utils::id_type::TenantId::try_from_string(
common_utils::consts::DEFAULT_TENANT.to_owned(),
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to parse default tenant id")?;
if state.tenant.tenant_id != default_tenant_id {
return Err(UserErrors::ForbiddenTenantId)
.attach_printable("Operation allowed only for the default tenant");
}
let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id(
consts::user_role::INTERNAL_USER_MERCHANT_ID,
);
let internal_merchant = state
.store
.find_merchant_account_by_merchant_id(key_manager_state, &internal_merchant_id, &key_store)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(UserErrors::MerchantIdNotFound)
} else {
e.change_context(UserErrors::InternalServerError)
}
})?;
let new_user = domain::NewUser::try_from((request, internal_merchant.organization_id.clone()))?;
let mut store_user: storage_user::UserNew = new_user.clone().try_into()?;
store_user.set_is_verified(true);
state
.global_store
.insert_user(store_user)
.await
.map_err(|e| {
if e.current_context().is_db_unique_violation() {
e.change_context(UserErrors::UserExists)
} else {
e.change_context(UserErrors::InternalServerError)
}
})
.map(domain::user::UserFromStorage::from)?;
new_user
.get_no_level_user_role(role_info.get_role_id().to_string(), UserStatus::Active)
.add_entity(domain::MerchantLevel {
tenant_id: default_tenant_id,
org_id: internal_merchant.organization_id,
merchant_id: internal_merchant_id,
})
.insert_in_v2(&state)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn create_tenant_user(
state: SessionState,
request: user_api::CreateTenantUserRequest,
) -> UserResponse<()> {
let key_manager_state = &(&state).into();
let (merchant_id, org_id) = state
.store
.list_merchant_and_org_ids(key_manager_state, 1, None)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get merchants list for org")?
.pop()
.ok_or(UserErrors::InvalidRoleOperation)
.attach_printable("No merchants found in the tenancy")?;
let new_user = domain::NewUser::try_from((
request,
domain::MerchantAccountIdentifier {
merchant_id,
org_id,
},
))?;
let mut store_user: storage_user::UserNew = new_user.clone().try_into()?;
store_user.set_is_verified(true);
state
.global_store
.insert_user(store_user)
.await
.map_err(|e| {
if e.current_context().is_db_unique_violation() {
e.change_context(UserErrors::UserExists)
} else {
e.change_context(UserErrors::InternalServerError)
}
})
.map(domain::user::UserFromStorage::from)?;
new_user
.get_no_level_user_role(
common_utils::consts::ROLE_ID_TENANT_ADMIN.to_string(),
UserStatus::Active,
)
.add_entity(domain::TenantLevel {
tenant_id: state.tenant.tenant_id.clone(),
})
.insert_in_v2(&state)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::StatusOk)
}
#[cfg(feature = "v1")]
pub async fn create_platform_account(
state: SessionState,
user_from_token: auth::UserFromToken,
req: user_api::PlatformAccountCreateRequest,
) -> UserResponse<user_api::PlatformAccountCreateResponse> {
let user_from_db = user_from_token.get_user_from_db(&state).await?;
let new_merchant = domain::NewUserMerchant::try_from(req)?;
let new_organization = new_merchant.get_new_organization();
let organization = new_organization.insert_org_in_db(state.clone()).await?;
let merchant_account = new_merchant
.create_new_merchant_and_insert_in_db(state.to_owned())
.await?;
state
.accounts_store
.update_organization_by_org_id(
&organization.get_organization_id(),
diesel_models::organization::OrganizationUpdate::Update {
organization_name: None,
organization_details: None,
metadata: None,
platform_merchant_id: Some(merchant_account.get_id().to_owned()),
},
)
.await
.change_context(UserErrors::InternalServerError)?;
let now = common_utils::date_time::now();
let user_role = domain::NewUserRole {
user_id: user_from_db.get_user_id().to_owned(),
role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
status: 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,
};
user_role
.add_entity(domain::OrganizationLevel {
tenant_id: user_from_token
.tenant_id
.clone()
.unwrap_or(state.tenant.tenant_id.clone()),
org_id: merchant_account.organization_id.clone(),
})
.insert_in_v2(&state)
.await?;
Ok(ApplicationResponse::Json(
user_api::PlatformAccountCreateResponse {
org_id: organization.get_organization_id(),
org_name: organization.get_organization_name(),
org_type: organization.organization_type.unwrap_or_default(),
merchant_id: merchant_account.get_id().to_owned(),
merchant_account_type: merchant_account.merchant_account_type,
},
))
}
#[cfg(feature = "v1")]
pub async fn create_org_merchant_for_user(
state: SessionState,
req: user_api::UserOrgMerchantCreateRequest,
) -> UserResponse<()> {
let db_organization = ForeignFrom::foreign_from(req.clone());
let org: diesel_models::organization::Organization = state
.accounts_store
.insert_organization(db_organization)
.await
.change_context(UserErrors::InternalServerError)?;
let default_product_type = consts::user::DEFAULT_PRODUCT_TYPE;
let merchant_account_create_request = utils::user::create_merchant_account_request_for_org(
req,
org.clone(),
default_product_type,
)?;
admin::create_merchant_account(
state.clone(),
merchant_account_create_request,
Some(auth::AuthenticationDataWithOrg {
organization_id: org.get_organization_id(),
}),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while creating a merchant")?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn create_merchant_account(
state: SessionState,
user_from_token: auth::UserFromToken,
req: user_api::UserMerchantCreate,
) -> UserResponse<user_api::UserMerchantAccountResponse> {
let user_from_db = user_from_token.get_user_from_db(&state).await?;
let new_merchant = domain::NewUserMerchant::try_from((user_from_db, req, user_from_token))?;
let domain_merchant_account = new_merchant
.create_new_merchant_and_insert_in_db(state.to_owned())
.await?;
Ok(ApplicationResponse::Json(
user_api::UserMerchantAccountResponse {
merchant_id: domain_merchant_account.get_id().to_owned(),
merchant_name: domain_merchant_account.merchant_name,
product_type: domain_merchant_account.product_type,
merchant_account_type: domain_merchant_account.merchant_account_type,
version: domain_merchant_account.version,
},
))
}
pub async fn list_user_roles_details(
state: SessionState,
user_from_token: auth::UserFromToken,
request: user_api::GetUserRoleDetailsRequest,
_req_state: ReqState,
) -> UserResponse<Vec<user_api::GetUserRoleDetailsResponseV2>> {
let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?)
.await
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
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
.to_not_found_response(UserErrors::InternalServerError)
.attach_printable("Failed to fetch role info")?;
if requestor_role_info.is_internal() {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Internal roles are not allowed for this operation".to_string(),
)
.into());
}
let user_roles_set = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: required_user.get_user_id(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: Some(&user_from_token.org_id),
merchant_id: (requestor_role_info.get_entity_type() <= EntityType::Merchant)
.then_some(&user_from_token.merchant_id),
profile_id: (requestor_role_info.get_entity_type() <= EntityType::Profile)
.then_some(&user_from_token.profile_id),
entity_id: None,
version: None,
status: None,
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to fetch user roles")?
.into_iter()
.collect::<HashSet<_>>();
let org_name = state
.accounts_store
.find_organization_by_org_id(&user_from_token.org_id)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Org id not found")?
.get_organization_name();
let org = NameIdUnit {
id: user_from_token.org_id.clone(),
name: org_name,
};
let (merchant_ids, merchant_profile_ids) = user_roles_set.iter().try_fold(
(Vec::new(), Vec::new()),
|(mut merchant, mut merchant_profile), user_role| {
let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)
.attach_printable("Failed to compute entity id and type")?;
match entity_type {
EntityType::Merchant => {
let merchant_id = user_role
.merchant_id
.clone()
.ok_or(UserErrors::InternalServerError)
.attach_printable(
"Merchant id not found in user role for merchant level entity",
)?;
merchant.push(merchant_id)
}
EntityType::Profile => {
let merchant_id = user_role
.merchant_id
.clone()
.ok_or(UserErrors::InternalServerError)
.attach_printable(
"Merchant id not found in user role for merchant level entity",
)?;
let profile_id = user_role
.profile_id
.clone()
.ok_or(UserErrors::InternalServerError)
.attach_printable(
"Profile id not found in user role for profile level entity",
)?;
merchant.push(merchant_id.clone());
merchant_profile.push((merchant_id, profile_id))
}
EntityType::Tenant | EntityType::Organization => (),
};
Ok::<_, error_stack::Report<UserErrors>>((merchant, merchant_profile))
},
)?;
let merchant_map = state
.store
.list_multiple_merchant_accounts(&(&state).into(), merchant_ids)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error while listing merchant accounts")?
.into_iter()
.map(|merchant_account| {
(
merchant_account.get_id().to_owned(),
merchant_account.merchant_name.clone(),
)
})
.collect::<HashMap<_, _>>();
let key_manager_state = &(&state).into();
let profile_map = futures::future::try_join_all(merchant_profile_ids.iter().map(
|merchant_profile_id| async {
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_profile_id.0,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant key store by merchant_id")?;
state
.store
.find_business_profile_by_profile_id(
key_manager_state,
&merchant_key_store,
&merchant_profile_id.1,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve business profile")
},
))
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to construct profile map")?
.into_iter()
.map(|profile| (profile.get_id().to_owned(), profile.profile_name))
.collect::<HashMap<_, _>>();
let role_name_map = futures::future::try_join_all(
user_roles_set
.iter()
.map(|user_role| user_role.role_id.clone())
.collect::<HashSet<_>>()
.into_iter()
.map(|role_id| async {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&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)?;
Ok::<_, error_stack::Report<_>>((role_id, role_info.get_role_name().to_string()))
}),
)
.await?
.into_iter()
.collect::<HashMap<_, _>>();
let role_details_list: Vec<_> = user_roles_set
.iter()
.map(|user_role| {
let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
let (merchant, profile) = match entity_type {
EntityType::Tenant | EntityType::Organization => (None, None),
EntityType::Merchant => {
let merchant_id = &user_role
.merchant_id
.clone()
.ok_or(UserErrors::InternalServerError)?;
(
Some(NameIdUnit {
id: merchant_id.clone(),
name: merchant_map
.get(merchant_id)
.ok_or(UserErrors::InternalServerError)?
.to_owned(),
}),
None,
)
}
EntityType::Profile => {
let merchant_id = &user_role
.merchant_id
.clone()
.ok_or(UserErrors::InternalServerError)?;
let profile_id = &user_role
.profile_id
.clone()
.ok_or(UserErrors::InternalServerError)?;
(
Some(NameIdUnit {
id: merchant_id.clone(),
name: merchant_map
.get(merchant_id)
.ok_or(UserErrors::InternalServerError)?
.to_owned(),
}),
Some(NameIdUnit {
id: profile_id.clone(),
name: profile_map
.get(profile_id)
.ok_or(UserErrors::InternalServerError)?
.to_owned(),
}),
)
}
};
Ok(user_api::GetUserRoleDetailsResponseV2 {
role_id: user_role.role_id.clone(),
org: org.clone(),
merchant,
profile,
status: user_role.status.foreign_into(),
entity_type,
role_name: role_name_map
.get(&user_role.role_id)
.ok_or(UserErrors::InternalServerError)
.cloned()?,
})
})
.collect::<Result<Vec<_>, UserErrors>>()?;
Ok(ApplicationResponse::Json(role_details_list))
}
#[cfg(feature = "email")]
pub async fn verify_email_token_only_flow(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
req: user_api::VerifyEmailRequest,
) -> UserResponse<user_api::TokenResponse> {
let token = req.token.clone().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_email = state
.global_store
.find_user_by_email(&email_token.get_email()?)
.await
.change_context(UserErrors::InternalServerError)?;
if user_from_email.user_id != user_token.user_id {
return Err(UserErrors::LinkInvalid.into());
}
let user_from_db: domain::UserFromStorage = state
.global_store
.update_user_by_user_id(
user_from_email.user_id.as_str(),
storage_user::UserUpdate::VerifyUser,
)
.await
.change_context(UserErrors::InternalServerError)?
.into();
let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
.await
.map_err(|error| logger::error!(?error));
let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::VerifyEmail.into())?;
let next_flow = current_flow.next(user_from_db, &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 send_verification_mail(
state: SessionState,
req: user_api::SendVerifyEmailRequest,
auth_id: Option<String>,
theme_id: Option<String>,
) -> UserResponse<()> {
let user_email = domain::UserEmail::from_pii_email(req.email)?;
utils::user::validate_email_domain_auth_type_using_db(
&state,
&user_email,
UserAuthType::MagicLink,
)
.await?;
let user = 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)
}
})?;
if user.is_verified {
return Err(UserErrors::UserAlreadyVerified.into());
}
let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
let email_contents = email_types::VerifyEmail {
recipient_email: domain::UserEmail::from_pii_email(user.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()),
};
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(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn update_user_details(
state: SessionState,
user_token: auth::UserFromToken,
req: user_api::UpdateUserAccountDetailsRequest,
_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 name = req.name.map(domain::UserName::new).transpose()?;
let user_update = storage_user::UserUpdate::AccountUpdate {
name: name.map(|name| name.get_secret().expose()),
is_verified: None,
};
state
.global_store
.update_user_by_user_id(user.get_user_id(), user_update)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::StatusOk)
}
#[cfg(feature = "email")]
pub async fn user_from_email(
state: SessionState,
req: user_api::UserFromEmailRequest,
) -> UserResponse<user_api::TokenResponse> {
let token = req.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();
let next_flow =
domain::NextFlow::from_origin(email_token.get_flow(), 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 begin_totp(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
) -> UserResponse<user_api::BeginTotpResponse> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
if user_from_db.get_totp_status() == TotpStatus::Set {
return Ok(ApplicationResponse::Json(user_api::BeginTotpResponse {
secret: None,
}));
}
let totp = tfa_utils::generate_default_totp(
user_from_db.get_email(),
None,
state.conf.user.totp_issuer_name.clone(),
)?;
let secret = totp.get_secret_base32().into();
tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?;
Ok(ApplicationResponse::Json(user_api::BeginTotpResponse {
secret: Some(user_api::TotpSecret {
secret,
totp_url: totp.get_url().into(),
}),
}))
}
pub async fn reset_totp(
state: SessionState,
user_token: auth::UserFromToken,
) -> UserResponse<user_api::BeginTotpResponse> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
if user_from_db.get_totp_status() != TotpStatus::Set {
return Err(UserErrors::TotpNotSetup.into());
}
if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?
&& !tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await?
{
return Err(UserErrors::TwoFactorAuthRequired.into());
}
let totp = tfa_utils::generate_default_totp(
user_from_db.get_email(),
None,
state.conf.user.totp_issuer_name.clone(),
)?;
let secret = totp.get_secret_base32().into();
tfa_utils::insert_totp_secret_in_redis(&state, &user_token.user_id, &secret).await?;
Ok(ApplicationResponse::Json(user_api::BeginTotpResponse {
secret: Some(user_api::TotpSecret {
secret,
totp_url: totp.get_url().into(),
}),
}))
}
pub async fn verify_totp(
state: SessionState,
user_token: auth::UserIdFromAuth,
req: user_api::VerifyTotpRequest,
) -> UserResponse<user_api::TokenResponse> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
if user_from_db.get_totp_status() != TotpStatus::Set {
return Err(UserErrors::TotpNotSetup.into());
}
let user_totp_attempts =
tfa_utils::get_totp_attempts_from_redis(&state, &user_token.user_id).await?;
if user_totp_attempts >= consts::user::TOTP_MAX_ATTEMPTS {
return Err(UserErrors::MaxTotpAttemptsReached.into());
}
let user_totp_secret = user_from_db
.decrypt_and_get_totp_secret(&state)
.await?
.ok_or(UserErrors::InternalServerError)?;
let totp = tfa_utils::generate_default_totp(
user_from_db.get_email(),
Some(user_totp_secret),
state.conf.user.totp_issuer_name.clone(),
)?;
if totp
.generate_current()
.change_context(UserErrors::InternalServerError)?
!= req.totp.expose()
{
let _ = tfa_utils::insert_totp_attempts_in_redis(
&state,
&user_token.user_id,
user_totp_attempts + 1,
)
.await
.inspect_err(|error| logger::error!(?error));
return Err(UserErrors::InvalidTotp.into());
}
tfa_utils::insert_totp_in_redis(&state, &user_token.user_id).await?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn update_totp(
state: SessionState,
user_token: auth::UserIdFromAuth,
req: user_api::VerifyTotpRequest,
) -> UserResponse<()> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
let new_totp_secret = tfa_utils::get_totp_secret_from_redis(&state, &user_token.user_id)
.await?
.ok_or(UserErrors::TotpSecretNotFound)?;
let totp = tfa_utils::generate_default_totp(
user_from_db.get_email(),
Some(new_totp_secret),
state.conf.user.totp_issuer_name.clone(),
)?;
if totp
.generate_current()
.change_context(UserErrors::InternalServerError)?
!= req.totp.expose()
{
return Err(UserErrors::InvalidTotp.into());
}
let key_store = user_from_db.get_or_create_key_store(&state).await?;
state
.global_store
.update_user_by_user_id(
&user_token.user_id,
storage_user::UserUpdate::TotpUpdate {
totp_status: None,
totp_secret: Some(
// TODO: Impl conversion trait for User and move this there
domain::types::crypto_operation::<String, masking::WithType>(
&(&state).into(),
type_name!(storage_user::User),
domain::types::CryptoOperation::Encrypt(totp.get_secret_base32().into()),
Identifier::User(key_store.user_id.clone()),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(UserErrors::InternalServerError)?
.into(),
),
totp_recovery_codes: None,
},
)
.await
.change_context(UserErrors::InternalServerError)?;
let _ = tfa_utils::delete_totp_secret_from_redis(&state, &user_token.user_id)
.await
.map_err(|error| logger::error!(?error));
// This is not the main task of this API, so we don't throw error if this fails.
// Any following API which requires TOTP will throw error if TOTP is not set in redis
// and FE will ask user to enter TOTP again
let _ = tfa_utils::insert_totp_in_redis(&state, &user_token.user_id)
.await
.map_err(|error| logger::error!(?error));
Ok(ApplicationResponse::StatusOk)
}
pub async fn generate_recovery_codes(
state: SessionState,
user_token: auth::UserIdFromAuth,
) -> UserResponse<user_api::RecoveryCodes> {
if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? {
return Err(UserErrors::TotpRequired.into());
}
let recovery_codes = domain::RecoveryCodes::generate_new();
state
.global_store
.update_user_by_user_id(
&user_token.user_id,
storage_user::UserUpdate::TotpUpdate {
totp_status: None,
totp_secret: None,
totp_recovery_codes: Some(
recovery_codes
.get_hashed()
.change_context(UserErrors::InternalServerError)?,
),
},
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(user_api::RecoveryCodes {
recovery_codes: recovery_codes.into_inner(),
}))
}
pub async fn transfer_user_key_store_keymanager(
state: SessionState,
req: user_api::UserKeyTransferRequest,
) -> UserResponse<user_api::UserTransferKeyResponse> {
let db = &state.global_store;
let key_stores = db
.get_all_user_key_store(
&(&state).into(),
&state.store.get_master_key().to_vec().into(),
req.from,
req.limit,
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(
user_api::UserTransferKeyResponse {
total_transferred: send_request_to_key_service_for_user(&state, key_stores)
.await
.change_context(UserErrors::InternalServerError)?,
},
))
}
pub async fn verify_recovery_code(
state: SessionState,
user_token: auth::UserIdFromAuth,
req: user_api::VerifyRecoveryCodeRequest,
) -> UserResponse<()> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
if user_from_db.get_totp_status() != TotpStatus::Set {
return Err(UserErrors::TwoFactorAuthNotSetup.into());
}
let user_recovery_code_attempts =
tfa_utils::get_recovery_code_attempts_from_redis(&state, &user_token.user_id).await?;
if user_recovery_code_attempts >= consts::user::RECOVERY_CODE_MAX_ATTEMPTS {
return Err(UserErrors::MaxRecoveryCodeAttemptsReached.into());
}
let mut recovery_codes = user_from_db
.get_recovery_codes()
.ok_or(UserErrors::InternalServerError)?;
let Some(matching_index) = utils::user::password::get_index_for_correct_recovery_code(
&req.recovery_code,
&recovery_codes,
)?
else {
let _ = tfa_utils::insert_recovery_code_attempts_in_redis(
&state,
&user_token.user_id,
user_recovery_code_attempts + 1,
)
.await
.inspect_err(|error| logger::error!(?error));
return Err(UserErrors::InvalidRecoveryCode.into());
};
tfa_utils::insert_recovery_code_in_redis(&state, user_from_db.get_user_id()).await?;
let _ = recovery_codes.remove(matching_index);
state
.global_store
.update_user_by_user_id(
user_from_db.get_user_id(),
storage_user::UserUpdate::TotpUpdate {
totp_status: None,
totp_secret: None,
totp_recovery_codes: Some(recovery_codes),
},
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::StatusOk)
}
pub async fn terminate_two_factor_auth(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
skip_two_factor_auth: bool,
) -> UserResponse<user_api::TokenResponse> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
if state.conf.user.force_two_factor_auth || !skip_two_factor_auth {
if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?
&& !tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await?
{
return Err(UserErrors::TwoFactorAuthRequired.into());
}
if user_from_db.get_recovery_codes().is_none() {
return Err(UserErrors::TwoFactorAuthNotSetup.into());
}
if user_from_db.get_totp_status() != TotpStatus::Set {
state
.global_store
.update_user_by_user_id(
user_from_db.get_user_id(),
storage_user::UserUpdate::TotpUpdate {
totp_status: Some(TotpStatus::Set),
totp_secret: None,
totp_recovery_codes: None,
},
)
.await
.change_context(UserErrors::InternalServerError)?;
}
}
let current_flow = domain::CurrentFlow::new(user_token.clone(), domain::SPTFlow::TOTP.into())?;
let next_flow = current_flow.next(user_from_db, &state).await?;
let token = next_flow.get_token(&state).await?;
let _ = tfa_utils::delete_totp_attempts_from_redis(&state, &user_token.user_id)
.await
.inspect_err(|error| logger::error!(?error));
let _ = tfa_utils::delete_recovery_code_attempts_from_redis(&state, &user_token.user_id)
.await
.inspect_err(|error| logger::error!(?error));
auth::cookies::set_cookie_response(
user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
},
token,
)
}
pub async fn check_two_factor_auth_status(
state: SessionState,
user_token: auth::UserFromToken,
) -> UserResponse<user_api::TwoFactorAuthStatusResponse> {
Ok(ApplicationResponse::Json(
user_api::TwoFactorAuthStatusResponse {
totp: tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?,
recovery_code: tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id)
.await?,
},
))
}
pub async fn check_two_factor_auth_status_with_attempts(
state: SessionState,
user_token: auth::UserIdFromAuth,
) -> UserResponse<user_api::TwoFactorStatus> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
let is_skippable = state.conf.user.force_two_factor_auth.not();
if user_from_db.get_totp_status() == TotpStatus::NotSet {
return Ok(ApplicationResponse::Json(user_api::TwoFactorStatus {
status: None,
is_skippable,
}));
};
let totp = user_api::TwoFactorAuthAttempts {
is_completed: tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?,
remaining_attempts: consts::user::TOTP_MAX_ATTEMPTS
- tfa_utils::get_totp_attempts_from_redis(&state, &user_token.user_id).await?,
};
let recovery_code = user_api::TwoFactorAuthAttempts {
is_completed: tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id).await?,
remaining_attempts: consts::user::RECOVERY_CODE_MAX_ATTEMPTS
- tfa_utils::get_recovery_code_attempts_from_redis(&state, &user_token.user_id).await?,
};
Ok(ApplicationResponse::Json(user_api::TwoFactorStatus {
status: Some(user_api::TwoFactorAuthStatusResponseWithAttempts {
totp,
recovery_code,
}),
is_skippable,
}))
}
pub async fn create_user_authentication_method(
state: SessionState,
req: user_api::CreateUserAuthenticationMethodRequest,
) -> UserResponse<user_api::CreateUserAuthenticationMethodResponse> {
let user_auth_encryption_key = hex::decode(
state
.conf
.user_auth_methods
.get_inner()
.encryption_key
.clone()
.expose(),
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to decode DEK")?;
let id = uuid::Uuid::new_v4().to_string();
let (private_config, public_config) = utils::user::construct_public_and_private_db_configs(
&state,
&req.auth_method,
&user_auth_encryption_key,
id.clone(),
)
.await?;
let auth_methods = state
.store
.list_user_authentication_methods_for_owner_id(&req.owner_id)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get list of auth methods for the owner id")?;
let (auth_id, email_domain) = if let Some(auth_method) = auth_methods.first() {
let email_domain = match &req.email_domain {
Some(email_domain) => {
if email_domain != &auth_method.email_domain {
return Err(report!(UserErrors::InvalidAuthMethodOperationWithMessage(
"Email domain mismatch".to_string(),
)));
}
email_domain.clone()
}
None => auth_method.email_domain.clone(),
};
(auth_method.auth_id.clone(), email_domain)
} else {
let email_domain =
req.email_domain
.ok_or(UserErrors::InvalidAuthMethodOperationWithMessage(
"Email domain not found".to_string(),
))?;
(uuid::Uuid::new_v4().to_string(), email_domain)
};
for db_auth_method in auth_methods {
let is_type_same = db_auth_method.auth_type == (&req.auth_method).foreign_into();
let is_extra_identifier_same = match &req.auth_method {
user_api::AuthConfig::OpenIdConnect { public_config, .. } => {
let db_auth_name = db_auth_method
.public_config
.map(|config| {
utils::user::parse_value::<user_api::OpenIdConnectPublicConfig>(
config,
"OpenIdConnectPublicConfig",
)
})
.transpose()?
.map(|config| config.name);
db_auth_name.is_some_and(|name| name == public_config.name)
}
user_api::AuthConfig::Password | user_api::AuthConfig::MagicLink => true,
};
if is_type_same && is_extra_identifier_same {
return Err(report!(UserErrors::UserAuthMethodAlreadyExists));
}
}
let now = common_utils::date_time::now();
let inserted_auth_method = state
.store
.insert_user_authentication_method(UserAuthenticationMethodNew {
id,
auth_id,
owner_id: req.owner_id,
owner_type: req.owner_type,
auth_type: (&req.auth_method).foreign_into(),
private_config,
public_config,
allow_signup: req.allow_signup,
created_at: now,
last_modified_at: now,
email_domain,
})
.await
.to_duplicate_response(UserErrors::UserAuthMethodAlreadyExists)?;
Ok(ApplicationResponse::Json(
user_api::CreateUserAuthenticationMethodResponse {
id: inserted_auth_method.id,
auth_id: inserted_auth_method.auth_id,
owner_id: inserted_auth_method.owner_id,
owner_type: inserted_auth_method.owner_type,
auth_type: inserted_auth_method.auth_type,
email_domain: Some(inserted_auth_method.email_domain),
allow_signup: inserted_auth_method.allow_signup,
},
))
}
pub async fn update_user_authentication_method(
state: SessionState,
req: user_api::UpdateUserAuthenticationMethodRequest,
) -> UserResponse<()> {
let user_auth_encryption_key = hex::decode(
state
.conf
.user_auth_methods
.get_inner()
.encryption_key
.clone()
.expose(),
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to decode DEK")?;
match req {
user_api::UpdateUserAuthenticationMethodRequest::AuthMethod {
id,
auth_config: auth_method,
} => {
let (private_config, public_config) =
utils::user::construct_public_and_private_db_configs(
&state,
&auth_method,
&user_auth_encryption_key,
id.clone(),
)
.await?;
state
.store
.update_user_authentication_method(
&id,
UserAuthenticationMethodUpdate::UpdateConfig {
private_config,
public_config,
},
)
.await
.map_err(|error| {
let user_error = match error.current_context() {
StorageError::ValueNotFound(_) => {
UserErrors::InvalidAuthMethodOperationWithMessage(
"Auth method not found".to_string(),
)
}
StorageError::DuplicateValue { .. } => {
UserErrors::UserAuthMethodAlreadyExists
}
_ => UserErrors::InternalServerError,
};
error.change_context(user_error)
})?;
}
user_api::UpdateUserAuthenticationMethodRequest::EmailDomain {
owner_id,
email_domain,
} => {
let auth_methods = state
.store
.list_user_authentication_methods_for_owner_id(&owner_id)
.await
.change_context(UserErrors::InternalServerError)?;
futures::future::try_join_all(auth_methods.iter().map(|auth_method| async {
state
.store
.update_user_authentication_method(
&auth_method.id,
UserAuthenticationMethodUpdate::EmailDomain {
email_domain: email_domain.clone(),
},
)
.await
.to_duplicate_response(UserErrors::UserAuthMethodAlreadyExists)
}))
.await?;
}
}
Ok(ApplicationResponse::StatusOk)
}
pub async fn list_user_authentication_methods(
state: SessionState,
req: user_api::GetUserAuthenticationMethodsRequest,
) -> UserResponse<Vec<user_api::UserAuthenticationMethodResponse>> {
let user_authentication_methods = match (req.auth_id, req.email_domain) {
(Some(auth_id), None) => state
.store
.list_user_authentication_methods_for_auth_id(&auth_id)
.await
.change_context(UserErrors::InternalServerError)?,
(None, Some(email_domain)) => state
.store
.list_user_authentication_methods_for_email_domain(&email_domain)
.await
.change_context(UserErrors::InternalServerError)?,
(Some(_), Some(_)) | (None, None) => {
return Err(UserErrors::InvalidUserAuthMethodOperation.into());
}
};
Ok(ApplicationResponse::Json(
user_authentication_methods
.into_iter()
.map(|auth_method| {
let auth_name = match (auth_method.auth_type, auth_method.public_config) {
(UserAuthType::OpenIdConnect, config) => {
let open_id_public_config: Option<user_api::OpenIdConnectPublicConfig> =
config
.map(|config| {
utils::user::parse_value(config, "OpenIdConnectPublicConfig")
})
.transpose()?;
if let Some(public_config) = open_id_public_config {
Ok(Some(public_config.name))
} else {
Err(report!(UserErrors::InternalServerError))
.attach_printable("Public config not found for OIDC auth type")
}
}
_ => Ok(None),
}?;
Ok(user_api::UserAuthenticationMethodResponse {
id: auth_method.id,
auth_id: auth_method.auth_id,
auth_method: user_api::AuthMethodDetails {
name: auth_name,
auth_type: auth_method.auth_type,
},
allow_signup: auth_method.allow_signup,
})
})
.collect::<UserResult<_>>()?,
))
}
#[cfg(feature = "v1")]
pub async fn get_sso_auth_url(
state: SessionState,
request: user_api::GetSsoAuthUrlRequest,
) -> UserResponse<()> {
let user_authentication_method = state
.store
.get_user_authentication_method_by_id(request.id.as_str())
.await
.to_not_found_response(UserErrors::InvalidUserAuthMethodOperation)?;
let open_id_private_config = utils::user::decrypt_oidc_private_config(
&state,
user_authentication_method.private_config,
request.id.clone(),
)
.await?;
let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>(
user_authentication_method
.public_config
.ok_or(UserErrors::InternalServerError)
.attach_printable("Public config not present")?,
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to parse OpenIdConnectPublicConfig")?;
let oidc_state = Secret::new(nanoid::nanoid!());
utils::user::set_sso_id_in_redis(&state, oidc_state.clone(), request.id).await?;
let redirect_url =
utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string());
openidconnect::get_authorization_url(
state,
redirect_url,
oidc_state,
open_id_private_config.base_url.into(),
open_id_private_config.client_id,
)
.await
.map(|url| {
ApplicationResponse::JsonForRedirection(RedirectionResponse {
headers: Vec::with_capacity(0),
return_url: String::new(),
http_method: String::new(),
params: Vec::with_capacity(0),
return_url_with_query_params: url.to_string(),
})
})
}
pub async fn sso_sign(
state: SessionState,
request: user_api::SsoSignInRequest,
user_from_single_purpose_token: Option<auth::UserFromSinglePurposeToken>,
) -> UserResponse<user_api::TokenResponse> {
let authentication_method_id =
utils::user::get_sso_id_from_redis(&state, request.state.clone()).await?;
let user_authentication_method = state
.store
.get_user_authentication_method_by_id(&authentication_method_id)
.await
.change_context(UserErrors::InternalServerError)?;
let open_id_private_config = utils::user::decrypt_oidc_private_config(
&state,
user_authentication_method.private_config,
authentication_method_id,
)
.await?;
let open_id_public_config = serde_json::from_value::<user_api::OpenIdConnectPublicConfig>(
user_authentication_method
.public_config
.ok_or(UserErrors::InternalServerError)
.attach_printable("Public config not present")?,
)
.change_context(UserErrors::InternalServerError)
.attach_printable("Unable to parse OpenIdConnectPublicConfig")?;
let redirect_url =
utils::user::get_oidc_sso_redirect_url(&state, &open_id_public_config.name.to_string());
let email = openidconnect::get_user_email_from_oidc_provider(
&state,
redirect_url,
request.state,
open_id_private_config.base_url.into(),
open_id_private_config.client_id,
request.code,
open_id_private_config.client_secret,
)
.await?;
utils::user::validate_email_domain_auth_type_using_db(
&state,
&email,
UserAuthType::OpenIdConnect,
)
.await?;
// TODO: Use config to handle not found error
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_email(&email)
.await
.map(Into::into)
.to_not_found_response(UserErrors::UserNotFound)?;
if !user_from_db.is_verified() {
state
.global_store
.update_user_by_user_id(
user_from_db.get_user_id(),
storage_user::UserUpdate::VerifyUser,
)
.await
.change_context(UserErrors::InternalServerError)?;
}
let next_flow = if let Some(user_from_single_purpose_token) = user_from_single_purpose_token {
let current_flow =
domain::CurrentFlow::new(user_from_single_purpose_token, domain::SPTFlow::SSO.into())?;
current_flow.next(user_from_db, &state).await?
} else {
domain::NextFlow::from_origin(domain::Origin::SignInWithSSO, user_from_db, &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 terminate_auth_select(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
req: user_api::AuthSelectRequest,
) -> UserResponse<user_api::TokenResponse> {
let user_from_db: domain::UserFromStorage = state
.global_store
.find_user_by_id(&user_token.user_id)
.await
.change_context(UserErrors::InternalServerError)?
.into();
let user_email = domain::UserEmail::from_pii_email(user_from_db.get_email())?;
let auth_methods = state
.store
.list_user_authentication_methods_for_email_domain(user_email.extract_domain()?)
.await
.change_context(UserErrors::InternalServerError)?;
let user_authentication_method = match (req.id, auth_methods.is_empty()) {
(Some(id), _) => auth_methods
.into_iter()
.find(|auth_method| auth_method.id == id)
.ok_or(UserErrors::InvalidUserAuthMethodOperation)?,
(None, true) => DEFAULT_USER_AUTH_METHOD.clone(),
(None, false) => return Err(UserErrors::InvalidUserAuthMethodOperation.into()),
};
let current_flow = domain::CurrentFlow::new(user_token, domain::SPTFlow::AuthSelect.into())?;
let mut next_flow = current_flow.next(user_from_db.clone(), &state).await?;
// Skip SSO if continue with password(TOTP)
if next_flow.get_flow() == domain::UserFlow::SPTFlow(domain::SPTFlow::SSO)
&& !utils::user::is_sso_auth_type(user_authentication_method.auth_type)
{
next_flow = next_flow.skip(user_from_db, &state).await?;
}
let token = next_flow.get_token(&state).await?;
auth::cookies::set_cookie_response(
user_api::TokenResponse {
token: token.clone(),
token_type: next_flow.get_flow().into(),
},
token,
)
}
pub async fn list_orgs_for_user(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::ListOrgsForUserResponse>> {
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)?;
if role_info.is_internal() {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Internal roles are not allowed for this operation".to_string(),
)
.into());
}
let orgs = match role_info.get_entity_type() {
EntityType::Tenant => {
let key_manager_state = &(&state).into();
state
.store
.list_merchant_and_org_ids(
key_manager_state,
consts::user::ORG_LIST_LIMIT_FOR_TENANT,
None,
)
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.map(|(_, org_id)| org_id)
.collect::<HashSet<_>>()
}
EntityType::Organization | EntityType::Merchant | EntityType::Profile => state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_token.user_id.as_str(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: None,
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.filter_map(|user_role| user_role.org_id)
.collect::<HashSet<_>>(),
};
let resp = futures::future::try_join_all(
orgs.iter()
.map(|org_id| state.accounts_store.find_organization_by_org_id(org_id)),
)
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.map(|org| user_api::ListOrgsForUserResponse {
org_id: org.get_organization_id(),
org_name: org.get_organization_name(),
org_type: org.organization_type.unwrap_or_default(),
})
.collect::<Vec<_>>();
if resp.is_empty() {
Err(UserErrors::InternalServerError).attach_printable("No orgs found for a user")?;
}
Ok(ApplicationResponse::Json(resp))
}
pub async fn list_merchants_for_user_in_org(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::UserMerchantAccountResponse>> {
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)?;
if role_info.is_internal() {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Internal roles are not allowed for this operation".to_string(),
)
.into());
}
let merchant_accounts = match role_info.get_entity_type() {
EntityType::Tenant | EntityType::Organization => state
.store
.list_merchant_accounts_by_organization_id(&(&state).into(), &user_from_token.org_id)
.await
.change_context(UserErrors::InternalServerError)?,
EntityType::Merchant | EntityType::Profile => {
let merchant_ids = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_token.user_id.as_str(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: Some(&user_from_token.org_id),
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.filter_map(|user_role| user_role.merchant_id)
.collect::<HashSet<_>>()
.into_iter()
.collect();
state
.store
.list_multiple_merchant_accounts(&(&state).into(), merchant_ids)
.await
.change_context(UserErrors::InternalServerError)?
}
};
// TODO: Add a check to see if merchant accounts are empty, and handle accordingly, when a single route will be used instead
// of having two separate routes.
Ok(ApplicationResponse::Json(
merchant_accounts
.into_iter()
.map(|merchant_account| user_api::UserMerchantAccountResponse {
merchant_name: merchant_account.merchant_name.clone(),
merchant_id: merchant_account.get_id().to_owned(),
product_type: merchant_account.product_type,
merchant_account_type: merchant_account.merchant_account_type,
version: merchant_account.version,
})
.collect::<Vec<_>>(),
))
}
pub async fn list_profiles_for_user_in_org_and_merchant_account(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> UserResponse<Vec<user_api::ListProfilesForUserInOrgAndMerchantAccountResponse>> {
let role_info = roles::RoleInfo::from_role_id_org_id_tenant_id(
&state,
&user_from_token.role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await
.change_context(UserErrors::InternalServerError)?;
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&user_from_token.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)?;
let profiles = match role_info.get_entity_type() {
EntityType::Tenant | EntityType::Organization | EntityType::Merchant => state
.store
.list_profile_by_merchant_id(
key_manager_state,
&key_store,
&user_from_token.merchant_id,
)
.await
.change_context(UserErrors::InternalServerError)?,
EntityType::Profile => {
let profile_ids = state
.global_store
.list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
user_id: user_from_token.user_id.as_str(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
org_id: Some(&user_from_token.org_id),
merchant_id: Some(&user_from_token.merchant_id),
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.filter_map(|user_role| user_role.profile_id)
.collect::<HashSet<_>>();
futures::future::try_join_all(profile_ids.iter().map(|profile_id| {
state.store.find_business_profile_by_profile_id(
key_manager_state,
&key_store,
profile_id,
)
}))
.await
.change_context(UserErrors::InternalServerError)?
}
};
if profiles.is_empty() {
Err(UserErrors::InternalServerError).attach_printable("No profile found for a user")?;
}
Ok(ApplicationResponse::Json(
profiles
.into_iter()
.map(
|profile| user_api::ListProfilesForUserInOrgAndMerchantAccountResponse {
profile_id: profile.get_id().to_owned(),
profile_name: profile.profile_name,
},
)
.collect::<Vec<_>>(),
))
}
pub async fn switch_org_for_user(
state: SessionState,
request: user_api::SwitchOrganizationRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::TokenResponse> {
if user_from_token.org_id == request.org_id {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User switching to same org".to_string(),
)
.into());
}
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")?;
if role_info.is_internal() {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"Org switching not allowed for Internal role".to_string(),
)
.into());
}
let (merchant_id, profile_id, role_id) = match role_info.get_entity_type() {
EntityType::Tenant => {
let merchant_id = state
.store
.list_merchant_accounts_by_organization_id(&(&state).into(), &request.org_id)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get merchant list for org")?
.pop()
.ok_or(UserErrors::InvalidRoleOperation)
.attach_printable("No merchants found for the org id")?
.get_id()
.to_owned();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&(&state).into(),
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)?;
let profile_id = state
.store
.list_profile_by_merchant_id(&(&state).into(), &key_store, &merchant_id)
.await
.change_context(UserErrors::InternalServerError)?
.pop()
.ok_or(UserErrors::InternalServerError)?
.get_id()
.to_owned();
(merchant_id, profile_id, user_from_token.role_id)
}
EntityType::Organization | EntityType::Merchant | EntityType::Profile => {
let user_role = 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: Some(&request.org_id),
merchant_id: None,
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list user roles by user_id and org_id")?
.pop()
.ok_or(UserErrors::InvalidRoleOperationWithMessage(
"No user role found for the requested org_id".to_string(),
))?;
let (merchant_id, profile_id) =
utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role).await?;
(merchant_id, profile_id, user_role.role_id)
}
};
let lineage_context = LineageContext {
user_id: user_from_token.user_id.clone(),
merchant_id: merchant_id.clone(),
role_id: role_id.clone(),
org_id: request.org_id.clone(),
profile_id: profile_id.clone(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id)
.clone(),
};
utils::user::spawn_async_lineage_context_update_to_db(
&state,
&user_from_token.user_id,
lineage_context,
);
let token = utils::user::generate_jwt_auth_token_with_attributes(
&state,
user_from_token.user_id,
merchant_id.clone(),
request.org_id.clone(),
role_id.clone(),
profile_id.clone(),
user_from_token.tenant_id.clone(),
)
.await?;
utils::user_role::set_role_info_in_cache_by_role_id_org_id(
&state,
&role_id,
&request.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await;
let response = user_api::TokenResponse {
token: token.clone(),
token_type: common_enums::TokenPurpose::UserInfo,
};
auth::cookies::set_cookie_response(response, token)
}
pub async fn switch_merchant_for_user_in_org(
state: SessionState,
request: user_api::SwitchMerchantRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::TokenResponse> {
if user_from_token.merchant_id == request.merchant_id {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User switching to same merchant".to_string(),
)
.into());
}
let key_manager_state = &(&state).into();
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")?;
// Check if the role is internal and handle separately
let (org_id, merchant_id, profile_id, role_id) = if role_info.is_internal() {
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&request.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(UserErrors::MerchantIdNotFound)?;
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
&request.merchant_id,
&merchant_key_store,
)
.await
.to_not_found_response(UserErrors::MerchantIdNotFound)?;
let profile_id = state
.store
.list_profile_by_merchant_id(
key_manager_state,
&merchant_key_store,
&request.merchant_id,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list business profiles by merchant_id")?
.pop()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No business profile found for the given merchant_id")?
.get_id()
.to_owned();
(
merchant_account.organization_id,
request.merchant_id,
profile_id,
user_from_token.role_id.clone(),
)
} else {
// Match based on the other entity types
match role_info.get_entity_type() {
EntityType::Tenant | EntityType::Organization => {
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&request.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(UserErrors::MerchantIdNotFound)?;
let merchant_id = state
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
&request.merchant_id,
&merchant_key_store,
)
.await
.change_context(UserErrors::MerchantIdNotFound)?
.organization_id
.eq(&user_from_token.org_id)
.then(|| request.merchant_id.clone())
.ok_or_else(|| {
UserErrors::InvalidRoleOperationWithMessage(
"No such merchant_id found for the user in the org".to_string(),
)
})?;
let profile_id = state
.store
.list_profile_by_merchant_id(
key_manager_state,
&merchant_key_store,
&merchant_id,
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list business profiles by merchant_id")?
.pop()
.ok_or(UserErrors::InternalServerError)
.attach_printable("No business profile found for the merchant_id")?
.get_id()
.to_owned();
(
user_from_token.org_id.clone(),
merchant_id,
profile_id,
user_from_token.role_id.clone(),
)
}
EntityType::Merchant | EntityType::Profile => {
let user_role = 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: Some(&user_from_token.org_id),
merchant_id: Some(&request.merchant_id),
profile_id: None,
entity_id: None,
version: None,
status: Some(UserStatus::Active),
limit: Some(1),
})
.await
.change_context(UserErrors::InternalServerError)
.attach_printable(
"Failed to list user roles for the given user_id, org_id and merchant_id",
)?
.pop()
.ok_or(UserErrors::InvalidRoleOperationWithMessage(
"No user role associated with the requested merchant_id".to_string(),
))?;
let (merchant_id, profile_id) =
utils::user_role::get_single_merchant_id_and_profile_id(&state, &user_role)
.await?;
(
user_from_token.org_id,
merchant_id,
profile_id,
user_role.role_id,
)
}
}
};
let lineage_context = LineageContext {
user_id: user_from_token.user_id.clone(),
merchant_id: merchant_id.clone(),
role_id: role_id.clone(),
org_id: org_id.clone(),
profile_id: profile_id.clone(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id)
.clone(),
};
utils::user::spawn_async_lineage_context_update_to_db(
&state,
&user_from_token.user_id,
lineage_context,
);
let token = utils::user::generate_jwt_auth_token_with_attributes(
&state,
user_from_token.user_id,
merchant_id.clone(),
org_id.clone(),
role_id.clone(),
profile_id,
user_from_token.tenant_id.clone(),
)
.await?;
utils::user_role::set_role_info_in_cache_by_role_id_org_id(
&state,
&role_id,
&org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await;
let response = user_api::TokenResponse {
token: token.clone(),
token_type: common_enums::TokenPurpose::UserInfo,
};
auth::cookies::set_cookie_response(response, token)
}
pub async fn switch_profile_for_user_in_org_and_merchant(
state: SessionState,
request: user_api::SwitchProfileRequest,
user_from_token: auth::UserFromToken,
) -> UserResponse<user_api::TokenResponse> {
if user_from_token.profile_id == request.profile_id {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User switching to same profile".to_string(),
)
.into());
}
let key_manager_state = &(&state).into();
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 (profile_id, role_id) = match role_info.get_entity_type() {
EntityType::Tenant | EntityType::Organization | EntityType::Merchant => {
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&user_from_token.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to retrieve merchant key store by merchant_id")?;
let profile_id = state
.store
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&merchant_key_store,
&user_from_token.merchant_id,
&request.profile_id,
)
.await
.change_context(UserErrors::InvalidRoleOperationWithMessage(
"No such profile found for the merchant".to_string(),
))?
.get_id()
.to_owned();
(profile_id, user_from_token.role_id)
}
EntityType::Profile => {
let user_role = 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: Some(&user_from_token.org_id),
merchant_id: Some(&user_from_token.merchant_id),
profile_id:Some(&request.profile_id),
entity_id: None,
version:None,
status: Some(UserStatus::Active),
limit: Some(1)
}
)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list user roles for the given user_id, org_id, merchant_id and profile_id")?
.pop()
.ok_or(UserErrors::InvalidRoleOperationWithMessage(
"No user role associated with the profile".to_string(),
))?;
(request.profile_id, user_role.role_id)
}
};
let lineage_context = LineageContext {
user_id: user_from_token.user_id.clone(),
merchant_id: user_from_token.merchant_id.clone(),
role_id: role_id.clone(),
org_id: user_from_token.org_id.clone(),
profile_id: profile_id.clone(),
tenant_id: user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id)
.clone(),
};
utils::user::spawn_async_lineage_context_update_to_db(
&state,
&user_from_token.user_id,
lineage_context,
);
let token = utils::user::generate_jwt_auth_token_with_attributes(
&state,
user_from_token.user_id,
user_from_token.merchant_id.clone(),
user_from_token.org_id.clone(),
role_id.clone(),
profile_id,
user_from_token.tenant_id.clone(),
)
.await?;
utils::user_role::set_role_info_in_cache_by_role_id_org_id(
&state,
&role_id,
&user_from_token.org_id,
user_from_token
.tenant_id
.as_ref()
.unwrap_or(&state.tenant.tenant_id),
)
.await;
let response = user_api::TokenResponse {
token: token.clone(),
token_type: common_enums::TokenPurpose::UserInfo,
};
auth::cookies::set_cookie_response(response, token)
}
#[cfg(feature = "v1")]
pub async fn clone_connector(
state: SessionState,
request: user_api::CloneConnectorRequest,
) -> UserResponse<api_models::admin::MerchantConnectorResponse> {
let Some(allowlist) = &state.conf.clone_connector_allowlist else {
return Err(UserErrors::InvalidCloneConnectorOperation(
"Cloning is not allowed".to_string(),
)
.into());
};
fp_utils::when(
allowlist
.merchant_ids
.contains(&request.source.merchant_id)
.not(),
|| {
Err(UserErrors::InvalidCloneConnectorOperation(
"Cloning is not allowed from this merchant".to_string(),
))
},
)?;
let key_manager_state = &(&state).into();
let source_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&request.source.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(UserErrors::InvalidCloneConnectorOperation(
"Source merchant account not found".to_string(),
))?;
let source_mca = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&request.source.merchant_id,
&request.source.mca_id,
&source_key_store,
)
.await
.to_not_found_response(UserErrors::InvalidCloneConnectorOperation(
"Source merchant connector account not found".to_string(),
))?;
let source_mca_name = source_mca
.connector_name
.parse::<connector_enums::Connector>()
.change_context(UserErrors::InternalServerError)
.attach_printable("Invalid connector name received")?;
fp_utils::when(
allowlist.connector_names.contains(&source_mca_name).not(),
|| {
Err(UserErrors::InvalidCloneConnectorOperation(
"Cloning is not allowed for this connector".to_string(),
))
},
)?;
let merchant_connector_create = utils::user::build_cloned_connector_create_request(
source_mca,
Some(request.destination.profile_id.clone()),
request.destination.connector_label,
)
.await?;
let destination_key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&request.destination.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(UserErrors::InvalidCloneConnectorOperation(
"Destination merchant account not found".to_string(),
))?;
let destination_merchant_account = state
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
&request.destination.merchant_id,
&destination_key_store,
)
.await
.to_not_found_response(UserErrors::InvalidCloneConnectorOperation(
"Destination merchant account not found".to_string(),
))?;
let destination_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
destination_merchant_account,
destination_key_store,
)));
admin::create_connector(
state,
merchant_connector_create,
destination_context,
Some(request.destination.profile_id),
)
.await
.map_err(|e| {
let message = e.current_context().error_message();
e.change_context(UserErrors::ErrorCloningConnector(message))
})
.attach_printable("Failed to create cloned connector")
}
| crates/router/src/core/user.rs | router::src::core::user | 27,033 | true |
// File: crates/router/src/core/user_role.rs
// Module: router::src::core::user_role
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<_>, _>>()?,
))
}
pub async fn list_invitations_for_user(
state: SessionState,
user_from_token: auth::UserIdFromAuth,
) -> UserResponse<Vec<user_role_api::ListInvitationForUserResponse>> {
let user_roles = 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: Some(UserStatus::InvitationSent),
limit: None,
})
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to list user roles by user id and invitation sent")?
.into_iter()
.collect::<HashSet<_>>();
let (org_ids, merchant_ids, profile_ids_with_merchant_ids) = user_roles.iter().try_fold(
(Vec::new(), Vec::new(), Vec::new()),
|(mut org_ids, mut merchant_ids, mut profile_ids_with_merchant_ids), user_role| {
let (_, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)
.attach_printable("Failed to compute entity id and type")?;
match entity_type {
EntityType::Tenant => {
return Err(report!(UserErrors::InternalServerError))
.attach_printable("Tenant roles are not allowed for this operation");
}
EntityType::Organization => org_ids.push(
user_role
.org_id
.clone()
.ok_or(UserErrors::InternalServerError)?,
),
EntityType::Merchant => merchant_ids.push(
user_role
.merchant_id
.clone()
.ok_or(UserErrors::InternalServerError)?,
),
EntityType::Profile => profile_ids_with_merchant_ids.push((
user_role
.profile_id
.clone()
.ok_or(UserErrors::InternalServerError)?,
user_role
.merchant_id
.clone()
.ok_or(UserErrors::InternalServerError)?,
)),
}
Ok::<_, error_stack::Report<UserErrors>>((
org_ids,
merchant_ids,
profile_ids_with_merchant_ids,
))
},
)?;
let org_name_map = futures::future::try_join_all(org_ids.into_iter().map(|org_id| async {
let org_name = state
.accounts_store
.find_organization_by_org_id(&org_id)
.await
.change_context(UserErrors::InternalServerError)?
.get_organization_name()
.map(Secret::new);
Ok::<_, error_stack::Report<UserErrors>>((org_id, org_name))
}))
.await?
.into_iter()
.collect::<HashMap<_, _>>();
let key_manager_state = &(&state).into();
let merchant_name_map = state
.store
.list_multiple_merchant_accounts(key_manager_state, merchant_ids)
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
.map(|merchant| {
(
merchant.get_id().clone(),
merchant
.merchant_name
.map(|encryptable_name| encryptable_name.into_inner()),
)
})
.collect::<HashMap<_, _>>();
let master_key = &state.store.get_master_key().to_vec().into();
let profile_name_map = futures::future::try_join_all(profile_ids_with_merchant_ids.iter().map(
|(profile_id, merchant_id)| async {
let merchant_key_store = state
.store
.get_merchant_key_store_by_merchant_id(key_manager_state, merchant_id, master_key)
.await
.change_context(UserErrors::InternalServerError)?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
&merchant_key_store,
profile_id,
)
.await
.change_context(UserErrors::InternalServerError)?;
Ok::<_, error_stack::Report<UserErrors>>((
profile_id.clone(),
Secret::new(business_profile.profile_name),
))
},
))
.await?
.into_iter()
.collect::<HashMap<_, _>>();
user_roles
.into_iter()
.map(|user_role| {
let (entity_id, entity_type) = user_role
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)
.attach_printable("Failed to compute entity id and type")?;
let entity_name = match entity_type {
EntityType::Tenant => {
return Err(report!(UserErrors::InternalServerError))
.attach_printable("Tenant roles are not allowed for this operation");
}
EntityType::Organization => user_role
.org_id
.as_ref()
.and_then(|org_id| org_name_map.get(org_id).cloned())
.ok_or(UserErrors::InternalServerError)?,
EntityType::Merchant => user_role
.merchant_id
.as_ref()
.and_then(|merchant_id| merchant_name_map.get(merchant_id).cloned())
.ok_or(UserErrors::InternalServerError)?,
EntityType::Profile => user_role
.profile_id
.as_ref()
.map(|profile_id| profile_name_map.get(profile_id).cloned())
.ok_or(UserErrors::InternalServerError)?,
};
Ok(user_role_api::ListInvitationForUserResponse {
entity_id,
entity_type,
entity_name,
role_id: user_role.role_id,
})
})
.collect::<Result<Vec<_>, _>>()
.map(ApplicationResponse::Json)
}
| crates/router/src/core/user_role.rs | router::src::core::user_role | 7,832 | true |
// File: crates/router/src/core/files.rs
// Module: router::src::core::files
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,
merchant_context: domain::MerchantContext,
create_file_request: api::CreateFileRequest,
) -> RouterResponse<files::CreateFileResponse> {
helpers::validate_file_upload(
&state,
merchant_context.clone(),
create_file_request.clone(),
)
.await?;
let file_id = common_utils::generate_id(consts::ID_LENGTH, "file");
let file_key = format!(
"{}/{}",
merchant_context
.get_merchant_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: merchant_context.get_merchant_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,
&merchant_context,
&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,
merchant_context: domain::MerchantContext,
req: api::FileId,
) -> RouterResponse<serde_json::Value> {
helpers::delete_file_using_file_id(&state, req.file_id.clone(), &merchant_context).await?;
state
.store
.as_ref()
.delete_file_metadata_by_merchant_id_file_id(
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
req: api::FileRetrieveRequest,
) -> RouterResponse<serde_json::Value> {
let file_metadata_object = state
.store
.as_ref()
.find_file_metadata_by_merchant_id_file_id(
merchant_context.get_merchant_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,
&merchant_context,
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,
)))
}
| crates/router/src/core/files.rs | router::src::core::files | 995 | true |
// File: crates/router/src/core/metrics.rs
// Module: router::src::core::metrics
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!(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);
| crates/router/src/core/metrics.rs | router::src::core::metrics | 965 | true |
// File: crates/router/src/core/unified_connector_service.rs
// Module: router::src::core::unified_connector_service
use std::{str::FromStr, time::Instant};
use api_models::admin;
#[cfg(feature = "v2")]
use base64::Engine;
use common_enums::{
connector_enums::Connector, AttemptStatus, ConnectorIntegrationType, ExecutionMode,
ExecutionPath, GatewaySystem, PaymentMethodType, ShadowRolloutAvailability, UcsAvailability,
};
#[cfg(feature = "v2")]
use common_utils::consts::BASE64_ENGINE;
use common_utils::{
consts::X_FLOW_NAME,
errors::CustomResult,
ext_traits::ValueExt,
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::{
merchant_context::MerchantContext,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_response_types::PaymentsResponseData,
};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
use unified_connector_service_cards::CardNumber;
use unified_connector_service_client::payments::{
self as payments_grpc, payment_method::PaymentMethod, CardDetails, CardPaymentMethodType,
PaymentServiceAuthorizeResponse, RewardPaymentMethodType,
};
#[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,
},
OperationSessionGetters, OperationSessionSetters,
},
utils::get_flow_name,
},
events::connector_api_logs::ConnectorEvent,
headers::{CONTENT_TYPE, X_REQUEST_ID},
routes::SessionState,
types::transformers::ForeignTryFrom,
};
pub mod transformers;
// Re-export webhook transformer types for easier access
pub use transformers::WebhookTransformData;
/// Type alias for return type used by unified connector service response handlers
type UnifiedConnectorServiceResult = CustomResult<
(
Result<(PaymentsResponseData, AttemptStatus), 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,
config_key: &str,
) -> 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);
let is_rollout_enabled = should_execute_based_on_rollout(state, config_key).await?;
if is_ucs_only || is_rollout_enabled {
router_env::logger::debug!(
connector = ?connector,
ucs_only_list = is_ucs_only,
rollout_enabled = is_rollout_enabled,
"Using UcsConnector"
);
Ok(ConnectorIntegrationType::UcsConnector)
} else {
router_env::logger::debug!(
connector = ?connector,
"Using DirectConnector - not in ucs_only_list and rollout not enabled"
);
Ok(ConnectorIntegrationType::DirectConnector)
}
}
None => {
router_env::logger::debug!(
connector = ?connector,
"UCS config not present, using DirectConnector"
);
Ok(ConnectorIntegrationType::DirectConnector)
}
}
}
pub async fn should_call_unified_connector_service<F: Clone, T, D>(
state: &SessionState,
merchant_context: &MerchantContext,
router_data: &RouterData<F, T, PaymentsResponseData>,
payment_data: Option<&D>,
) -> RouterResult<ExecutionPath>
where
D: OperationSessionGetters<F>,
{
// Extract context information
let merchant_id = merchant_context
.get_merchant_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 payment_method = router_data.payment_method.to_string();
let flow_name = get_flow_name::<F>()?;
// Check UCS availability using idiomatic helper
let ucs_availability = check_ucs_availability(state).await;
// Build rollout keys
let rollout_key = format!(
"{}_{}_{}_{}_{}",
consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
merchant_id,
connector_name,
payment_method,
flow_name
);
// Determine connector integration type
let connector_integration_type =
determine_connector_integration_type(state, connector_enum, &rollout_key).await?;
// Extract previous gateway from payment data
let previous_gateway = payment_data.and_then(extract_gateway_system_from_payment_intent);
let shadow_rollout_key = format!("{}_shadow", rollout_key);
let shadow_rollout_availability =
if should_execute_based_on_rollout(state, &shadow_rollout_key).await? {
ShadowRolloutAvailability::IsAvailable
} else {
ShadowRolloutAvailability::NotAvailable
};
// Single decision point using pattern matching
let (gateway_system, execution_path) = if ucs_availability == UcsAvailability::Disabled {
router_env::logger::debug!("UCS is disabled, using Direct gateway");
(GatewaySystem::Direct, ExecutionPath::Direct)
} else {
// UCS is enabled, call decide function
decide_execution_path(
connector_integration_type,
previous_gateway,
shadow_rollout_availability,
)?
};
router_env::logger::info!(
"Payment gateway decision: gateway={:?}, execution_path={:?} - merchant_id={}, connector={}, payment_method={}, flow={}",
gateway_system,
execution_path,
merchant_id,
connector_name,
payment_method,
flow_name
);
Ok(execution_path)
}
fn decide_execution_path(
connector_type: ConnectorIntegrationType,
previous_gateway: Option<GatewaySystem>,
shadow_rollout_enabled: ShadowRolloutAvailability,
) -> RouterResult<(GatewaySystem, ExecutionPath)> {
match (connector_type, previous_gateway, shadow_rollout_enabled) {
// Case 1: DirectConnector with no previous gateway and no shadow rollout
// This is a fresh payment request for a direct connector - use direct gateway
(
ConnectorIntegrationType::DirectConnector,
None,
ShadowRolloutAvailability::NotAvailable,
) => Ok((GatewaySystem::Direct, ExecutionPath::Direct)),
// Case 2: DirectConnector previously used Direct gateway, no shadow rollout
// Continue using the same direct gateway for consistency
(
ConnectorIntegrationType::DirectConnector,
Some(GatewaySystem::Direct),
ShadowRolloutAvailability::NotAvailable,
) => Ok((GatewaySystem::Direct, ExecutionPath::Direct)),
// Case 3: DirectConnector previously used UCS, but now switching back to Direct (no shadow)
// Migration scenario: UCS was used before, but now we're reverting to Direct
(
ConnectorIntegrationType::DirectConnector,
Some(GatewaySystem::UnifiedConnectorService),
ShadowRolloutAvailability::NotAvailable,
) => Ok((GatewaySystem::Direct, ExecutionPath::Direct)),
// Case 4: UcsConnector configuration, but previously used Direct gateway (no shadow)
// Maintain Direct for backward compatibility - don't switch mid-transaction
(
ConnectorIntegrationType::UcsConnector,
Some(GatewaySystem::Direct),
ShadowRolloutAvailability::NotAvailable,
) => Ok((GatewaySystem::Direct, ExecutionPath::Direct)),
// Case 5: DirectConnector with no previous gateway, shadow rollout enabled
// Use Direct as primary, but also execute UCS in shadow mode for comparison
(
ConnectorIntegrationType::DirectConnector,
None,
ShadowRolloutAvailability::IsAvailable,
) => Ok((
GatewaySystem::Direct,
ExecutionPath::ShadowUnifiedConnectorService,
)),
// Case 6: DirectConnector previously used Direct, shadow rollout enabled
// Continue with Direct as primary, execute UCS in shadow mode for testing
(
ConnectorIntegrationType::DirectConnector,
Some(GatewaySystem::Direct),
ShadowRolloutAvailability::IsAvailable,
) => Ok((
GatewaySystem::Direct,
ExecutionPath::ShadowUnifiedConnectorService,
)),
// Case 7: DirectConnector previously used UCS, shadow rollout enabled
// Revert to Direct as primary, but keep UCS in shadow mode for comparison
(
ConnectorIntegrationType::DirectConnector,
Some(GatewaySystem::UnifiedConnectorService),
ShadowRolloutAvailability::IsAvailable,
) => Ok((
GatewaySystem::Direct,
ExecutionPath::ShadowUnifiedConnectorService,
)),
// Case 8: UcsConnector configuration, previously used Direct, shadow rollout enabled
// Maintain Direct as primary for transaction consistency, shadow UCS for testing
(
ConnectorIntegrationType::UcsConnector,
Some(GatewaySystem::Direct),
ShadowRolloutAvailability::IsAvailable,
) => Ok((
GatewaySystem::Direct,
ExecutionPath::ShadowUnifiedConnectorService,
)),
// Case 9: UcsConnector with no previous gateway (regardless of shadow rollout)
// Fresh payment for a UCS-enabled connector - use UCS as primary
(ConnectorIntegrationType::UcsConnector, None, _) => Ok((
GatewaySystem::UnifiedConnectorService,
ExecutionPath::UnifiedConnectorService,
)),
// Case 10: UcsConnector previously used UCS (regardless of shadow rollout)
// Continue using UCS for consistency in the payment flow
(
ConnectorIntegrationType::UcsConnector,
Some(GatewaySystem::UnifiedConnectorService),
_,
) => Ok((
GatewaySystem::UnifiedConnectorService,
ExecutionPath::UnifiedConnectorService,
)),
}
}
/// Extracts the gateway system from the payment intent's feature metadata
/// Returns None if metadata is missing, corrupted, or doesn't contain gateway_system
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,
merchant_context: &MerchantContext,
connector_name: &str,
) -> RouterResult<bool> {
if state.grpc_client.unified_connector_service_client.is_none() {
logger::debug!(
connector = connector_name.to_string(),
"Unified Connector Service client is not available for webhooks"
);
return Ok(false);
}
let ucs_config_key = consts::UCS_ENABLED;
if !is_ucs_enabled(state, ucs_config_key).await {
return Ok(false);
}
let merchant_id = merchant_context
.get_merchant_account()
.get_id()
.get_string_repr();
let config_key = format!(
"{}_{}_{}_Webhooks",
consts::UCS_ROLLOUT_PERCENT_CONFIG_PREFIX,
merchant_id,
connector_name
);
let should_execute = should_execute_based_on_rollout(state, &config_key).await?;
Ok(should_execute)
}
pub fn build_unified_connector_service_payment_method(
payment_method_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData,
payment_method_type: 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.get_expiry_year_4_digit().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(),
};
let grpc_card_type = match payment_method_type {
PaymentMethodType::Credit => {
payments_grpc::card_payment_method_type::CardType::Credit(card_details)
}
PaymentMethodType::Debit => {
payments_grpc::card_payment_method_type::CardType::Debit(card_details)
}
_ => {
return Err(UnifiedConnectorServiceError::NotImplemented(format!(
"Unimplemented payment method subtype: {payment_method_type:?}"
))
.into());
}
};
Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(grpc_card_type),
})),
})
}
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()),
};
PaymentMethod::UpiCollect(upi_details)
}
hyperswitch_domain_models::payment_method_data::UpiData::UpiIntent(_) => {
let upi_details = payments_grpc::UpiIntent { app_name: None };
PaymentMethod::UpiIntent(upi_details)
}
hyperswitch_domain_models::payment_method_data::UpiData::UpiQr(_) => {
let upi_details = payments_grpc::UpiQr {};
PaymentMethod::UpiQr(upi_details)
}
};
Ok(payments_grpc::PaymentMethod {
payment_method: Some(upi_type),
})
}
hyperswitch_domain_models::payment_method_data::PaymentMethodData::Reward => {
match payment_method_type {
PaymentMethodType::ClassicReward => Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::Reward(RewardPaymentMethodType {
reward_type: 1,
})),
}),
PaymentMethodType::Evoucher => Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::Reward(RewardPaymentMethodType {
reward_type: 2,
})),
}),
_ => Err(UnifiedConnectorServiceError::NotImplemented(format!(
"Unimplemented payment method subtype: {payment_method_type:?}"
))
.into()),
}
}
_ => Err(UnifiedConnectorServiceError::NotImplemented(format!(
"Unimplemented payment method: {payment_method_data:?}"
))
.into()),
}
}
pub fn build_unified_connector_service_payment_method_for_external_proxy(
payment_method_data: hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData,
payment_method_type: PaymentMethodType,
) -> CustomResult<payments_grpc::PaymentMethod, UnifiedConnectorServiceError> {
match payment_method_data {
hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card(
external_vault_card,
) => {
let card_network = external_vault_card
.card_network
.clone()
.map(payments_grpc::CardNetwork::foreign_try_from)
.transpose()?;
let card_details = CardDetails {
card_number: Some(CardNumber::from_str(external_vault_card.card_number.peek()).change_context(
UnifiedConnectorServiceError::RequestEncodingFailedWithReason("Failed to parse card number".to_string())
)?),
card_exp_month: Some(external_vault_card.card_exp_month.expose().into()),
card_exp_year: Some(external_vault_card.card_exp_year.expose().into()),
card_cvc: Some(external_vault_card.card_cvc.expose().into()),
card_holder_name: external_vault_card.card_holder_name.map(|name| name.expose().into()),
card_issuer: external_vault_card.card_issuer.clone(),
card_network: card_network.map(|card_network| card_network.into()),
card_type: external_vault_card.card_type.clone(),
bank_code: external_vault_card.bank_code.clone(),
nick_name: external_vault_card.nick_name.map(|n| n.expose()),
card_issuing_country_alpha2: external_vault_card.card_issuing_country.clone(),
};
let grpc_card_type = match payment_method_type {
PaymentMethodType::Credit => {
payments_grpc::card_payment_method_type::CardType::CreditProxy(card_details)
}
PaymentMethodType::Debit => {
payments_grpc::card_payment_method_type::CardType::DebitProxy(card_details)
}
_ => {
return Err(UnifiedConnectorServiceError::NotImplemented(format!(
"Unimplemented payment method subtype: {payment_method_type:?}"
))
.into());
}
};
Ok(payments_grpc::PaymentMethod {
payment_method: Some(PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(grpc_card_type),
})),
})
}
hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::VaultToken(_) => {
Err(UnifiedConnectorServiceError::NotImplemented(format!(
"Unimplemented payment method subtype: {payment_method_type:?}"
))
.into())
}
}
}
pub fn build_unified_connector_service_auth_metadata(
#[cfg(feature = "v1")] merchant_connector_account: MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: MerchantConnectorAccountTypeDetails,
merchant_context: &MerchantContext,
) -> CustomResult<ConnectorAuthMetadata, UnifiedConnectorServiceError> {
#[cfg(feature = "v1")]
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(UnifiedConnectorServiceError::FailedToObtainAuthType)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
#[cfg(feature = "v2")]
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.change_context(UnifiedConnectorServiceError::FailedToObtainAuthType)
.attach_printable("Failed to obtain ConnectorAuthType")?;
let connector_name = {
#[cfg(feature = "v1")]
{
merchant_connector_account
.get_connector_name()
.ok_or(UnifiedConnectorServiceError::MissingConnectorName)
.attach_printable("Missing connector name")?
}
#[cfg(feature = "v2")]
{
merchant_connector_account
.get_connector_name()
.map(|connector| connector.to_string())
.ok_or(UnifiedConnectorServiceError::MissingConnectorName)
.attach_printable("Missing connector name")?
}
};
let merchant_id = merchant_context
.get_merchant_account()
.get_id()
.get_string_repr();
match &auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(ConnectorAuthMetadata {
connector_name,
auth_type: consts::UCS_AUTH_SIGNATURE_KEY.to_string(),
api_key: Some(api_key.clone()),
key1: Some(key1.clone()),
api_secret: Some(api_secret.clone()),
auth_key_map: None,
merchant_id: Secret::new(merchant_id.to_string()),
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(ConnectorAuthMetadata {
connector_name,
auth_type: consts::UCS_AUTH_BODY_KEY.to_string(),
api_key: Some(api_key.clone()),
key1: Some(key1.clone()),
api_secret: None,
auth_key_map: None,
merchant_id: Secret::new(merchant_id.to_string()),
}),
ConnectorAuthType::HeaderKey { api_key } => Ok(ConnectorAuthMetadata {
connector_name,
auth_type: consts::UCS_AUTH_HEADER_KEY.to_string(),
api_key: Some(api_key.clone()),
key1: None,
api_secret: None,
auth_key_map: None,
merchant_id: Secret::new(merchant_id.to_string()),
}),
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => Ok(ConnectorAuthMetadata {
connector_name,
auth_type: consts::UCS_AUTH_CURRENCY_AUTH_KEY.to_string(),
api_key: None,
key1: None,
api_secret: None,
auth_key_map: Some(auth_key_map.clone()),
merchant_id: Secret::new(merchant_id.to_string()),
}),
_ => Err(UnifiedConnectorServiceError::FailedToObtainAuthType)
.attach_printable("Unsupported ConnectorAuthType for header injection"),
}
}
#[cfg(feature = "v2")]
pub fn build_unified_connector_service_external_vault_proxy_metadata(
external_vault_merchant_connector_account: MerchantConnectorAccountTypeDetails,
) -> CustomResult<String, UnifiedConnectorServiceError> {
let external_vault_metadata = external_vault_merchant_connector_account
.get_metadata()
.ok_or(UnifiedConnectorServiceError::ParsingFailed)
.attach_printable("Failed to obtain ConnectorMetadata")?;
let connector_name = external_vault_merchant_connector_account
.get_connector_name()
.map(|connector| connector.to_string())
.ok_or(UnifiedConnectorServiceError::MissingConnectorName)
.attach_printable("Missing connector name")?; // always get the connector name from this call
let external_vault_connector = api_enums::VaultConnectors::from_str(&connector_name)
.change_context(UnifiedConnectorServiceError::InvalidConnectorName)
.attach_printable("Failed to parse Vault connector")?;
let unified_service_vault_metdata = match external_vault_connector {
api_enums::VaultConnectors::Vgs => {
let vgs_metadata: ExternalVaultConnectorMetadata = external_vault_metadata
.expose()
.parse_value("ExternalVaultConnectorMetadata")
.change_context(UnifiedConnectorServiceError::ParsingFailed)
.attach_printable("Failed to parse Vgs connector metadata")?;
Some(external_services::grpc_client::unified_connector_service::ExternalVaultProxyMetadata::VgsMetadata(
external_services::grpc_client::unified_connector_service::VgsMetadata {
proxy_url: vgs_metadata.proxy_url,
certificate: vgs_metadata.certificate,
}
))
}
api_enums::VaultConnectors::HyperswitchVault | api_enums::VaultConnectors::Tokenex => None,
};
match unified_service_vault_metdata {
Some(metdata) => {
let external_vault_metadata_bytes = serde_json::to_vec(&metdata)
.change_context(UnifiedConnectorServiceError::ParsingFailed)
.attach_printable("Failed to convert External vault metadata to bytes")?;
Ok(BASE64_ENGINE.encode(&external_vault_metadata_bytes))
}
None => Err(UnifiedConnectorServiceError::NotImplemented(
"External vault proxy metadata is not supported for {connector_name}".to_string(),
)
.into()),
}
}
pub fn handle_unified_connector_service_response_for_payment_authorize(
response: PaymentServiceAuthorizeResponse,
) -> UnifiedConnectorServiceResult {
let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
let router_data_response =
Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
Ok((router_data_response, status_code))
}
pub fn handle_unified_connector_service_response_for_payment_register(
response: payments_grpc::PaymentServiceRegisterResponse,
) -> UnifiedConnectorServiceResult {
let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
let router_data_response =
Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
Ok((router_data_response, status_code))
}
pub fn handle_unified_connector_service_response_for_payment_repeat(
response: payments_grpc::PaymentServiceRepeatEverythingResponse,
) -> UnifiedConnectorServiceResult {
let status_code = transformers::convert_connector_service_status_code(response.status_code)?;
let router_data_response =
Result::<(PaymentsResponseData, AttemptStatus), ErrorResponse>::foreign_try_from(response)?;
Ok((router_data_response, status_code))
}
pub fn build_webhook_secrets_from_merchant_connector_account(
#[cfg(feature = "v1")] merchant_connector_account: &MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: &MerchantConnectorAccountTypeDetails,
) -> CustomResult<Option<payments_grpc::WebhookSecrets>, UnifiedConnectorServiceError> {
// Extract webhook credentials from merchant connector account
// This depends on how webhook secrets are stored in the merchant connector account
#[cfg(feature = "v1")]
let webhook_details = merchant_connector_account
.get_webhook_details()
.map_err(|_| UnifiedConnectorServiceError::FailedToObtainAuthType)?;
#[cfg(feature = "v2")]
let webhook_details = match merchant_connector_account {
MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => {
mca.connector_webhook_details.as_ref()
}
MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,
};
match webhook_details {
Some(details) => {
// Parse the webhook details JSON to extract secrets
let webhook_details: admin::MerchantConnectorWebhookDetails = details
.clone()
.parse_value("MerchantConnectorWebhookDetails")
.change_context(UnifiedConnectorServiceError::FailedToObtainAuthType)
.attach_printable("Failed to parse MerchantConnectorWebhookDetails")?;
// Build gRPC WebhookSecrets from parsed details
Ok(Some(payments_grpc::WebhookSecrets {
secret: webhook_details.merchant_secret.expose().to_string(),
additional_secret: webhook_details
.additional_secret
.map(|secret| secret.expose().to_string()),
}))
}
None => Ok(None),
}
}
/// High-level abstraction for calling UCS webhook transformation
/// This provides a clean interface similar to payment flow UCS calls
pub async fn call_unified_connector_service_for_webhook(
state: &SessionState,
merchant_context: &MerchantContext,
connector_name: &str,
body: &actix_web::web::Bytes,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
merchant_connector_account: Option<
&hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
>,
) -> RouterResult<(
api_models::webhooks::IncomingWebhookEvent,
bool,
WebhookTransformData,
)> {
let ucs_client = state
.grpc_client
.unified_connector_service_client
.as_ref()
.ok_or_else(|| {
error_stack::report!(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("UCS client is not available for webhook processing")
})?;
// Build webhook secrets from merchant connector account
let webhook_secrets = merchant_connector_account.and_then(|mca| {
#[cfg(feature = "v1")]
let mca_type = MerchantConnectorAccountType::DbVal(Box::new(mca.clone()));
#[cfg(feature = "v2")]
let mca_type =
MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca.clone()));
build_webhook_secrets_from_merchant_connector_account(&mca_type)
.map_err(|e| {
logger::warn!(
build_error=?e,
connector_name=connector_name,
"Failed to build webhook secrets from merchant connector account in call_unified_connector_service_for_webhook"
);
e
})
.ok()
.flatten()
});
// Build UCS transform request using new webhook transformers
let transform_request = transformers::build_webhook_transform_request(
body,
request_details,
webhook_secrets,
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
connector_name,
)?;
// Build connector auth metadata
let connector_auth_metadata = merchant_connector_account
.map(|mca| {
#[cfg(feature = "v1")]
let mca_type = MerchantConnectorAccountType::DbVal(Box::new(mca.clone()));
#[cfg(feature = "v2")]
let mca_type = MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
mca.clone(),
));
build_unified_connector_service_auth_metadata(mca_type, merchant_context)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to build UCS auth metadata")?
.ok_or_else(|| {
error_stack::report!(errors::ApiErrorResponse::InternalServerError).attach_printable(
"Missing merchant connector account for UCS webhook transformation",
)
})?;
let profile_id = merchant_connector_account
.as_ref()
.map(|mca| mca.profile_id.clone())
.unwrap_or(consts::PROFILE_ID_UNAVAILABLE.clone());
// Build gRPC headers
let grpc_headers = state
.get_grpc_headers_ucs(ExecutionMode::Primary)
.lineage_ids(LineageIds::new(
merchant_context.get_merchant_account().get_id().clone(),
profile_id,
))
.external_vault_proxy_metadata(None)
.merchant_reference_id(None)
.build();
// Make UCS call - client availability already verified
match ucs_client
.transform_incoming_webhook(transform_request, connector_auth_metadata, grpc_headers)
.await
{
Ok(response) => {
let transform_response = response.into_inner();
let transform_data = transformers::transform_ucs_webhook_response(transform_response)?;
// UCS handles everything internally - event type, source verification, decoding
Ok((
transform_data.event_type,
transform_data.source_verified,
transform_data,
))
}
Err(err) => {
// When UCS is configured, we don't fall back to direct connector processing
Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable(format!("UCS webhook processing failed: {err}"))
}
}
}
/// Extract webhook content from UCS response for further processing
/// This provides a helper function to extract specific data from UCS responses
pub fn extract_webhook_content_from_ucs_response(
transform_data: &WebhookTransformData,
) -> Option<&unified_connector_service_client::payments::WebhookResponseContent> {
transform_data.webhook_content.as_ref()
}
/// UCS Event Logging Wrapper Function
/// This function wraps UCS calls with comprehensive event logging.
/// It logs the actual gRPC request/response data, timing, and error information.
#[instrument(skip_all, fields(connector_name, flow_type, payment_id))]
pub async fn ucs_logging_wrapper<T, F, Fut, Req, Resp, GrpcReq, GrpcResp>(
router_data: RouterData<T, Req, Resp>,
state: &SessionState,
grpc_request: GrpcReq,
grpc_header_builder: external_services::grpc_client::GrpcHeadersUcsBuilderFinal,
handler: F,
) -> RouterResult<RouterData<T, Req, Resp>>
where
T: std::fmt::Debug + Clone + Send + 'static,
Req: std::fmt::Debug + Clone + Send + Sync + 'static,
Resp: std::fmt::Debug + Clone + Send + Sync + 'static,
GrpcReq: serde::Serialize,
GrpcResp: serde::Serialize,
F: FnOnce(
RouterData<T, Req, Resp>,
GrpcReq,
external_services::grpc_client::GrpcHeadersUcs,
) -> Fut
+ Send,
Fut: std::future::Future<Output = RouterResult<(RouterData<T, Req, Resp>, GrpcResp)>> + Send,
{
tracing::Span::current().record("connector_name", &router_data.connector);
tracing::Span::current().record("flow_type", std::any::type_name::<T>());
tracing::Span::current().record("payment_id", &router_data.payment_id);
// Capture request data for logging
let connector_name = router_data.connector.clone();
let payment_id = router_data.payment_id.clone();
let merchant_id = router_data.merchant_id.clone();
let refund_id = router_data.refund_id.clone();
let dispute_id = router_data.dispute_id.clone();
let grpc_header = grpc_header_builder.build();
// Log the actual gRPC request with masking
let grpc_request_body = masking::masked_serialize(&grpc_request)
.unwrap_or_else(|_| serde_json::json!({"error": "failed_to_serialize_grpc_request"}));
// Update connector call count metrics for UCS operations
crate::routes::metrics::CONNECTOR_CALL_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector_name.clone()),
(
"flow",
std::any::type_name::<T>()
.split("::")
.last()
.unwrap_or_default()
),
),
);
// Execute UCS function and measure timing
let start_time = Instant::now();
let result = handler(router_data, grpc_request, grpc_header).await;
let external_latency = start_time.elapsed().as_millis();
// Create and emit connector event after UCS call
let (status_code, response_body, router_result) = match result {
Ok((updated_router_data, grpc_response)) => {
let status = updated_router_data
.connector_http_status_code
.unwrap_or(200);
// Log the actual gRPC response
let grpc_response_body = serde_json::to_value(&grpc_response).unwrap_or_else(
|_| serde_json::json!({"error": "failed_to_serialize_grpc_response"}),
);
(status, Some(grpc_response_body), Ok(updated_router_data))
}
Err(error) => {
// Update error metrics for UCS calls
crate::routes::metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
1,
router_env::metric_attributes!(("connector", connector_name.clone(),)),
);
let error_body = serde_json::json!({
"error": error.to_string(),
"error_type": "ucs_call_failed"
});
(500, Some(error_body), Err(error))
}
};
let mut connector_event = ConnectorEvent::new(
state.tenant.tenant_id.clone(),
connector_name,
std::any::type_name::<T>(),
grpc_request_body,
"grpc://unified-connector-service".to_string(),
Method::Post,
payment_id,
merchant_id,
state.request_id.as_ref(),
external_latency,
refund_id,
dispute_id,
status_code,
);
// Set response body based on status code
if let Some(body) = response_body {
match status_code {
400..=599 => {
connector_event.set_error_response_body(&body);
}
_ => {
connector_event.set_response_body(&body);
}
}
}
// Emit event
state.event_handler.log_event(&connector_event);
router_result
}
#[derive(serde::Serialize)]
pub struct ComparisonData {
pub hyperswitch_data: Secret<serde_json::Value>,
pub unified_connector_service_data: Secret<serde_json::Value>,
}
/// Sends router data comparison to external service
pub async fn send_comparison_data(
state: &SessionState,
comparison_data: ComparisonData,
) -> RouterResult<()> {
// Check if comparison service is enabled
let comparison_config = match state.conf.comparison_service.as_ref() {
Some(comparison_config) => comparison_config,
None => {
tracing::warn!(
"Comparison service configuration missing, skipping comparison data send"
);
return Ok(());
}
};
let mut request = RequestBuilder::new()
.method(Method::Post)
.url(comparison_config.url.get_string_repr())
.header(CONTENT_TYPE, "application/json")
.header(X_FLOW_NAME, "router-data")
.set_body(RequestContent::Json(Box::new(comparison_data)))
.build();
if let Some(req_id) = &state.request_id {
request.add_header(X_REQUEST_ID, masking::Maskable::Normal(req_id.to_string()));
}
let _ = http_client::send_request(&state.conf.proxy, request, comparison_config.timeout_secs)
.await
.map_err(|e| {
tracing::debug!("Error sending comparison data: {:?}", e);
});
Ok(())
}
| crates/router/src/core/unified_connector_service.rs | router::src::core::unified_connector_service | 8,748 | true |
// File: crates/router/src/core/external_service_auth.rs
// Module: router::src::core::external_service_auth
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,
},
))
}
| crates/router/src/core/external_service_auth.rs | router::src::core::external_service_auth | 687 | true |
// File: crates/router/src/core/verify_connector.rs
// Module: router::src::core::verify_connector
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()),
}
}
| crates/router/src/core/verify_connector.rs | router::src::core::verify_connector | 430 | true |
// File: crates/router/src/core/payment_link.rs
// Module: router::src::core::payment_link
pub mod validator;
use std::collections::HashMap;
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,
merchant_context: domain::MerchantContext,
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,
merchant_context: domain::MerchantContext,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResult<(PaymentLink, PaymentLinkData, PaymentLinkConfig)> {
let db = &*state.store;
let key_manager_state = &state.into();
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&(state).into(),
&payment_id,
&merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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 = merchant_context
.get_merchant_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,
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(
key_manager_state,
merchant_context.get_merchant_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(),
merchant_context.get_merchant_account().storage_scheme,
)
.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(),
merchant_context.get_merchant_account().storage_scheme,
)
.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: merchant_context
.get_merchant_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(),
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,
merchant_context: domain::MerchantContext,
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, merchant_context, 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,
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,
merchant_context: domain::MerchantContext,
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, merchant_context, 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),
)))
}
}
}
/*
The get_js_script function is used to inject dynamic value to payment_link sdk, which is unique to every payment.
*/
fn get_js_script(payment_details: &PaymentLinkData) -> RouterResult<String> {
let payment_details_str = serde_json::to_string(payment_details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentLinkData")?;
let url_encoded_str = urlencoding::encode(&payment_details_str);
Ok(format!("window.__PAYMENT_DETAILS = '{url_encoded_str}';"))
}
fn camel_to_kebab(s: &str) -> String {
let mut result = String::new();
if s.is_empty() {
return result;
}
let chars: Vec<char> = s.chars().collect();
for (i, &ch) in chars.iter().enumerate() {
if ch.is_uppercase() {
let should_add_dash = i > 0
&& (chars.get(i - 1).map(|c| c.is_lowercase()).unwrap_or(false)
|| (i + 1 < chars.len()
&& chars.get(i + 1).map(|c| c.is_lowercase()).unwrap_or(false)
&& chars.get(i - 1).map(|c| c.is_uppercase()).unwrap_or(false)));
if should_add_dash {
result.push('-');
}
result.push(ch.to_ascii_lowercase());
} else {
result.push(ch);
}
}
result
}
fn generate_dynamic_css(
rules: &HashMap<String, HashMap<String, String>>,
) -> Result<String, errors::ApiErrorResponse> {
if rules.is_empty() {
return Ok(String::new());
}
let mut css_string = String::new();
css_string.push_str("/* Dynamically Injected UI Rules */\n");
for (selector, styles_map) in rules {
if selector.trim().is_empty() {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "CSS selector cannot be empty.".to_string(),
});
}
css_string.push_str(selector);
css_string.push_str(" {\n");
for (prop_camel_case, css_value) in styles_map {
let css_property = camel_to_kebab(prop_camel_case);
css_string.push_str(" ");
css_string.push_str(&css_property);
css_string.push_str(": ");
css_string.push_str(css_value);
css_string.push_str(";\n");
}
css_string.push_str("}\n");
}
Ok(css_string)
}
fn get_payment_link_css_script(
payment_link_config: &PaymentLinkConfig,
) -> Result<String, errors::ApiErrorResponse> {
let custom_rules_css_option = payment_link_config
.payment_link_ui_rules
.as_ref()
.map(generate_dynamic_css)
.transpose()?;
let color_scheme_css = get_color_scheme_css(payment_link_config);
if let Some(custom_rules_css) = custom_rules_css_option {
Ok(format!("{color_scheme_css}\n{custom_rules_css}"))
} else {
Ok(color_scheme_css)
}
}
fn get_color_scheme_css(payment_link_config: &PaymentLinkConfig) -> String {
let background_primary_color = payment_link_config
.background_colour
.clone()
.unwrap_or(payment_link_config.theme.clone());
format!(
":root {{
--primary-color: {background_primary_color};
}}"
)
}
fn get_meta_tags_html(payment_details: &api_models::payments::PaymentLinkDetails) -> String {
format!(
r#"<meta property="og:title" content="Payment request from {0}"/>
<meta property="og:description" content="{1}"/>"#,
payment_details.merchant_name.clone(),
payment_details
.merchant_description
.clone()
.unwrap_or_default()
)
}
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>,
merchant_name: String,
default_domain_name: String,
payment_link_config_id: Option<String>,
) -> Result<(PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>> {
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,
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),
(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,
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,
_merchant_context: domain::MerchantContext,
_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,
merchant_context: domain::MerchantContext,
merchant_id: common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
) -> RouterResponse<services::PaymentLinkFormData> {
let db = &*state.store;
let key_manager_state = &(&state).into();
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
&merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
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(),
merchant_context.get_merchant_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 = merchant_context
.get_merchant_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 {
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,
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 currency =
payment_intent
.currency
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "currency",
})?;
let required_conversion_type = StringMajorUnitForCore;
let amount = required_conversion_type
.convert(payment_attempt.get_total_amount(), currency)
.change_context(errors::ApiErrorResponse::AmountConversionFailed {
amount_type: "StringMajorUnit",
})?;
// converting first letter of merchant name to upperCase
let merchant_name = capitalize_first_char(&payment_link_config.seller_name);
let css_script = get_color_scheme_css(&payment_link_config);
let profile_id = payment_link
.profile_id
.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(
key_manager_state,
merchant_context.get_merchant_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 (unified_code, unified_message) = if let Some((code, message)) = payment_attempt
.unified_code
.as_ref()
.zip(payment_attempt.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(),
)
};
let unified_translated_message = helpers::get_unified_translation(
&state,
unified_code.to_owned(),
unified_message.to_owned(),
state.locale.clone(),
)
.await
.or(Some(unified_message));
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: PaymentLinkStatusWrap::IntentStatus(payment_intent.status),
error_code: payment_attempt.error_code,
error_message: payment_attempt.error_message,
redirect: true,
theme: payment_link_config.theme.clone(),
return_url,
locale: Some(state.locale.clone()),
transaction_details: payment_link_config.transaction_details,
unified_code: Some(unified_code),
unified_message: unified_translated_message,
capture_method: payment_attempt.capture_method,
setup_future_usage_applied: payment_attempt.setup_future_usage_applied,
};
let js_script = get_js_script(&PaymentLinkData::PaymentLinkStatusDetails(Box::new(
payment_details,
)))?;
let payment_link_status_data = services::PaymentLinkStatusData {
js_script,
css_script,
};
Ok(services::ApplicationResponse::PaymentLinkForm(Box::new(
services::api::PaymentLinkAction::PaymentLinkStatus(payment_link_status_data),
)))
}
| crates/router/src/core/payment_link.rs | router::src::core::payment_link | 8,051 | true |
// File: crates/router/src/core/recon.rs
// Module: router::src::core::recon
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 key_manager_state = &(&state).into();
let response = db
.update_merchant(
key_manager_state,
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,
auth: authentication::AuthenticationData,
req: recon_api::ReconUpdateMerchantRequest,
) -> RouterResponse<api_types::MerchantAccountResponse> {
let db = &*state.store;
let key_manager_state = &(&state).into();
let updated_merchant_account = storage::MerchantAccountUpdate::ReconUpdate {
recon_status: req.recon_status,
};
let merchant_id = auth.merchant_account.get_id().clone();
let updated_merchant_account = db
.update_merchant(
key_manager_state,
auth.merchant_account.clone(),
updated_merchant_account,
&auth.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: auth.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 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,
},
))
}
| crates/router/src/core/recon.rs | router::src::core::recon | 2,078 | true |
// File: crates/router/src/core/poll.rs
// Module: router::src::core::poll
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,
merchant_context: domain::MerchantContext,
) -> 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(
merchant_context.get_merchant_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))
}
| crates/router/src/core/poll.rs | router::src::core::poll | 412 | true |
// File: crates/router/src/core/webhooks.rs
// Module: router::src::core::webhooks
#[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";
| crates/router/src/core/webhooks.rs | router::src::core::webhooks | 242 | true |
// File: crates/router/src/core/api_keys.rs
// Module: router::src::core::api_keys
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)
.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>,
) -> 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,
)
.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)
.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 {
#![allow(clippy::expect_used, clippy::unwrap_used)]
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)
}
}
| crates/router/src/core/api_keys.rs | router::src::core::api_keys | 4,702 | true |
// File: crates/router/src/core/errors.rs
// Module: router::src::core::errors
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,
}
#[cfg(feature = "detailed_errors")]
pub mod error_stack_parsing {
#[derive(serde::Deserialize)]
pub struct NestedErrorStack<'a> {
context: std::borrow::Cow<'a, str>,
attachments: Vec<std::borrow::Cow<'a, str>>,
sources: Vec<NestedErrorStack<'a>>,
}
#[derive(serde::Serialize, Debug)]
struct LinearErrorStack<'a> {
context: std::borrow::Cow<'a, str>,
#[serde(skip_serializing_if = "Vec::is_empty")]
attachments: Vec<std::borrow::Cow<'a, str>>,
}
#[derive(serde::Serialize, Debug)]
pub struct VecLinearErrorStack<'a>(Vec<LinearErrorStack<'a>>);
impl<'a> From<Vec<NestedErrorStack<'a>>> for VecLinearErrorStack<'a> {
fn from(value: Vec<NestedErrorStack<'a>>) -> Self {
let multi_layered_errors: Vec<_> = value
.into_iter()
.flat_map(|current_error| {
[LinearErrorStack {
context: current_error.context,
attachments: current_error.attachments,
}]
.into_iter()
.chain(Into::<VecLinearErrorStack<'a>>::into(current_error.sources).0)
})
.collect();
Self(multi_layered_errors)
}
}
}
#[cfg(feature = "detailed_errors")]
pub use error_stack_parsing::*;
#[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,
}
| crates/router/src/core/errors.rs | router::src::core::errors | 4,164 | true |
// File: crates/router/src/core/customers.rs
// Module: router::src::core::customers
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},
utils::{
self,
customer_validation::{CUSTOMER_LIST_LOWER_LIMIT, CUSTOMER_LIST_UPPER_LIMIT},
},
},
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,
merchant_context: domain::MerchantContext,
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 = merchant_context.get_merchant_account().get_id();
let merchant_reference_id_customer = MerchantReferenceIdForCustomer {
merchant_reference_id: merchant_reference_id.as_ref(),
merchant_id,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
};
// 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,
&merchant_context,
key_manager_state,
&state,
)
.await?;
let customer = db
.insert_customer(
domain_customer,
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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>,
merchant_context: &'a domain::MerchantContext,
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>,
merchant_context: &'a domain::MerchantContext,
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 = merchant_context.get_merchant_account().get_id();
let key = merchant_context
.get_merchant_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: merchant_context.get_merchant_account().storage_scheme,
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
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(
merchant_context
.get_merchant_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,
})
}
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>,
merchant_context: &'a domain::MerchantContext,
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,
merchant_context.get_merchant_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,
merchant_context.get_merchant_key_store(),
shipping_address,
)
})
.await
.transpose()
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt default customer shipping address")?;
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let key = merchant_context
.get_merchant_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(
merchant_context
.get_merchant_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,
})
}
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,
key_manager_state: &'a KeyManagerState,
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(self.key_manager_state, 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,
key_manager_state: &'a KeyManagerState,
}
#[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(
self.key_manager_state,
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(
self.key_manager_state,
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,
merchant_context: domain::MerchantContext,
_profile_id: Option<id_type::ProfileId>,
customer_id: id_type::CustomerId,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let response = db
.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
key_manager_state,
&customer_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(
key_manager_state,
address_id,
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
id: id_type::GlobalCustomerId,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let response = db
.find_customer_by_global_id(
key_manager_state,
&id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from(response),
))
}
#[instrument(skip(state))]
pub async fn list_customers(
state: SessionState,
merchant_id: id_type::MerchantId,
_profile_id_list: Option<Vec<id_type::ProfileId>>,
key_store: domain::MerchantKeyStore,
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(
&(&state).into(),
&merchant_id,
&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,
merchant_id: id_type::MerchantId,
_profile_id_list: Option<Vec<id_type::ProfileId>>,
key_store: domain::MerchantKeyStore,
request: customers::CustomerListRequestWithConstraints,
) -> errors::CustomerResponse<customers::CustomerListResponse> {
let db = state.store.as_ref();
let limit = utils::customer_validation::validate_customer_list_limit(request.limit)
.change_context(errors::CustomersErrorResponse::InvalidRequestData {
message: format!(
"limit should be between {CUSTOMER_LIST_LOWER_LIMIT} and {CUSTOMER_LIST_UPPER_LIMIT}"
),
})?;
let customer_list_constraints = crate::db::customers::CustomerListConstraints {
limit: request.limit.unwrap_or(limit),
offset: request.offset,
customer_id: request.customer_id,
time_range: request.time_range,
};
let domain_customers = db
.list_customers_by_merchant_id_with_count(
&(&state).into(),
&merchant_id,
&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,
merchant_context: domain::MerchantContext,
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,
&merchant_context,
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,
merchant_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let customer_orig = db
.find_customer_by_global_id(
key_manager_state,
self,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(
key_manager_state,
merchant_context.get_merchant_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,
merchant_context.get_merchant_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 = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let identifier = Identifier::Merchant(
merchant_context
.get_merchant_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),
}));
db.update_customer_by_global_id(
key_manager_state,
self,
customer_orig,
updated_customer,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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,
merchant_context: &'a domain::MerchantContext,
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,
merchant_context: domain::MerchantContext,
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,
&merchant_context,
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,
merchant_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
) -> errors::CustomerResponse<customers::CustomerDeleteResponse> {
let customer_orig = db
.find_customer_by_customer_id_merchant_id(
key_manager_state,
self,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
let customer_mandates = db
.find_mandate_by_merchant_id_customer_id(
merchant_context.get_merchant_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(
key_manager_state,
merchant_context.get_merchant_key_store(),
self,
merchant_context.get_merchant_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,
merchant_context,
}
.delete_card_from_locker(
self,
merchant_context.get_merchant_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,
merchant_context.get_merchant_account().get_id(),
pm.payment_method_id.clone(),
pm.network_token_locker_id,
network_token_ref_id,
merchant_context,
)
.await
.switch()?;
}
}
db.delete_payment_method_by_merchant_id_payment_method_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().get_id(),
&pm.payment_method_id,
)
.await
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable(
"failed to delete payment method while redacting customer details",
)?;
}
}
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 = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let identifier = Identifier::Merchant(
merchant_context
.get_merchant_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 update_address = storage::AddressUpdate::Update {
city: Some(REDACTED.to_string()),
country: None,
line1: Some(redacted_encrypted_value.clone()),
line2: Some(redacted_encrypted_value.clone()),
line3: Some(redacted_encrypted_value.clone()),
state: Some(redacted_encrypted_value.clone()),
zip: Some(redacted_encrypted_value.clone()),
first_name: Some(redacted_encrypted_value.clone()),
last_name: Some(redacted_encrypted_value.clone()),
phone_number: Some(redacted_encrypted_value.clone()),
country_code: Some(REDACTED.to_string()),
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
email: Some(redacted_encrypted_email),
origin_zip: Some(redacted_encrypted_value.clone()),
};
match db
.update_address_by_merchant_id_customer_id(
key_manager_state,
self,
merchant_context.get_merchant_account().get_id(),
update_address,
merchant_context.get_merchant_key_store(),
)
.await
{
Ok(_) => Ok(()),
Err(error) => {
if error.current_context().is_db_not_found() {
Ok(())
} else {
Err(error)
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("failed update_address_by_merchant_id_customer_id")
}
}
}?;
let updated_customer = storage::CustomerUpdate::Update {
name: Some(redacted_encrypted_value.clone()),
email: Some(
types::crypto_operation(
key_manager_state,
type_name!(storage::Customer),
types::CryptoOperation::Encrypt(REDACTED.to_string().into()),
identifier,
key,
)
.await
.and_then(|val| val.try_into_operation())
.switch()?,
),
phone: Box::new(Some(redacted_encrypted_value.clone())),
description: Some(Description::from_str_unchecked(REDACTED)),
phone_country_code: Some(REDACTED.to_string()),
metadata: Box::new(None),
connector_customer: Box::new(None),
address_id: None,
tax_registration_id: Some(redacted_encrypted_value.clone()),
};
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
self.clone(),
merchant_context.get_merchant_account().get_id().to_owned(),
customer_orig,
updated_customer,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
let response = customers::CustomerDeleteResponse {
customer_id: self.clone(),
customer_deleted: true,
address_deleted: true,
payment_methods_deleted: true,
};
metrics::CUSTOMER_REDACTED.add(1, &[]);
Ok(services::ApplicationResponse::Json(response))
}
}
#[instrument(skip(state))]
pub async fn update_customer(
state: SessionState,
merchant_context: domain::MerchantContext,
update_customer: customers::CustomerUpdateRequestInternal,
) -> errors::CustomerResponse<customers::CustomerResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
//Add this in update call if customer can be updated anywhere else
#[cfg(feature = "v1")]
let verify_id_for_update_customer = VerifyIdForUpdateCustomer {
merchant_reference_id: &update_customer.customer_id,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
};
#[cfg(feature = "v2")]
let verify_id_for_update_customer = VerifyIdForUpdateCustomer {
id: &update_customer.id,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
};
let customer = verify_id_for_update_customer
.verify_id_and_get_customer_object(db)
.await?;
let updated_customer = update_customer
.request
.create_domain_model_from_request(
&None,
db,
&merchant_context,
key_manager_state,
&state,
&customer,
)
.await?;
update_customer.request.generate_response(&updated_customer)
}
#[async_trait::async_trait]
trait CustomerUpdateBridge {
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_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
domain_customer: &'a domain::Customer,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse>;
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse>;
}
#[cfg(feature = "v1")]
struct AddressStructForDbUpdate<'a> {
update_customer: &'a customers::CustomerUpdateRequest,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
domain_customer: &'a domain::Customer,
}
#[cfg(feature = "v1")]
impl AddressStructForDbUpdate<'_> {
async fn update_address_if_sent(
&self,
db: &dyn StorageInterface,
) -> errors::CustomResult<Option<domain::Address>, errors::CustomersErrorResponse> {
let address = if let Some(addr) = &self.update_customer.address {
match self.domain_customer.address_id.clone() {
Some(address_id) => {
let customer_address: api_models::payments::AddressDetails = addr.clone();
let update_address = self
.update_customer
.get_address_update(
self.state,
customer_address,
self.key_store.key.get_inner().peek(),
self.merchant_account.storage_scheme,
self.merchant_account.get_id().clone(),
)
.await
.switch()
.attach_printable("Failed while encrypting Address while Update")?;
Some(
db.update_address(
self.key_manager_state,
address_id,
update_address,
self.key_store,
)
.await
.switch()
.attach_printable(format!(
"Failed while updating address: merchant_id: {:?}, customer_id: {:?}",
self.merchant_account.get_id(),
self.domain_customer.customer_id
))?,
)
}
None => {
let customer_address: api_models::payments::AddressDetails = addr.clone();
let address = self
.update_customer
.get_domain_address(
self.state,
customer_address,
self.merchant_account.get_id(),
&self.domain_customer.customer_id,
self.key_store.key.get_inner().peek(),
self.merchant_account.storage_scheme,
)
.await
.switch()
.attach_printable("Failed while encrypting address")?;
Some(
db.insert_address_for_customers(
self.key_manager_state,
address,
self.key_store,
)
.await
.switch()
.attach_printable("Failed while inserting new address")?,
)
}
}
} else {
match &self.domain_customer.address_id {
Some(address_id) => Some(
db.find_address_by_address_id(
self.key_manager_state,
address_id,
self.key_store,
)
.await
.switch()?,
),
None => None,
}
};
Ok(address)
}
}
#[cfg(feature = "v1")]
#[derive(Debug)]
struct VerifyIdForUpdateCustomer<'a> {
merchant_reference_id: &'a id_type::CustomerId,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
}
#[cfg(feature = "v2")]
#[derive(Debug)]
struct VerifyIdForUpdateCustomer<'a> {
id: &'a id_type::GlobalCustomerId,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
}
#[cfg(feature = "v1")]
impl VerifyIdForUpdateCustomer<'_> {
async fn verify_id_and_get_customer_object(
&self,
db: &dyn StorageInterface,
) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> {
let customer = db
.find_customer_by_customer_id_merchant_id(
self.key_manager_state,
self.merchant_reference_id,
self.merchant_account.get_id(),
self.key_store,
self.merchant_account.storage_scheme,
)
.await
.switch()?;
Ok(customer)
}
}
#[cfg(feature = "v2")]
impl VerifyIdForUpdateCustomer<'_> {
async fn verify_id_and_get_customer_object(
&self,
db: &dyn StorageInterface,
) -> Result<domain::Customer, error_stack::Report<errors::CustomersErrorResponse>> {
let customer = db
.find_customer_by_global_id(
self.key_manager_state,
self.id,
self.key_store,
self.merchant_account.storage_scheme,
)
.await
.switch()?;
Ok(customer)
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl CustomerUpdateBridge for customers::CustomerUpdateRequest {
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_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
domain_customer: &'a domain::Customer,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
let update_address_for_update_customer = AddressStructForDbUpdate {
update_customer: self,
merchant_account: merchant_context.get_merchant_account(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
state,
domain_customer,
};
let address = update_address_for_update_customer
.update_address_if_sent(db)
.await?;
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
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
.as_ref()
.map(|a| a.clone().expose().switch_strategy()),
phone: self.phone.clone(),
tax_registration_id: self.tax_registration_id.clone(),
},
),
),
Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.switch()?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
let response = db
.update_customer_by_customer_id_merchant_id(
key_manager_state,
domain_customer.customer_id.to_owned(),
merchant_context.get_merchant_account().get_id().to_owned(),
domain_customer.to_owned(),
storage::CustomerUpdate::Update {
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: Box::new(encryptable_customer.phone),
tax_registration_id: encryptable_customer.tax_registration_id,
phone_country_code: self.phone_country_code.clone(),
metadata: Box::new(self.metadata.clone()),
description: self.description.clone(),
connector_customer: Box::new(None),
address_id: address.clone().map(|addr| addr.address_id),
},
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
Ok(response)
}
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 CustomerUpdateBridge for customers::CustomerUpdateRequest {
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_context: &'a domain::MerchantContext,
key_manager_state: &'a KeyManagerState,
state: &'a SessionState,
domain_customer: &'a domain::Customer,
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
let default_billing_address = self.get_default_customer_billing_address();
let encrypted_customer_billing_address = default_billing_address
.async_map(|billing_address| {
create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
billing_address,
)
})
.await
.transpose()
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt default customer billing address")?;
let default_shipping_address = self.get_default_customer_shipping_address();
let encrypted_customer_shipping_address = default_shipping_address
.async_map(|shipping_address| {
create_encrypted_data(
key_manager_state,
merchant_context.get_merchant_key_store(),
shipping_address,
)
})
.await
.transpose()
.change_context(errors::CustomersErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt default customer shipping address")?;
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
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
.as_ref()
.map(|a| a.clone().expose().switch_strategy()),
phone: self.phone.clone(),
tax_registration_id: self.tax_registration_id.clone(),
},
),
),
Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.switch()?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::CustomersErrorResponse::InternalServerError)?;
let response = db
.update_customer_by_global_id(
key_manager_state,
&domain_customer.id,
domain_customer.to_owned(),
storage::CustomerUpdate::Update(Box::new(storage::CustomerGeneralUpdate {
name: encryptable_customer.name,
email: Box::new(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: Box::new(encryptable_customer.phone),
tax_registration_id: encryptable_customer.tax_registration_id,
phone_country_code: self.phone_country_code.clone(),
metadata: self.metadata.clone(),
description: self.description.clone(),
connector_customer: Box::new(None),
default_billing_address: encrypted_customer_billing_address.map(Into::into),
default_shipping_address: encrypted_customer_shipping_address.map(Into::into),
default_payment_method_id: Some(self.default_payment_method_id.clone()),
status: None,
})),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.switch()?;
Ok(response)
}
fn generate_response<'a>(
&'a self,
customer: &'a domain::Customer,
) -> errors::CustomerResponse<customers::CustomerResponse> {
Ok(services::ApplicationResponse::Json(
customers::CustomerResponse::foreign_from(customer.clone()),
))
}
}
pub async fn migrate_customers(
state: SessionState,
customers_migration: Vec<payment_methods_domain::PaymentMethodCustomerMigrate>,
merchant_context: domain::MerchantContext,
) -> errors::CustomerResponse<()> {
for customer_migration in customers_migration {
match create_customer(
state.clone(),
merchant_context.clone(),
customer_migration.customer,
customer_migration.connector_customer_details,
)
.await
{
Ok(_) => (),
Err(e) => match e.current_context() {
errors::CustomersErrorResponse::CustomerAlreadyExists => (),
_ => return Err(e),
},
}
}
Ok(services::ApplicationResponse::Json(()))
}
| crates/router/src/core/customers.rs | router::src::core::customers | 10,785 | true |
// File: crates/router/src/core/card_testing_guard.rs
// Module: router::src::core::card_testing_guard
pub mod utils;
use crate::core::errors;
| crates/router/src/core/card_testing_guard.rs | router::src::core::card_testing_guard | 36 | true |
// File: crates/router/src/core/gsm.rs
// Module: router::src::core::gsm
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,
} = 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)),
},
)
.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),
}
}
| crates/router/src/core/gsm.rs | router::src::core::gsm | 1,273 | true |
// File: crates/router/src/core/revenue_recovery.rs
// Module: router::src::core::revenue_recovery
pub mod api;
pub mod transformers;
pub mod types;
use std::marker::PhantomData;
use api_models::{
enums,
payments::{self as api_payments, PaymentsGetIntentRequest, PaymentsResponse},
process_tracker::revenue_recovery,
webhooks,
};
use common_utils::{
self,
errors::CustomResult,
ext_traits::{AsyncExt, OptionExt, ValueExt},
id_type,
};
use diesel_models::{enums as diesel_enum, process_tracker::business_status};
use error_stack::{self, report, ResultExt};
use hyperswitch_domain_models::{
merchant_context,
payments::{PaymentIntent, PaymentIntentData, PaymentStatusData},
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::RevenueRecoveryOutgoingWebhook,
},
db::StorageInterface,
logger,
routes::{app::ReqState, metrics, SessionState},
services::ApplicationResponse,
types::{
api as router_api_types, domain,
storage::{self, revenue_recovery as pcr},
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";
#[allow(clippy::too_many_arguments)]
pub async fn upsert_calculate_pcr_task(
billing_connector_account: &domain::MerchantConnectorAccount,
state: &SessionState,
merchant_context: &domain::MerchantContext,
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: merchant_context.get_merchant_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,
)
.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,
})
}
pub async fn perform_execute_payment(
state: &SessionState,
execute_task_process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
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.clone(),
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(),
})?
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "Failed to fetch token details from redis".to_string(),
})?;
logger::info!("Token fetched from redis success");
let card_info =
api_models::payments::AdditionalCardInfo::foreign_from(&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,
&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,
merchant_context,
revenue_recovery_payment_data,
&revenue_recovery_metadata,
&record_attempt_response.id,
))
.await?;
Box::pin(action.execute_payment_task_response_handler(
state,
payment_intent,
execute_task_process,
revenue_recovery_payment_data,
&mut revenue_recovery_metadata,
))
.await?;
}
Err(err) => {
logger::error!("Error while recording attempt: {:?}", err);
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Pending,
business_status: Some(String::from(
business_status::EXECUTE_WORKFLOW_REQUEUE,
)),
};
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
}
}
}
types::Decision::Psync(attempt_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::RevenueRecoveryPaymentsAttemptStatus =
attempt_status.foreign_into();
pcr_status
.update_pt_status_based_on_attempt_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,
)
.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: enums::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: id_type::GlobalPaymentId,
profile_id: id_type::ProfileId,
payment_attempt_id: id_type::GlobalAttemptId,
runner: storage::ProcessTrackerRunner,
revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,
) -> 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,
)
.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,
merchant_context: domain::MerchantContext,
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::RevenueRecoveryPaymentsAttemptStatus =
payment_attempt.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,
merchant_context,
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,
merchant_context: domain::MerchantContext,
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 merchant_context_from_revenue_recovery_payment_data =
domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
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,
&merchant_context_from_revenue_recovery_payment_data,
active_payment_attempt_id,
)
.await?;
// 2. Get best available token
let best_time_to_schedule =
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"
);
None
}
};
match best_time_to_schedule {
Some(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"
);
}
None => {
let scheduled_token = match storage::revenue_recovery_redis_operation::
RedisTokenManager::get_payment_processor_token_with_schedule_time(state, &connector_customer_id)
.await {
Ok(scheduled_token_opt) => scheduled_token_opt,
Err(e) => {
logger::error!(
error = ?e,
connector_customer_id = %connector_customer_id,
"Failed to get PSP token status"
);
None
}
};
match scheduled_token {
Some(scheduled_token) => {
// Update scheduled time to scheduled time + 15 minutes
// here scheduled_time is the wait time 15 minutes is a buffer time that we are adding
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"No token but time available, rescheduling for scheduled time + 15 mins"
);
update_calculate_job_schedule_time(
db,
process,
time::Duration::seconds(
state
.conf
.revenue_recovery
.recovery_timestamp
.job_schedule_buffer_time_in_seconds,
),
scheduled_token.scheduled_at,
&connector_customer_id,
)
.await?;
}
None => {
let hard_decline_flag = storage::revenue_recovery_redis_operation::
RedisTokenManager::are_all_tokens_hard_declined(
state,
&connector_customer_id
)
.await
.ok()
.unwrap_or(false);
match hard_decline_flag {
false => {
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"Hard decline flag is false, rescheduling for scheduled time + 15 mins"
);
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,
)
.await?;
}
true => {
// Finish calculate workflow with CALCULATE_WORKFLOW_FINISH
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"No token available, 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,
&merchant_context,
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,
) -> 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 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(process.clone().tracking_data),
business_status: Some(String::from(business_status::PENDING)),
status: Some(common_enums::ProcessTrackerStatus::Pending),
updated_at: Some(common_utils::date_time::now()),
};
db.as_scheduler()
.update_process(process.clone(), pt_update)
.await
.map_err(|e| {
logger::error!(
process_id = %process.id,
error = ?e,
"Failed to reschedule CALCULATE_WORKFLOW"
);
sch_errors::ProcessTrackerError::ProcessUpdateFailed
})?;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
new_schedule_time = %new_schedule_time,
additional_time = ?additional_time,
"CALCULATE_WORKFLOW rescheduled successfully"
);
Ok(())
}
/// Insert Execute PCR Task to Process Tracker
#[allow(clippy::too_many_arguments)]
async fn insert_execute_pcr_task_to_pt(
billing_mca_id: &id_type::MerchantConnectorAccountId,
state: &SessionState,
merchant_id: &id_type::MerchantId,
payment_intent: &PaymentIntent,
profile_id: &id_type::ProfileId,
payment_attempt_id: &id_type::GlobalAttemptId,
runner: storage::ProcessTrackerRunner,
revenue_recovery_retry: diesel_enum::RevenueRecoveryAlgorithmType,
schedule_time: time::PrimitiveDateTime,
) -> Result<storage::ProcessTracker, sch_errors::ProcessTrackerError> {
let task = "EXECUTE_WORKFLOW";
let payment_id = payment_intent.id.clone();
let process_tracker_id = format!("{runner}_{task}_{}", payment_id.get_string_repr());
// Check if a process tracker entry already exists for this payment intent
let existing_entry = state
.store
.find_process_by_id(&process_tracker_id)
.await
.map_err(|e| {
logger::error!(
payment_id = %payment_id.get_string_repr(),
process_tracker_id = %process_tracker_id,
error = ?e,
"Failed to check for existing execute workflow process tracker entry"
);
sch_errors::ProcessTrackerError::ProcessUpdateFailed
})?;
match existing_entry {
Some(existing_process)
if existing_process.business_status == business_status::EXECUTE_WORKFLOW_FAILURE
|| existing_process.business_status
== business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC =>
{
// Entry exists with EXECUTE_WORKFLOW_COMPLETE status - update it
logger::info!(
payment_id = %payment_id.get_string_repr(),
process_tracker_id = %process_tracker_id,
current_retry_count = %existing_process.retry_count,
"Found existing EXECUTE_WORKFLOW task with COMPLETE status, updating to PENDING with incremented retry count"
);
let mut tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
serde_json::from_value(existing_process.tracking_data.clone())
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable(
"Failed to deserialize the tracking data from process tracker",
)?;
tracking_data.revenue_recovery_retry = revenue_recovery_retry;
let tracking_data_json = serde_json::to_value(&tracking_data)
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to serialize the tracking data to json")?;
let pt_update = storage::ProcessTrackerUpdate::Update {
name: Some(task.to_string()),
retry_count: Some(existing_process.clone().retry_count + 1),
schedule_time: Some(schedule_time),
tracking_data: Some(tracking_data_json),
business_status: Some(String::from(business_status::PENDING)),
status: Some(enums::ProcessTrackerStatus::Pending),
updated_at: Some(common_utils::date_time::now()),
};
let updated_process = state
.store
.update_process(existing_process, pt_update)
.await
.map_err(|e| {
logger::error!(
payment_id = %payment_id.get_string_repr(),
process_tracker_id = %process_tracker_id,
error = ?e,
"Failed to update existing execute workflow process tracker entry"
);
sch_errors::ProcessTrackerError::ProcessUpdateFailed
})?;
logger::info!(
payment_id = %payment_id.get_string_repr(),
process_tracker_id = %process_tracker_id,
new_retry_count = %updated_process.retry_count,
"Successfully updated existing EXECUTE_WORKFLOW task"
);
Ok(updated_process)
}
Some(existing_process) => {
// Entry exists but business status is not EXECUTE_WORKFLOW_COMPLETE
logger::info!(
payment_id = %payment_id.get_string_repr(),
process_tracker_id = %process_tracker_id,
current_business_status = %existing_process.business_status,
);
Ok(existing_process)
}
None => {
// No entry exists - create a new one
logger::info!(
payment_id = %payment_id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"No existing EXECUTE_WORKFLOW task found, creating new entry"
);
let execute_workflow_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
billing_mca_id: billing_mca_id.clone(),
global_payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
profile_id: profile_id.clone(),
payment_attempt_id: payment_attempt_id.clone(),
revenue_recovery_retry,
invoice_scheduled_time: Some(schedule_time),
};
let tag = ["PCR"];
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id.clone(),
task,
runner,
tag,
execute_workflow_tracking_data,
Some(1),
schedule_time,
common_types::consts::API_VERSION,
)
.map_err(|e| {
logger::error!(
payment_id = %payment_id.get_string_repr(),
error = ?e,
"Failed to construct execute workflow process tracker entry"
);
sch_errors::ProcessTrackerError::ProcessUpdateFailed
})?;
let response = state
.store
.insert_process(process_tracker_entry)
.await
.map_err(|e| {
logger::error!(
payment_id = %payment_id.get_string_repr(),
error = ?e,
"Failed to insert execute workflow process tracker entry"
);
sch_errors::ProcessTrackerError::ProcessUpdateFailed
})?;
metrics::TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", "RevenueRecoveryExecute")),
);
logger::info!(
payment_id = %payment_id.get_string_repr(),
process_tracker_id = %response.id,
"Successfully created new EXECUTE_WORKFLOW task"
);
Ok(response)
}
}
}
pub async fn retrieve_revenue_recovery_process_tracker(
state: SessionState,
id: id_type::GlobalPaymentId,
) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> {
let db = &*state.store;
let task = EXECUTE_WORKFLOW;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_id = id.get_execute_revenue_recovery_id(task, runner);
let process_tracker = db
.find_process_by_id(&process_tracker_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("error retrieving the process tracker id")?
.get_required_value("Process Tracker")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Entry For the following id doesn't exists".to_owned(),
})?;
let tracking_data = process_tracker
.tracking_data
.clone()
.parse_value::<pcr::RevenueRecoveryWorkflowTrackingData>("PCRWorkflowTrackingData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize Pcr Workflow Tracking Data")?;
let psync_task = PSYNC_WORKFLOW;
let process_tracker_id_for_psync = tracking_data
.payment_attempt_id
.get_psync_revenue_recovery_id(psync_task, runner);
let process_tracker_for_psync = db
.find_process_by_id(&process_tracker_id_for_psync)
.await
.map_err(|e| {
logger::error!("Error while retrieving psync task : {:?}", e);
})
.ok()
.flatten();
let schedule_time_for_psync = process_tracker_for_psync.and_then(|pt| pt.schedule_time);
let response = revenue_recovery::RevenueRecoveryResponse {
id: process_tracker.id,
name: process_tracker.name,
schedule_time_for_payment: process_tracker.schedule_time,
schedule_time_for_psync,
status: process_tracker.status,
business_status: process_tracker.business_status,
};
Ok(ApplicationResponse::Json(response))
}
pub async fn resume_revenue_recovery_process_tracker(
state: SessionState,
id: id_type::GlobalPaymentId,
request_retrigger: revenue_recovery::RevenueRecoveryRetriggerRequest,
) -> RouterResponse<revenue_recovery::RevenueRecoveryResponse> {
let db = &*state.store;
let task = request_retrigger.revenue_recovery_task;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_id = id.get_execute_revenue_recovery_id(&task, runner);
let process_tracker = db
.find_process_by_id(&process_tracker_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("error retrieving the process tracker id")?
.get_required_value("Process Tracker")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Entry For the following id doesn't exists".to_owned(),
})?;
let tracking_data = process_tracker
.tracking_data
.clone()
.parse_value::<pcr::RevenueRecoveryWorkflowTrackingData>("PCRWorkflowTrackingData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize Pcr Workflow Tracking Data")?;
//Call payment intent to check the status
let request = PaymentsGetIntentRequest { id: id.clone() };
let revenue_recovery_payment_data =
revenue_recovery_workflow::extract_data_and_perform_action(&state, &tracking_data)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Failed to extract the revenue recovery data".to_owned(),
})?;
let merchant_context_from_revenue_recovery_payment_data =
domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
let create_intent_response = payments::payments_intent_core::<
router_api_types::PaymentGetIntent,
router_api_types::payments::PaymentsIntentResponse,
_,
_,
PaymentIntentData<router_api_types::PaymentGetIntent>,
>(
state.clone(),
state.get_req_state(),
merchant_context_from_revenue_recovery_payment_data,
revenue_recovery_payment_data.profile.clone(),
payments::operations::PaymentGetIntent,
request,
tracking_data.global_payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
.await?;
let response = create_intent_response
.get_json_body()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response from payments core")?;
match response.status {
enums::IntentStatus::Failed => {
let pt_update = storage::ProcessTrackerUpdate::Update {
name: process_tracker.name.clone(),
tracking_data: Some(process_tracker.tracking_data.clone()),
business_status: Some(request_retrigger.business_status.clone()),
status: Some(request_retrigger.status),
updated_at: Some(common_utils::date_time::now()),
retry_count: Some(process_tracker.retry_count + 1),
schedule_time: Some(request_retrigger.schedule_time.unwrap_or(
common_utils::date_time::now().saturating_add(time::Duration::seconds(600)),
)),
};
let updated_pt = db
.update_process(process_tracker, pt_update)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Failed to update the process tracker".to_owned(),
})?;
let response = revenue_recovery::RevenueRecoveryResponse {
id: updated_pt.id,
name: updated_pt.name,
schedule_time_for_payment: updated_pt.schedule_time,
schedule_time_for_psync: None,
status: updated_pt.status,
business_status: updated_pt.business_status,
};
Ok(ApplicationResponse::Json(response))
}
enums::IntentStatus::Succeeded
| enums::IntentStatus::Cancelled
| enums::IntentStatus::CancelledPostCapture
| enums::IntentStatus::Processing
| enums::IntentStatus::RequiresCustomerAction
| enums::IntentStatus::RequiresMerchantAction
| enums::IntentStatus::RequiresPaymentMethod
| enums::IntentStatus::RequiresConfirmation
| enums::IntentStatus::RequiresCapture
| enums::IntentStatus::PartiallyCaptured
| enums::IntentStatus::PartiallyCapturedAndCapturable
| enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| enums::IntentStatus::Conflicted
| enums::IntentStatus::Expired => Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Invalid Payment Status ".to_owned(),
})),
}
}
pub async fn get_payment_response_using_payment_get_operation(
state: &SessionState,
payment_intent_id: &id_type::GlobalPaymentId,
revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
merchant_context: &domain::MerchantContext,
active_payment_attempt_id: Option<&id_type::GlobalAttemptId>,
) -> Result<Option<ApplicationResponse<PaymentsResponse>>, sch_errors::ProcessTrackerError> {
match active_payment_attempt_id {
Some(_) => {
let payment_response = api::call_psync_api(
state,
payment_intent_id,
revenue_recovery_payment_data,
false,
false,
)
.await?;
let payments_response = payment_response.generate_response(
state,
None,
None,
None,
merchant_context,
&revenue_recovery_payment_data.profile,
None,
)?;
Ok(Some(payments_response))
}
None => Ok(None),
}
}
// This function can be implemented to reset the connector transmission and active attempt ID
// before pushing to the execute workflow.
pub async fn reset_connector_transmission_and_active_attempt_id_before_pushing_to_execute_workflow(
state: &SessionState,
payment_intent: &PaymentIntent,
revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
active_payment_attempt_id: Option<&id_type::GlobalAttemptId>,
) -> Result<Option<()>, sch_errors::ProcessTrackerError> {
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();
match active_payment_attempt_id {
Some(_) => {
// update the connector payment transmission field to Unsuccessful and unset active attempt id
revenue_recovery_metadata.set_payment_transmission_field_for_api_request(
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
);
let payment_update_req =
api_payments::PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
payment_intent
.feature_metadata
.clone()
.unwrap_or_default()
.convert_back()
.set_payment_revenue_recovery_metadata_using_api(
revenue_recovery_metadata.clone(),
),
enums::UpdateActiveAttempt::Unset,
);
logger::info!(
"Call made to payments update intent api , with the request body {:?}",
payment_update_req
);
api::update_payment_intent_api(
state,
payment_intent.id.clone(),
revenue_recovery_payment_data,
payment_update_req,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)?;
Ok(Some(()))
}
None => Ok(None),
}
}
| crates/router/src/core/revenue_recovery.rs | router::src::core::revenue_recovery | 8,975 | true |
// File: crates/router/src/core/currency.rs
// Module: router::src::core::currency
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;
}
}
}
}
| crates/router/src/core/currency.rs | router::src::core::currency | 722 | true |
// File: crates/router/src/core/gift_card.rs
// Module: router::src::core::gift_card
use std::marker::PhantomData;
#[cfg(feature = "v2")]
use api_models::payments::{GiftCardBalanceCheckResponse, PaymentsGiftCardBalanceCheckRequest};
use common_enums::CallConnectorAction;
#[cfg(feature = "v2")]
use common_utils::id_type;
use common_utils::types::MinorUnit;
use error_stack::ResultExt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::HeaderPayload;
use hyperswitch_domain_models::{
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 crate::db::errors::StorageErrorExt;
#[cfg(feature = "v2")]
use crate::{
core::{
errors::{self, RouterResponse},
payments::helpers,
},
routes::{app::ReqState, SessionState},
services,
types::{api, domain},
};
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn payments_check_gift_card_balance_core(
state: SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
_req_state: ReqState,
req: PaymentsGiftCardBalanceCheckRequest,
_header_payload: HeaderPayload,
payment_id: id_type::GlobalPaymentId,
) -> RouterResponse<GiftCardBalanceCheckResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
&payment_id,
merchant_context.get_merchant_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,
merchant_context.get_merchant_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 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(
req.gift_card_data.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 remaining_amount =
if (payment_intent.amount_details.order_amount - balance).is_greater_than(0) {
payment_intent.amount_details.order_amount - balance
} else {
MinorUnit::zero()
};
let needs_additional_pm_data = remaining_amount.is_greater_than(0);
let resp = GiftCardBalanceCheckResponse {
payment_id: payment_intent.id.clone(),
balance,
currency,
needs_additional_pm_data,
remaining_amount,
};
Ok(services::ApplicationResponse::Json(resp))
}
| crates/router/src/core/gift_card.rs | router::src::core::gift_card | 1,399 | true |
// File: crates/router/src/core/profile_acquirer.rs
// Module: router::src::core::profile_acquirer
use api_models::profile_acquirer;
use common_utils::types::keymanager::KeyManagerState;
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,
merchant_context: domain::MerchantContext,
) -> RouterResponse<profile_acquirer::ProfileAcquirerResponse> {
let db = state.store.as_ref();
let profile_acquirer_id = common_utils::generate_profile_acquirer_id_of_default_length();
let key_manager_state: KeyManagerState = (&state).into();
let merchant_key_store = merchant_context.get_merchant_key_store();
let mut business_profile = db
.find_business_profile_by_profile_id(
&key_manager_state,
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(
&key_manager_state,
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,
merchant_context: domain::MerchantContext,
) -> RouterResponse<profile_acquirer::ProfileAcquirerResponse> {
let db = state.store.as_ref();
let key_manager_state = (&state).into();
let merchant_key_store = merchant_context.get_merchant_key_store();
let mut business_profile = db
.find_business_profile_by_profile_id(&key_manager_state, 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(
&key_manager_state,
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))
}
| crates/router/src/core/profile_acquirer.rs | router::src::core::profile_acquirer | 1,740 | true |
// File: crates/router/src/core/debit_routing.rs
// Module: router::src::core::debit_routing
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, types::keymanager::KeyManagerState,
};
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 key_manager_state = &(state).into();
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(
key_manager_state,
&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()), 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 key_manager_state = &(state).into();
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(
key_manager_state,
&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 key_manager_state = &state.into();
let debit_routing_config = &state.conf.debit_routing_config;
let mcas_for_profile =
fetch_merchant_connector_accounts(state, key_manager_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,
key_manager_state: &KeyManagerState,
profile_id: &id_type::ProfileId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::ApiErrorResponse> {
state
.store
.list_enabled_connector_accounts_by_profile_id(
key_manager_state,
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)
}
| crates/router/src/core/debit_routing.rs | router::src::core::debit_routing | 5,671 | true |
// File: crates/router/src/core/authentication.rs
// Module: router::src::core::authentication
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 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},
storage,
},
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: storage::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,
shipping_address,
browser_details,
amount,
currency,
message_category,
device_channel,
merchant_connector_account,
authentication_data.clone(),
return_url,
sdk_information,
threeds_method_comp_ind,
email,
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 = utils::update_trackers(
state,
response.clone(),
authentication_data,
None,
merchant_key_store,
)
.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 (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,
)
.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?;
utils::update_trackers(state, router_data, authentication, None, key_store).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>,
) -> 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,
)
.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 updated_authentication = utils::update_trackers(
state,
router_data,
authentication,
acquirer_details.clone(),
key_store,
)
.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_update = utils::update_trackers(
state,
router_data,
authentication,
acquirer_details,
key_store,
)
.await?;
Ok(
hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
authentication: authentication_update,
cavv: None, // since cavv wont be present in pre_authentication step
},
)
}
| crates/router/src/core/authentication.rs | router::src::core::authentication | 2,007 | true |
// File: crates/router/src/core/routing.rs
// Module: router::src::core::routing
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, 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(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,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_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,
merchant_context,
&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,
merchant_context: domain::MerchantContext,
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 key_manager_state = &state.into();
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,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(profile_id),
merchant_context.get_merchant_account().get_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,
merchant_context: domain::MerchantContext,
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 key_manager_state = &(&state).into();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&request.profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let merchant_id = merchant_context.get_merchant_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(
key_manager_state,
merchant_id,
true,
merchant_context.get_merchant_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,
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
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 key_manager_state = &(&state).into();
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,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_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,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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.clone(),
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: merchant_context.get_merchant_account().get_id().to_owned(),
name: name.clone(),
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,
merchant_context: domain::MerchantContext,
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(
merchant_context.get_merchant_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,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_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,
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
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 key_manager_state = &(&state).into();
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
&algorithm_id,
merchant_context.get_merchant_account().get_id(),
)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&routing_algorithm.profile_id),
merchant_context.get_merchant_account().get_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
.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,
);
}
helpers::update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
business_profile.clone(),
dynamic_routing_ref,
)
.await?;
}
diesel_models::enums::RoutingAlgorithmKind::Single
| diesel_models::enums::RoutingAlgorithmKind::Priority
| diesel_models::enums::RoutingAlgorithmKind::Advanced
| diesel_models::enums::RoutingAlgorithmKind::VolumeSplit
| diesel_models::enums::RoutingAlgorithmKind::ThreeDsDecisionRule => {
let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile
.routing_algorithm
.clone()
.map(|val| val.parse_value("RoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize routing algorithm ref from business profile",
)?
.unwrap_or_default();
utils::when(routing_algorithm.algorithm_for != transaction_type, || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"Cannot use {}'s routing algorithm for {} operation",
routing_algorithm.algorithm_for, transaction_type
),
})
})?;
utils::when(
routing_ref.algorithm_id == Some(algorithm_id.clone()),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already active".to_string(),
})
},
)?;
routing_ref.update_algorithm_id(algorithm_id);
helpers::update_profile_active_algorithm_ref(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
business_profile.clone(),
routing_ref,
&transaction_type,
)
.await?;
}
};
if let Some(euclid_routing_id) = routing_algorithm.decision_engine_routing_id.clone() {
let routing_algo = ActivateRoutingConfigRequest {
created_by: business_profile.get_id().get_string_repr().to_string(),
routing_algorithm_id: euclid_routing_id,
};
let link_result = link_de_euclid_routing_algorithm(&state, routing_algo).await;
match link_result {
Ok(_) => {
router_env::logger::info!(
routing_flow=?"link_routing_algorithm",
is_equal=?true,
"decision_engine_euclid"
);
}
Err(e) => {
router_env::logger::info!(
routing_flow=?"link_routing_algorithm",
is_equal=?false,
error=?e,
"decision_engine_euclid"
);
}
}
}
// redact cgraph cache on rule activation
helpers::redact_cgraph_cache(
&state,
merchant_context.get_merchant_account().get_id(),
business_profile.get_id(),
)
.await?;
// redact routing cache on rule activation
helpers::redact_routing_cache(
&state,
merchant_context.get_merchant_account().get_id(),
business_profile.get_id(),
)
.await?;
metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_algorithm.foreign_into(),
))
}
#[cfg(feature = "v2")]
pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo(
merchant_context.get_merchant_account().get_id(),
&algorithm_id,
db,
)
.await?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&routing_algorithm.0.profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm.0)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse routing algorithm")?;
metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
}
#[cfg(feature = "v1")]
pub async fn retrieve_routing_algorithm_from_algorithm_id(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
algorithm_id: common_utils::id_type::RoutingId,
) -> RouterResponse<routing_types::MerchantRoutingAlgorithm> {
metrics::ROUTING_RETRIEVE_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
&algorithm_id,
merchant_context.get_merchant_account().get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&routing_algorithm.profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
let response = routing_types::MerchantRoutingAlgorithm::foreign_try_from(routing_algorithm)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse routing algorithm")?;
metrics::ROUTING_RETRIEVE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn unlink_routing_config_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UNLINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let routing_algo_id = match transaction_type {
enums::TransactionType::Payment => business_profile.routing_algorithm_id.clone(),
#[cfg(feature = "payouts")]
enums::TransactionType::Payout => business_profile.payout_routing_algorithm_id.clone(),
// TODO: Handle ThreeDsAuthentication Transaction Type for Three DS Decision Rule Algorithm configuration
enums::TransactionType::ThreeDsAuthentication => todo!(),
};
if let Some(algorithm_id) = routing_algo_id {
let record = RoutingAlgorithmUpdate::fetch_routing_algo(
merchant_context.get_merchant_account().get_id(),
&algorithm_id,
db,
)
.await?;
let response = record.0.foreign_into();
admin::ProfileWrapper::new(business_profile)
.update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
algorithm_id,
transaction_type,
)
.await?;
metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
} else {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?
}
}
#[cfg(feature = "v1")]
pub async fn unlink_routing_config(
state: SessionState,
merchant_context: domain::MerchantContext,
request: routing_types::RoutingConfigRequest,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UNLINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
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,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?;
match business_profile {
Some(business_profile) => {
core_utils::validate_profile_id_from_auth_layer(
authentication_profile_id,
&business_profile,
)?;
let routing_algo_ref: routing_types::RoutingAlgorithmRef = match transaction_type {
enums::TransactionType::Payment => business_profile.routing_algorithm.clone(),
#[cfg(feature = "payouts")]
enums::TransactionType::Payout => business_profile.payout_routing_algorithm.clone(),
enums::TransactionType::ThreeDsAuthentication => {
business_profile.three_ds_decision_rule_algorithm.clone()
}
}
.map(|val| val.parse_value("RoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize routing algorithm ref from merchant account")?
.unwrap_or_default();
let timestamp = common_utils::date_time::now_unix_timestamp();
match routing_algo_ref.algorithm_id {
Some(algorithm_id) => {
let routing_algorithm: routing_types::RoutingAlgorithmRef =
routing_types::RoutingAlgorithmRef {
algorithm_id: None,
timestamp,
config_algo_id: routing_algo_ref.config_algo_id.clone(),
surcharge_config_algo_id: routing_algo_ref.surcharge_config_algo_id,
};
let record = db
.find_routing_algorithm_by_profile_id_algorithm_id(
&profile_id,
&algorithm_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let response = record.foreign_into();
helpers::update_profile_active_algorithm_ref(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
business_profile.clone(),
routing_algorithm,
&transaction_type,
)
.await?;
// redact cgraph cache on rule activation
helpers::redact_cgraph_cache(
&state,
merchant_context.get_merchant_account().get_id(),
business_profile.get_id(),
)
.await?;
// redact routing cache on rule activation
helpers::redact_routing_cache(
&state,
merchant_context.get_merchant_account().get_id(),
business_profile.get_id(),
)
.await?;
metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
}
None => Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?,
}
}
None => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "The business_profile is not present".to_string(),
}
.into()),
}
}
#[cfg(feature = "v2")]
pub async fn update_default_fallback_routing(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
updated_list_of_connectors: Vec<routing_types::RoutableConnectorChoice>,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_UPDATE_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let profile_wrapper = admin::ProfileWrapper::new(profile);
let default_list_of_connectors =
profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;
utils::when(
default_list_of_connectors.len() != updated_list_of_connectors.len(),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "current config and updated config have different lengths".to_string(),
})
},
)?;
let existing_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter(
default_list_of_connectors
.iter()
.map(|conn_choice| conn_choice.to_string()),
);
let updated_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter(
updated_list_of_connectors
.iter()
.map(|conn_choice| conn_choice.to_string()),
);
let symmetric_diff_between_existing_and_updated_connectors: Vec<String> =
existing_set_of_default_connectors
.symmetric_difference(&updated_set_of_default_connectors)
.cloned()
.collect();
utils::when(
!symmetric_diff_between_existing_and_updated_connectors.is_empty(),
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector mismatch between old and new configs ({})",
symmetric_diff_between_existing_and_updated_connectors.join(", ")
),
})
},
)?;
profile_wrapper
.update_default_fallback_routing_of_connectors_under_profile(
db,
&updated_list_of_connectors,
key_manager_state,
merchant_context.get_merchant_key_store(),
)
.await?;
metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
updated_list_of_connectors,
))
}
#[cfg(feature = "v1")]
pub async fn update_default_routing_config(
state: SessionState,
merchant_context: domain::MerchantContext,
updated_config: Vec<routing_types::RoutableConnectorChoice>,
transaction_type: &enums::TransactionType,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_UPDATE_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let default_config = helpers::get_merchant_default_config(
db,
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
transaction_type,
)
.await?;
utils::when(default_config.len() != updated_config.len(), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "current config and updated config have different lengths".to_string(),
})
})?;
let existing_set: FxHashSet<String> =
FxHashSet::from_iter(default_config.iter().map(|c| c.to_string()));
let updated_set: FxHashSet<String> =
FxHashSet::from_iter(updated_config.iter().map(|c| c.to_string()));
let symmetric_diff: Vec<String> = existing_set
.symmetric_difference(&updated_set)
.cloned()
.collect();
utils::when(!symmetric_diff.is_empty(), || {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector mismatch between old and new configs ({})",
symmetric_diff.join(", ")
),
})
})?;
helpers::update_merchant_default_config(
db,
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
updated_config.clone(),
transaction_type,
)
.await?;
metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(updated_config))
}
#[cfg(feature = "v2")]
pub async fn retrieve_default_fallback_algorithm_for_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let connectors_choice = admin::ProfileWrapper::new(profile)
.get_default_fallback_list_of_connector_under_profile()?;
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(connectors_choice))
}
#[cfg(feature = "v1")]
pub async fn retrieve_default_routing_config(
state: SessionState,
profile_id: Option<common_utils::id_type::ProfileId>,
merchant_context: domain::MerchantContext,
transaction_type: &enums::TransactionType,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let id = profile_id
.map(|profile_id| profile_id.get_string_repr().to_owned())
.unwrap_or_else(|| {
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr()
.to_string()
});
helpers::get_merchant_default_config(db, &id, transaction_type)
.await
.map(|conn_choice| {
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
service_api::ApplicationResponse::Json(conn_choice)
})
}
#[cfg(feature = "v2")]
pub async fn retrieve_routing_config_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
query_params: RoutingRetrieveQuery,
profile_id: common_utils::id_type::ProfileId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> {
metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let record = db
.list_routing_algorithm_metadata_by_profile_id(
business_profile.get_id(),
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 active_algorithms = record
.into_iter()
.filter(|routing_rec| &routing_rec.algorithm_for == transaction_type)
.map(|routing_algo| routing_algo.foreign_into())
.collect::<Vec<_>>();
metrics::ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms),
))
}
#[cfg(feature = "v1")]
pub async fn retrieve_linked_routing_config(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
query_params: routing_types::RoutingRetrieveLinkQuery,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> {
metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_key_store = merchant_context.get_merchant_key_store();
let merchant_id = merchant_context.get_merchant_account().get_id();
// Get business profiles
let business_profiles = if let Some(profile_id) = query_params.profile_id {
core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_key_store,
Some(&profile_id),
merchant_id,
)
.await?
.map(|profile| vec![profile])
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?
} else {
let business_profile = db
.list_profile_by_merchant_id(key_manager_state, merchant_key_store, merchant_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
core_utils::filter_objects_based_on_profile_id_list(
authentication_profile_id.map(|profile_id| vec![profile_id]),
business_profile,
)
};
let mut active_algorithms = Vec::new();
for business_profile in business_profiles {
let profile_id = business_profile.get_id();
// Handle static routing algorithm
let routing_ref: routing_types::RoutingAlgorithmRef = match transaction_type {
enums::TransactionType::Payment => &business_profile.routing_algorithm,
#[cfg(feature = "payouts")]
enums::TransactionType::Payout => &business_profile.payout_routing_algorithm,
enums::TransactionType::ThreeDsAuthentication => {
&business_profile.three_ds_decision_rule_algorithm
}
}
.clone()
.map(|val| val.parse_value("RoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize routing algorithm ref from merchant account")?
.unwrap_or_default();
if let Some(algorithm_id) = routing_ref.algorithm_id {
let record = db
.find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&algorithm_id,
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let hs_records: Vec<routing_types::RoutingDictionaryRecord> =
vec![record.foreign_into()];
let de_records = retrieve_decision_engine_active_rules(
&state,
&transaction_type,
profile_id.clone(),
hs_records.clone(),
)
.await;
compare_and_log_result(
de_records.clone(),
hs_records.clone(),
"list_active_routing".to_string(),
);
active_algorithms.append(
&mut select_routing_result(&state, &business_profile, hs_records, de_records).await,
);
}
// Handle dynamic routing algorithms
let 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();
// Collect all dynamic algorithm IDs
let mut dynamic_algorithm_ids = Vec::new();
if let Some(sba) = &dynamic_routing_ref.success_based_algorithm {
if let Some(id) = &sba.algorithm_id_with_timestamp.algorithm_id {
dynamic_algorithm_ids.push(id.clone());
}
}
if let Some(era) = &dynamic_routing_ref.elimination_routing_algorithm {
if let Some(id) = &era.algorithm_id_with_timestamp.algorithm_id {
dynamic_algorithm_ids.push(id.clone());
}
}
if let Some(cbr) = &dynamic_routing_ref.contract_based_routing {
if let Some(id) = &cbr.algorithm_id_with_timestamp.algorithm_id {
dynamic_algorithm_ids.push(id.clone());
}
}
// Fetch all dynamic algorithms
for algorithm_id in dynamic_algorithm_ids {
let record = db
.find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&algorithm_id,
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
if record.algorithm_for == transaction_type {
active_algorithms.push(record.foreign_into());
}
}
}
metrics::ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms),
))
}
pub async fn retrieve_decision_engine_active_rules(
state: &SessionState,
transaction_type: &enums::TransactionType,
profile_id: common_utils::id_type::ProfileId,
hs_records: Vec<routing_types::RoutingDictionaryRecord>,
) -> Vec<routing_types::RoutingDictionaryRecord> {
let mut de_records =
list_de_euclid_active_routing_algorithm(state, profile_id.get_string_repr().to_owned())
.await
.map_err(|e| {
router_env::logger::error!(?e, "Failed to list DE Euclid active routing algorithm");
})
.ok() // Avoid throwing error if Decision Engine is not available or other errors thrown
.unwrap_or_default();
// Use Hs records to list the dynamic algorithms as DE is not supporting dynamic algorithms in HS standard
let mut dynamic_algos = hs_records
.into_iter()
.filter(|record| record.kind == routing_types::RoutingAlgorithmKind::Dynamic)
.collect::<Vec<_>>();
de_records.append(&mut dynamic_algos);
de_records
.into_iter()
.filter(|r| r.algorithm_for == Some(*transaction_type))
.collect::<Vec<_>>()
}
// List all the default fallback algorithms under all the profile under a merchant
pub async fn retrieve_default_routing_config_for_profiles(
state: SessionState,
merchant_context: domain::MerchantContext,
transaction_type: &enums::TransactionType,
) -> RouterResponse<Vec<routing_types::ProfileDefaultRoutingConfig>> {
metrics::ROUTING_RETRIEVE_CONFIG_FOR_PROFILE.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let all_profiles = db
.list_profile_by_merchant_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("error retrieving all business profiles for merchant")?;
let retrieve_config_futures = all_profiles
.iter()
.map(|prof| {
helpers::get_merchant_default_config(
db,
prof.get_id().get_string_repr(),
transaction_type,
)
})
.collect::<Vec<_>>();
let configs = futures::future::join_all(retrieve_config_futures)
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()?;
let default_configs = configs
.into_iter()
.zip(all_profiles.iter().map(|prof| prof.get_id().to_owned()))
.map(
|(config, profile_id)| routing_types::ProfileDefaultRoutingConfig {
profile_id,
connectors: config,
},
)
.collect::<Vec<_>>();
metrics::ROUTING_RETRIEVE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(default_configs))
}
pub async fn update_default_routing_config_for_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
updated_config: Vec<routing_types::RoutableConnectorChoice>,
profile_id: common_utils::id_type::ProfileId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::ProfileDefaultRoutingConfig> {
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let default_config = helpers::get_merchant_default_config(
db,
business_profile.get_id().get_string_repr(),
transaction_type,
)
.await?;
utils::when(default_config.len() != updated_config.len(), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "current config and updated config have different lengths".to_string(),
})
})?;
let existing_set = FxHashSet::from_iter(
default_config
.iter()
.map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())),
);
let updated_set = FxHashSet::from_iter(
updated_config
.iter()
.map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())),
);
let symmetric_diff = existing_set
.symmetric_difference(&updated_set)
.cloned()
.collect::<Vec<_>>();
utils::when(!symmetric_diff.is_empty(), || {
let error_str = symmetric_diff
.into_iter()
.map(|(connector, ident)| format!("'{connector}:{ident:?}'"))
.collect::<Vec<_>>()
.join(", ");
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("connector mismatch between old and new configs ({error_str})"),
})
})?;
helpers::update_merchant_default_config(
db,
business_profile.get_id().get_string_repr(),
updated_config.clone(),
transaction_type,
)
.await?;
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_types::ProfileDefaultRoutingConfig {
profile_id: business_profile.get_id().to_owned(),
connectors: updated_config,
},
))
}
// Toggle the specific routing type as well as add the default configs in RoutingAlgorithm table
// and update the same in business profile table.
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn toggle_specific_dynamic_routing(
state: SessionState,
merchant_context: domain::MerchantContext,
feature_to_enable: routing::DynamicRoutingFeatures,
profile_id: common_utils::id_type::ProfileId,
dynamic_routing_type: routing::DynamicRoutingType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
1,
router_env::metric_attributes!(
("profile_id", profile_id.clone()),
("algorithm_type", dynamic_routing_type.to_string())
),
);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let dynamic_routing_algo_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();
match feature_to_enable {
routing::DynamicRoutingFeatures::Metrics
| routing::DynamicRoutingFeatures::DynamicConnectorSelection => {
// occurs when algorithm is already present in the db
// 1. If present with same feature then return response as already enabled
// 2. Else update the feature and persist the same on db
// 3. If not present in db then create a new default entry
Box::pin(helpers::enable_dynamic_routing_algorithm(
&state,
merchant_context.get_merchant_key_store().clone(),
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
None,
))
.await
}
routing::DynamicRoutingFeatures::None => {
// disable specific dynamic routing for the requested profile
helpers::disable_dynamic_routing_algorithm(
&state,
merchant_context.get_merchant_key_store().clone(),
business_profile,
dynamic_routing_algo_ref,
dynamic_routing_type,
)
.await
}
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn create_specific_dynamic_routing(
state: SessionState,
merchant_context: domain::MerchantContext,
feature_to_enable: routing::DynamicRoutingFeatures,
profile_id: common_utils::id_type::ProfileId,
dynamic_routing_type: routing::DynamicRoutingType,
payload: routing_types::DynamicRoutingPayload,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
1,
router_env::metric_attributes!(
("profile_id", profile_id.clone()),
("algorithm_type", dynamic_routing_type.to_string())
),
);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let dynamic_routing_algo_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();
match feature_to_enable {
routing::DynamicRoutingFeatures::Metrics
| routing::DynamicRoutingFeatures::DynamicConnectorSelection => {
Box::pin(helpers::enable_dynamic_routing_algorithm(
&state,
merchant_context.get_merchant_key_store().clone(),
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
Some(payload),
))
.await
}
routing::DynamicRoutingFeatures::None => {
// disable specific dynamic routing for the requested profile
helpers::disable_dynamic_routing_algorithm(
&state,
merchant_context.get_merchant_key_store().clone(),
business_profile,
dynamic_routing_algo_ref,
dynamic_routing_type,
)
.await
}
}
}
#[cfg(feature = "v1")]
pub async fn configure_dynamic_routing_volume_split(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
routing_info: routing::RoutingVolumeSplit,
) -> RouterResponse<routing::RoutingVolumeSplit> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
utils::when(
routing_info.split > crate::consts::DYNAMIC_ROUTING_MAX_VOLUME,
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Dynamic routing volume split should be less than 100".to_string(),
})
},
)?;
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let mut dynamic_routing_algo_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();
dynamic_routing_algo_ref.update_volume_split(Some(routing_info.split));
helpers::update_business_profile_active_dynamic_algorithm_ref(
db,
&((&state).into()),
merchant_context.get_merchant_key_store(),
business_profile.clone(),
dynamic_routing_algo_ref.clone(),
)
.await?;
Ok(service_api::ApplicationResponse::Json(routing_info))
}
#[cfg(feature = "v1")]
pub async fn retrieve_dynamic_routing_volume_split(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<routing_types::RoutingVolumeSplitResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let dynamic_routing_algo_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();
let resp = routing_types::RoutingVolumeSplitResponse {
split: dynamic_routing_algo_ref
.dynamic_routing_volume_split
.unwrap_or_default(),
};
Ok(service_api::ApplicationResponse::Json(resp))
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn success_based_routing_update_configs(
state: SessionState,
request: routing_types::SuccessBasedRoutingConfig,
algorithm_id: common_utils::id_type::RoutingId,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(
1,
router_env::metric_attributes!(
("profile_id", profile_id.clone()),
(
"algorithm_type",
routing::DynamicRoutingType::SuccessRateBasedRouting.to_string()
)
),
);
let db = state.store.as_ref();
let dynamic_routing_algo_to_update = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let mut config_to_update: routing::SuccessBasedRoutingConfig = dynamic_routing_algo_to_update
.algorithm_data
.parse_value::<routing::SuccessBasedRoutingConfig>("SuccessBasedRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize algorithm data from routing table into SuccessBasedRoutingConfig")?;
config_to_update.update(request);
let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id: updated_algorithm_id,
profile_id: dynamic_routing_algo_to_update.profile_id,
merchant_id: dynamic_routing_algo_to_update.merchant_id,
name: dynamic_routing_algo_to_update.name,
description: dynamic_routing_algo_to_update.description,
kind: dynamic_routing_algo_to_update.kind,
algorithm_data: serde_json::json!(config_to_update.clone()),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: dynamic_routing_algo_to_update.algorithm_for,
decision_engine_routing_id: None,
};
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
// redact cache for success based routing configs
let cache_key = format!(
"{}_{}",
profile_id.get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact = vec![cache::CacheKind::SuccessBasedDynamicRoutingCache(
cache_key.into(),
)];
let _ = cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
cache_entries_to_redact,
)
.await
.map_err(|e| router_env::logger::error!("unable to publish into the redact channel for evicting the success based routing config cache {e:?}"));
let new_record = record.foreign_into();
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
if !state.conf.open_router.dynamic_routing_enabled {
state
.grpc_client
.dynamic_routing
.as_ref()
.async_map(|dr_client| async {
dr_client
.success_rate_client
.invalidate_success_rate_routing_keys(
profile_id.get_string_repr().into(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the routing keys")
})
.await
.transpose()?;
}
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn elimination_routing_update_configs(
state: SessionState,
request: routing_types::EliminationRoutingConfig,
algorithm_id: common_utils::id_type::RoutingId,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(
1,
router_env::metric_attributes!(
("profile_id", profile_id.clone()),
(
"algorithm_type",
routing::DynamicRoutingType::EliminationRouting.to_string()
)
),
);
let db = state.store.as_ref();
let dynamic_routing_algo_to_update = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let mut config_to_update: routing::EliminationRoutingConfig = dynamic_routing_algo_to_update
.algorithm_data
.parse_value::<routing::EliminationRoutingConfig>("EliminationRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize algorithm data from routing table into EliminationRoutingConfig",
)?;
config_to_update.update(request);
let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id: updated_algorithm_id,
profile_id: dynamic_routing_algo_to_update.profile_id,
merchant_id: dynamic_routing_algo_to_update.merchant_id,
name: dynamic_routing_algo_to_update.name,
description: dynamic_routing_algo_to_update.description,
kind: dynamic_routing_algo_to_update.kind,
algorithm_data: serde_json::json!(config_to_update),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: dynamic_routing_algo_to_update.algorithm_for,
decision_engine_routing_id: None,
};
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
// redact cache for elimination routing configs
let cache_key = format!(
"{}_{}",
profile_id.get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact = vec![cache::CacheKind::EliminationBasedDynamicRoutingCache(
cache_key.into(),
)];
cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
cache_entries_to_redact,
)
.await
.map_err(|e| router_env::logger::error!("unable to publish into the redact channel for evicting the elimination routing config cache {e:?}")).ok();
let new_record = record.foreign_into();
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
if !state.conf.open_router.dynamic_routing_enabled {
state
.grpc_client
.dynamic_routing
.as_ref()
.async_map(|dr_client| async {
dr_client
.elimination_based_client
.invalidate_elimination_bucket(
profile_id.get_string_repr().into(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the elimination routing keys")
})
.await
.transpose()?;
}
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn contract_based_dynamic_routing_setup(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
feature_to_enable: routing_types::DynamicRoutingFeatures,
config: Option<routing_types::ContractBasedRoutingConfig>,
) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let mut dynamic_routing_algo_ref: Option<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",
)
.ok()
.flatten();
utils::when(
dynamic_routing_algo_ref
.as_mut()
.and_then(|algo| {
algo.contract_based_routing.as_mut().map(|contract_algo| {
*contract_algo.get_enabled_features() == feature_to_enable
&& contract_algo
.clone()
.get_algorithm_id_with_timestamp()
.algorithm_id
.is_some()
})
})
.unwrap_or(false),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Contract Routing with specified features is already enabled".to_string(),
})
},
)?;
if feature_to_enable == routing::DynamicRoutingFeatures::None {
let algorithm = dynamic_routing_algo_ref
.clone()
.get_required_value("dynamic_routing_algo_ref")
.attach_printable("Failed to get dynamic_routing_algo_ref")?;
return helpers::disable_dynamic_routing_algorithm(
&state,
merchant_context.get_merchant_key_store().clone(),
business_profile,
algorithm,
routing_types::DynamicRoutingType::ContractBasedRouting,
)
.await;
}
let config = config
.get_required_value("ContractBasedRoutingConfig")
.attach_printable("Failed to get ContractBasedRoutingConfig from request")?;
let merchant_id = business_profile.merchant_id.clone();
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id: profile_id.clone(),
merchant_id,
name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),
description: None,
kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,
algorithm_data: serde_json::json!(config),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: common_enums::TransactionType::Payment,
decision_engine_routing_id: None,
};
// 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based
// 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up
let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref {
algo.update_algorithm_id(
algorithm_id,
feature_to_enable,
routing_types::DynamicRoutingType::ContractBasedRouting,
);
if feature_to_enable == routing::DynamicRoutingFeatures::DynamicConnectorSelection {
algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting);
}
algo
} else {
let contract_algo = routing_types::ContractRoutingAlgorithm {
algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp::new(Some(
algorithm_id.clone(),
)),
enabled_feature: feature_to_enable,
};
routing_types::DynamicRoutingAlgorithmRef {
success_based_algorithm: None,
elimination_routing_algorithm: None,
dynamic_routing_volume_split: None,
contract_based_routing: Some(contract_algo),
is_merchant_created_in_decision_engine: dynamic_routing_algo_ref
.as_ref()
.is_some_and(|algo| algo.is_merchant_created_in_decision_engine),
}
};
// validate the contained mca_ids
let mut contained_mca = Vec::new();
if let Some(info_vec) = &config.label_info {
for info in info_vec {
utils::when(
contained_mca.iter().any(|mca_id| mca_id == &info.mca_id),
|| {
Err(error_stack::Report::new(
errors::ApiErrorResponse::InvalidRequestData {
message: "Duplicate mca configuration received".to_string(),
},
))
},
)?;
contained_mca.push(info.mca_id.to_owned());
}
let validation_futures: Vec<_> = info_vec
.iter()
.map(|info| async {
let mca_id = info.mca_id.clone();
let label = info.label.clone();
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
&mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: mca_id.get_string_repr().to_owned(),
})?;
utils::when(mca.connector_name != label, || {
Err(error_stack::Report::new(
errors::ApiErrorResponse::InvalidRequestData {
message: "Incorrect mca configuration received".to_string(),
},
))
})?;
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(())
})
.collect();
futures::future::try_join_all(validation_futures).await?;
}
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
helpers::update_business_profile_active_dynamic_algorithm_ref(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
business_profile,
final_algorithm,
)
.await?;
let new_record = record.foreign_into();
metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_string())),
);
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn contract_based_routing_update_configs(
state: SessionState,
request: routing_types::ContractBasedRoutingConfig,
merchant_context: domain::MerchantContext,
algorithm_id: common_utils::id_type::RoutingId,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(
1,
router_env::metric_attributes!(
("profile_id", profile_id.get_string_repr().to_owned()),
(
"algorithm_type",
routing::DynamicRoutingType::ContractBasedRouting.to_string()
)
),
);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let dynamic_routing_algo_to_update = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update
.algorithm_data
.parse_value::<routing::ContractBasedRoutingConfig>("ContractBasedRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig")?;
// validate the contained mca_ids
let mut contained_mca = Vec::new();
if let Some(info_vec) = &request.label_info {
for info in info_vec {
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
&info.mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: info.mca_id.get_string_repr().to_owned(),
})?;
utils::when(mca.connector_name != info.label, || {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Incorrect mca configuration received".to_string(),
})
})?;
utils::when(
contained_mca.iter().any(|mca_id| mca_id == &info.mca_id),
|| {
Err(error_stack::Report::new(
errors::ApiErrorResponse::InvalidRequestData {
message: "Duplicate mca configuration received".to_string(),
},
))
},
)?;
contained_mca.push(info.mca_id.to_owned());
}
}
config_to_update.update(request);
let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id: updated_algorithm_id,
profile_id: dynamic_routing_algo_to_update.profile_id,
merchant_id: dynamic_routing_algo_to_update.merchant_id,
name: dynamic_routing_algo_to_update.name,
description: dynamic_routing_algo_to_update.description,
kind: dynamic_routing_algo_to_update.kind,
algorithm_data: serde_json::json!(config_to_update),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: dynamic_routing_algo_to_update.algorithm_for,
decision_engine_routing_id: None,
};
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
// redact cache for contract based routing configs
let cache_key = format!(
"{}_{}",
profile_id.get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache(
cache_key.into(),
)];
let _ = cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
cache_entries_to_redact,
)
.await
.map_err(|e| router_env::logger::error!("unable to publish into the redact channel for evicting the contract based routing config cache {e:?}"));
let new_record = record.foreign_into();
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.get_string_repr().to_owned())),
);
state
.grpc_client
.dynamic_routing
.as_ref()
.async_map(|dr_client| async {
dr_client
.contract_based_client
.invalidate_contracts(
profile_id.get_string_repr().into(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the contract based routing keys")
})
.await
.transpose()?;
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[async_trait]
pub trait GetRoutableConnectorsForChoice {
async fn get_routable_connectors(
&self,
db: &dyn StorageInterface,
business_profile: &domain::Profile,
) -> RouterResult<RoutableConnectors>;
}
pub struct StraightThroughAlgorithmTypeSingle(pub serde_json::Value);
#[async_trait]
impl GetRoutableConnectorsForChoice for StraightThroughAlgorithmTypeSingle {
async fn get_routable_connectors(
&self,
_db: &dyn StorageInterface,
_business_profile: &domain::Profile,
) -> RouterResult<RoutableConnectors> {
let straight_through_routing_algorithm = self
.0
.clone()
.parse_value::<api::routing::StraightThroughAlgorithm>("RoutingAlgorithm")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse the straight through routing algorithm")?;
let routable_connector = match straight_through_routing_algorithm {
api::routing::StraightThroughAlgorithm::Single(connector) => {
vec![*connector]
}
api::routing::StraightThroughAlgorithm::Priority(_)
| api::routing::StraightThroughAlgorithm::VolumeSplit(_) => {
Err(errors::RoutingError::DslIncorrectSelectionAlgorithm)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Unsupported algorithm received as a result of static routing",
)?
}
};
Ok(RoutableConnectors(routable_connector))
}
}
pub struct DecideConnector;
#[async_trait]
impl GetRoutableConnectorsForChoice for DecideConnector {
async fn get_routable_connectors(
&self,
db: &dyn StorageInterface,
business_profile: &domain::Profile,
) -> RouterResult<RoutableConnectors> {
let fallback_config = helpers::get_merchant_default_config(
db,
business_profile.get_id().get_string_repr(),
&common_enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(RoutableConnectors(fallback_config))
}
}
pub struct RoutableConnectors(Vec<routing_types::RoutableConnectorChoice>);
impl RoutableConnectors {
pub fn filter_network_transaction_id_flow_supported_connectors(
self,
nit_connectors: HashSet<String>,
) -> Self {
let connectors = self
.0
.into_iter()
.filter(|routable_connector_choice| {
nit_connectors.contains(&routable_connector_choice.connector.to_string())
})
.collect();
Self(connectors)
}
pub async fn construct_dsl_and_perform_eligibility_analysis<F, D>(
self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &D,
profile_id: &common_utils::id_type::ProfileId,
) -> RouterResult<Vec<api::ConnectorData>>
where
F: Send + Clone,
D: OperationSessionGetters<F>,
{
let payments_dsl_input = 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 routable_connector_choice = self.0.clone();
let backend_input = payments_routing::make_dsl_input(&payments_dsl_input)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct dsl input")?;
let connectors = payments_routing::perform_cgraph_filtering(
state,
key_store,
routable_connector_choice,
backend_input,
None,
profile_id,
&common_enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Eligibility analysis failed for routable connectors")?;
let connector_data = connectors
.into_iter()
.map(|conn| {
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&conn.connector.to_string(),
api::GetToken::Connector,
conn.merchant_connector_id.clone(),
)
})
.collect::<CustomResult<Vec<_>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
Ok(connector_data)
}
}
pub async fn migrate_rules_for_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
query_params: routing_types::RuleMigrationQuery,
) -> RouterResult<routing_types::RuleMigrationResult> {
use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm;
let profile_id = query_params.profile_id.clone();
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_key_store = merchant_context.get_merchant_key_store();
let merchant_id = merchant_context.get_merchant_account().get_id();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_key_store,
Some(&profile_id),
merchant_id,
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
#[cfg(feature = "v1")]
let active_payment_routing_ids: Vec<Option<common_utils::id_type::RoutingId>> = vec![
business_profile
.get_payment_routing_algorithm()
.attach_printable("Failed to get payment routing algorithm")?
.unwrap_or_default()
.algorithm_id,
business_profile
.get_payout_routing_algorithm()
.attach_printable("Failed to get payout routing algorithm")?
.unwrap_or_default()
.algorithm_id,
];
#[cfg(feature = "v2")]
let active_payment_routing_ids = [business_profile.routing_algorithm_id.clone()];
let routing_metadatas = state
.store
.list_routing_algorithm_metadata_by_profile_id(
&profile_id,
i64::from(query_params.validated_limit()),
i64::from(query_params.offset.unwrap_or_default()),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let mut response_list = Vec::new();
let mut error_list = Vec::new();
let mut push_error = |algorithm_id, msg: String| {
error_list.push(RuleMigrationError {
profile_id: profile_id.clone(),
algorithm_id,
error: msg,
});
};
for routing_metadata in routing_metadatas {
let algorithm_id = routing_metadata.algorithm_id.clone();
let algorithm = match db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
.await
{
Ok(algo) => algo,
Err(e) => {
router_env::logger::error!(?e, ?algorithm_id, "Failed to fetch routing algorithm");
push_error(algorithm_id, format!("Fetch error: {e:?}"));
continue;
}
};
let parsed_result = algorithm
.algorithm_data
.parse_value::<EuclidAlgorithm>("EuclidAlgorithm");
let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match parsed_result {
Ok(EuclidAlgorithm::Advanced(program)) => match program.try_into() {
Ok(ip) => Some(StaticRoutingAlgorithm::Advanced(ip)),
Err(e) => {
router_env::logger::error!(
?e,
?algorithm_id,
"Failed to convert advanced program"
);
push_error(algorithm_id.clone(), format!("Conversion error: {e:?}"));
None
}
},
Ok(EuclidAlgorithm::Single(conn)) => {
Some(StaticRoutingAlgorithm::Single(Box::new(conn.into())))
}
Ok(EuclidAlgorithm::Priority(connectors)) => Some(StaticRoutingAlgorithm::Priority(
connectors.into_iter().map(Into::into).collect(),
)),
Ok(EuclidAlgorithm::VolumeSplit(splits)) => Some(StaticRoutingAlgorithm::VolumeSplit(
splits.into_iter().map(Into::into).collect(),
)),
Ok(EuclidAlgorithm::ThreeDsDecisionRule(_)) => {
router_env::logger::info!(
?algorithm_id,
"Skipping 3DS rule migration (not supported yet)"
);
push_error(algorithm_id.clone(), "3DS migration not implemented".into());
None
}
Err(e) => {
router_env::logger::error!(?e, ?algorithm_id, "Failed to parse algorithm");
push_error(algorithm_id.clone(), format!("Parse error: {e:?}"));
None
}
};
let Some(static_algorithm) = maybe_static_algorithm else {
continue;
};
let routing_rule = RoutingRule {
rule_id: Some(algorithm.algorithm_id.clone().get_string_repr().to_string()),
name: algorithm.name.clone(),
description: algorithm.description.clone(),
created_by: profile_id.get_string_repr().to_string(),
algorithm: static_algorithm,
algorithm_for: algorithm.algorithm_for.into(),
metadata: Some(RoutingMetadata {
kind: algorithm.kind,
}),
};
match create_de_euclid_routing_algo(&state, &routing_rule).await {
Ok(decision_engine_routing_id) => {
let mut is_active_rule = false;
if active_payment_routing_ids.contains(&Some(algorithm.algorithm_id.clone())) {
link_de_euclid_routing_algorithm(
&state,
ActivateRoutingConfigRequest {
created_by: profile_id.get_string_repr().to_string(),
routing_algorithm_id: decision_engine_routing_id.clone(),
},
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to link active routing algorithm")?;
is_active_rule = true;
}
response_list.push(RuleMigrationResponse {
profile_id: profile_id.clone(),
euclid_algorithm_id: algorithm.algorithm_id.clone(),
decision_engine_algorithm_id: decision_engine_routing_id,
is_active_rule,
});
}
Err(err) => {
router_env::logger::error!(
decision_engine_rule_migration_error = ?err,
algorithm_id = ?algorithm.algorithm_id,
"Failed to insert into decision engine"
);
push_error(
algorithm.algorithm_id.clone(),
format!("Insertion error: {err:?}"),
);
}
}
}
Ok(routing_types::RuleMigrationResult {
success: response_list,
errors: error_list,
})
}
pub async fn decide_gateway_open_router(
state: SessionState,
req_body: OpenRouterDecideGatewayRequest,
) -> RouterResponse<DecideGatewayResponse> {
let response = if state.conf.open_router.dynamic_routing_enabled {
SRApiClient::send_decision_engine_request(
&state,
Method::Post,
"decide-gateway",
Some(req_body),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to perform decide gateway call with open router")?
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Dynamic routing is not enabled")?
};
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
pub async fn update_gateway_score_open_router(
state: SessionState,
req_body: UpdateScorePayload,
) -> RouterResponse<UpdateScoreResponse> {
let response = if state.conf.open_router.dynamic_routing_enabled {
SRApiClient::send_decision_engine_request(
&state,
Method::Post,
"update-gateway-score",
Some(req_body),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to perform update gateway score call with open router")?
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Dynamic routing is not enabled")?
};
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
| crates/router/src/core/routing.rs | router::src::core::routing | 21,228 | true |
// File: crates/router/src/core/surcharge_decision_config.rs
// Module: router::src::core::surcharge_decision_config
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,
merchant_context: domain::MerchantContext,
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 = merchant_context
.get_merchant_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 = merchant_context
.get_merchant_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 = merchant_context
.get_merchant_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,
merchant_context.get_merchant_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,
merchant_context.get_merchant_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,
_merchant_context: domain::MerchantContext,
_request: SurchargeDecisionConfigReq,
) -> RouterResponse<SurchargeDecisionManagerRecord> {
todo!();
}
#[cfg(feature = "v1")]
pub async fn delete_surcharge_decision_config(
state: SessionState,
merchant_context: domain::MerchantContext,
) -> 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 = merchant_context
.get_merchant_account()
.get_id()
.get_payment_method_surcharge_routing_id();
let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_context
.get_merchant_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 = merchant_context
.get_merchant_account()
.get_id()
.get_surcharge_dsk_key();
let config_key = cache::CacheKind::Surcharge(surcharge_cache_key.into());
update_merchant_active_algorithm_ref(
&state,
merchant_context.get_merchant_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,
_merchant_context: domain::MerchantContext,
) -> RouterResponse<()> {
todo!()
}
pub async fn retrieve_surcharge_decision_config(
state: SessionState,
merchant_context: domain::MerchantContext,
) -> RouterResponse<SurchargeDecisionManagerResponse> {
let db = state.store.as_ref();
let algorithm_id = merchant_context
.get_merchant_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))
}
| crates/router/src/core/surcharge_decision_config.rs | router::src::core::surcharge_decision_config | 1,849 | true |
// File: crates/router/src/core/health_check.rs
// Module: router::src::core::health_check
#[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_rs.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)
}
}
}
| crates/router/src/core/health_check.rs | router::src::core::health_check | 1,921 | true |
// File: crates/router/src/core/apple_pay_certificates_migration.rs
// Module: router::src::core::apple_pay_certificates_migration
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![];
let key_manager_state = &(&state).into();
for merchant_id in merchant_id_list {
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
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(
key_manager_state,
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,
},
))
}
| crates/router/src/core/apple_pay_certificates_migration.rs | router::src::core::apple_pay_certificates_migration | 861 | true |
// File: crates/router/src/core/three_ds_decision_rule.rs
// Module: router::src::core::three_ds_decision_rule
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::merchant_context::MerchantContext;
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,
merchant_context: MerchantContext,
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,
merchant_context.get_merchant_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,
}
| crates/router/src/core/three_ds_decision_rule.rs | router::src::core::three_ds_decision_rule | 715 | true |
// File: crates/router/src/core/relay.rs
// Module: router::src::core::relay
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,
merchant_context: domain::MerchantContext,
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,
merchant_context: domain::MerchantContext,
connector_account: domain::MerchantConnectorAccount,
relay_record: &relay::Relay,
) -> RouterResult<relay::RelayUpdate> {
let connector_id = &relay_record.connector_id;
let merchant_id = merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
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,
merchant_context,
profile_id_optional,
relay_flow_request,
)
.await
}
pub async fn relay<T: RelayInterface>(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_optional: Option<id_type::ProfileId>,
req: RelayRequestInner<T>,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_context.get_merchant_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(
key_manager_state,
merchant_context.get_merchant_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(
key_manager_state,
merchant_id,
connector_id,
merchant_context.get_merchant_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(
key_manager_state,
connector_id,
merchant_context.get_merchant_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(
key_manager_state,
merchant_context.get_merchant_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,
merchant_context.clone(),
connector_account,
&relay_record,
)
.await
.attach_printable("Failed to process relay")?;
let relay_update_record = db
.update_relay(
key_manager_state,
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
profile_id_optional: Option<id_type::ProfileId>,
req: relay_api_models::RelayRetrieveRequest,
) -> RouterResponse<relay_api_models::RelayResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_context.get_merchant_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(
key_manager_state,
merchant_context.get_merchant_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(
key_manager_state,
merchant_context.get_merchant_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(
key_manager_state,
merchant_id,
&relay_record.connector_id,
merchant_context.get_merchant_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(
key_manager_state,
&relay_record.connector_id,
merchant_context.get_merchant_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,
&merchant_context,
&relay_record,
connector_account,
)
.await?;
db.update_relay(
key_manager_state,
merchant_context.get_merchant_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,
merchant_context: &domain::MerchantContext,
relay_record: &relay::Relay,
connector_account: domain::MerchantConnectorAccount,
) -> RouterResult<relay::RelayUpdate> {
let connector_id = &relay_record.connector_id;
let merchant_id = merchant_context.get_merchant_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)
}
| crates/router/src/core/relay.rs | router::src::core::relay | 3,338 | true |
// File: crates/router/src/core/mandate.rs
// Module: router::src::core::mandate
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,
merchant_context: domain::MerchantContext,
req: mandates::MandateId,
) -> RouterResponse<mandates::MandateResponse> {
let mandate = state
.store
.as_ref()
.find_mandate_by_merchant_id_mandate_id(
merchant_context.get_merchant_account().get_id(),
&req.mandate_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
Ok(services::ApplicationResponse::Json(
mandates::MandateResponse::from_db_mandate(
&state,
merchant_context.get_merchant_key_store().clone(),
mandate,
merchant_context.get_merchant_account(),
)
.await?,
))
}
#[cfg(feature = "v1")]
#[instrument(skip(state))]
pub async fn revoke_mandate(
state: SessionState,
merchant_context: domain::MerchantContext,
req: mandates::MandateId,
) -> RouterResponse<mandates::MandateRevokedResponse> {
let db = state.store.as_ref();
let mandate = db
.find_mandate_by_merchant_id_mandate_id(
merchant_context.get_merchant_account().get_id(),
&req.mandate_id,
merchant_context.get_merchant_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, &merchant_context, mandate.clone())
.await?;
let merchant_connector_account = payment_helper::get_merchant_connector_account(
&state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_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,
&merchant_context,
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(
merchant_context.get_merchant_account().get_id(),
&req.mandate_id,
storage::MandateUpdate::StatusUpdate {
mandate_status: storage::enums::MandateStatus::Revoked,
},
mandate,
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
customer_id: id_type::CustomerId,
) -> RouterResponse<Vec<mandates::MandateResponse>> {
let mandates = state
.store
.find_mandate_by_merchant_id_customer_id(
merchant_context.get_merchant_account().get_id(),
&customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while finding mandate: merchant_id: {:?}, customer_id: {:?}",
merchant_context.get_merchant_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,
merchant_context.get_merchant_key_store().clone(),
mandate,
merchant_context.get_merchant_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,
merchant_context: domain::MerchantContext,
constraints: api_models::mandates::MandateListConstraints,
) -> RouterResponse<Vec<api_models::mandates::MandateResponse>> {
let mandates = state
.store
.as_ref()
.find_mandates_by_merchant_id(
merchant_context.get_merchant_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,
merchant_context.get_merchant_key_store().clone(),
mandate,
merchant_context.get_merchant_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>;
}
| crates/router/src/core/mandate.rs | router::src::core::mandate | 3,396 | true |
// File: crates/router/src/core/utils.rs
// Module: router::src::core::utils
pub mod customer_validation;
pub mod refunds_transformers;
pub mod refunds_validator;
use std::{collections::HashSet, marker::PhantomData, str::FromStr};
use api_models::enums::{Connector, DisputeStage, DisputeStatus};
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutVendorAccountDetails;
use common_enums::{IntentStatus, RequestIncrementalAuthorization};
#[cfg(feature = "payouts")]
use common_utils::{crypto::Encryptable, pii::Email};
use common_utils::{
errors::CustomResult,
ext_traits::AsyncExt,
types::{keymanager::KeyManagerState, ConnectorTransactionIdTrait, MinorUnit},
};
use diesel_models::refund as diesel_refund;
use error_stack::{report, ResultExt};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::types::VaultRouterData;
use hyperswitch_domain_models::{
merchant_connector_account::MerchantConnectorAccount,
payment_address::PaymentAddress,
router_data::ErrorResponse,
router_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,
_merchant_context: &domain::MerchantContext,
_payout_data: &mut PayoutData,
) -> RouterResult<types::PayoutsRouterData<F>> {
todo!()
}
#[cfg(all(feature = "payouts", feature = "v1"))]
#[instrument(skip_all)]
pub async fn construct_payout_router_data<'a, F>(
state: &SessionState,
connector_data: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
payout_data: &mut PayoutData,
) -> RouterResult<types::PayoutsRouterData<F>> {
let merchant_connector_account = payout_data
.merchant_connector_account
.clone()
.get_required_value("merchant_connector_account")?;
let connector_name = connector_data.connector_name;
let connector_auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let billing = payout_data.billing_address.to_owned();
let billing_address = billing.map(api_models::payments::Address::from);
let address = PaymentAddress::new(None, billing_address.map(From::from), None, None);
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let payouts = &payout_data.payouts;
let payout_attempt = &payout_data.payout_attempt;
let customer_details = &payout_data.customer_details;
let connector_label = format!(
"{}_{}",
payout_data.profile_id.get_string_repr(),
connector_name
);
let connector_customer_id = customer_details
.as_ref()
.and_then(|c| c.connector_customer.as_ref())
.and_then(|connector_customer_value| {
connector_customer_value
.clone()
.expose()
.get(connector_label)
.cloned()
})
.and_then(|id| serde_json::from_value::<String>(id).ok());
let vendor_details: Option<PayoutVendorAccountDetails> =
match api_models::enums::PayoutConnectors::try_from(connector_name.to_owned()).map_err(
|err| report!(errors::ApiErrorResponse::InternalServerError).attach_printable(err),
)? {
api_models::enums::PayoutConnectors::Stripe => {
payout_data.payouts.metadata.to_owned().and_then(|meta| {
let val = meta
.peek()
.to_owned()
.parse_value("PayoutVendorAccountDetails")
.ok();
val
})
}
_ => None,
};
let webhook_url = helpers::create_webhook_url(
&state.base_url,
&merchant_context.get_merchant_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: merchant_context.get_merchant_account().get_id().to_owned(),
customer_id: customer_details.to_owned().map(|c| c.customer_id),
tenant_id: state.tenant.tenant_id.clone(),
connector_customer: connector_customer_id,
connector: connector_name.to_string(),
payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("payout")
.get_string_repr()
.to_owned(),
attempt_id: "".to_string(),
status: enums::AttemptStatus::Failure,
payment_method: enums::PaymentMethod::default(),
payment_method_type: None,
connector_auth_type,
description: None,
address,
auth_type: enums::AuthenticationType::default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: None,
minor_amount_captured: None,
payment_method_status: None,
request: types::PayoutsData {
payout_id: payouts.payout_id.clone(),
amount: payouts.amount.get_amount_as_i64(),
minor_amount: payouts.amount,
connector_payout_id: payout_attempt.connector_payout_id.clone(),
destination_currency: payouts.destination_currency,
source_currency: payouts.source_currency,
entity_type: payouts.entity_type.to_owned(),
payout_type: payouts.payout_type,
vendor_details,
priority: payouts.priority,
customer_details: customer_details
.to_owned()
.map(|c| payments::CustomerDetails {
customer_id: Some(c.customer_id),
name: c.name.map(Encryptable::into_inner),
email: c.email.map(Email::from),
phone: c.phone.map(Encryptable::into_inner),
phone_country_code: c.phone_country_code,
tax_registration_id: c.tax_registration_id.map(Encryptable::into_inner),
}),
connector_transfer_method_id,
webhook_url: Some(webhook_url),
browser_info,
payout_connector_metadata: payout_attempt.payout_connector_metadata.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,
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,
merchant_context: &domain::MerchantContext,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
refund: &'a diesel_refund::Refund,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
) -> RouterResult<types::RefundsRouterData<F>> {
let auth_type = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let status = payment_attempt.status;
let payment_amount = payment_attempt.get_total_amount();
let currency = payment_intent.get_currency();
let payment_method_type = payment_attempt.payment_method_type;
let webhook_url = match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(
merchant_connector_account,
) => Some(helpers::create_webhook_url(
&state.base_url.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_connector_account.get_id().get_string_repr(),
)),
// TODO: Implement for connectors that require a webhook URL to be included in the request payload.
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,
};
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
.find_config_by_key(&format!("connector_api_version_{connector_enum}"))
.await
.map(|value| value.config)
.ok()
} else {
None
};
let browser_info = payment_attempt
.browser_info
.clone()
.map(types::BrowserInformation::from);
let connector_refund_id = refund.get_optional_connector_refund_id().cloned();
let capture_method = payment_intent.capture_method;
let customer_id = payment_intent
.get_optional_customer_id()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get optional customer id")?;
let braintree_metadata = payment_intent
.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: merchant_context.get_merchant_account().get_id().clone(),
customer_id,
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_enum.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.id.get_string_repr().to_string().clone(),
status,
payment_method: payment_method_type,
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,
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,
merchant_context: &domain::MerchantContext,
money: (MinorUnit, enums::Currency),
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
refund: &'a diesel_refund::Refund,
creds_identifier: Option<String>,
split_refunds: Option<router_request_types::SplitRefundsRequest>,
) -> RouterResult<types::RefundsRouterData<F>> {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?;
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
creds_identifier.as_deref(),
merchant_context.get_merchant_key_store(),
profile_id,
connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let status = payment_attempt.status;
let (payment_amount, currency) = money;
let payment_method = 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(),
merchant_context.get_merchant_account().get_id(),
merchant_connector_account_id_or_connector_name,
));
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_enum = Connector::from_str(connector_id)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_id:?}"))?;
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
.find_config_by_key(&format!("connector_api_version_{connector_id}"))
.await
.map(|value| value.config)
.ok()
} else {
None
};
let browser_info: Option<types::BrowserInformation> = payment_attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let connector_refund_id = refund.get_optional_connector_refund_id().cloned();
let capture_method = payment_attempt.capture_method;
let braintree_metadata = payment_intent
.connector_metadata
.clone()
.map(|cm| {
cm.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed parsing ConnectorMetadata")
})
.transpose()?
.and_then(|cm| cm.braintree);
let merchant_account_id = braintree_metadata
.as_ref()
.and_then(|braintree| braintree.merchant_account_id.clone());
let merchant_config_currency =
braintree_metadata.and_then(|braintree| braintree.merchant_config_currency);
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_attempt
.payment_method_data
.clone()
.and_then(|value| match serde_json::from_value(value) {
Ok(data) => Some(data),
Err(e) => {
router_env::logger::error!("Failed to deserialize payment_method_data: {}", e);
None
}
});
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id: payment_intent.customer_id.to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
status,
payment_method,
payment_method_type: 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,
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 {
#![allow(clippy::expect_used)]
use super::*;
#[test]
fn validate_id_length_constraint() {
let payment_id =
"abcdefghijlkmnopqrstuvwzyzabcdefghijknlmnopsjkdnfjsknfkjsdnfspoig".to_string(); //length = 65
let result = validate_id(payment_id, "payment_id");
assert!(result.is_err());
}
#[test]
fn validate_id_proper_response() {
let payment_id = "abcdefghijlkmnopqrstjhbjhjhkhbhgcxdfxvmhb".to_string();
let result = validate_id(payment_id.clone(), "payment_id");
assert!(result.is_ok());
let result = result.unwrap_or_default();
assert_eq!(result, payment_id);
}
#[test]
fn test_generate_id() {
let generated_id = generate_id(consts::ID_LENGTH, "ref");
assert_eq!(generated_id.len(), consts::ID_LENGTH + 4)
}
#[test]
fn test_filter_objects_based_on_profile_id_list() {
#[derive(PartialEq, Debug, Clone)]
struct Object {
profile_id: Option<common_utils::id_type::ProfileId>,
}
impl Object {
pub fn new(profile_id: &'static str) -> Self {
Self {
profile_id: Some(
common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(
profile_id,
))
.expect("invalid profile ID"),
),
}
}
}
impl GetProfileId for Object {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
self.profile_id.as_ref()
}
}
fn new_profile_id(profile_id: &'static str) -> common_utils::id_type::ProfileId {
common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(profile_id))
.expect("invalid profile ID")
}
// non empty object_list and profile_id_list
let object_list = vec![
Object::new("p1"),
Object::new("p2"),
Object::new("p2"),
Object::new("p4"),
Object::new("p5"),
];
let profile_id_list = vec![
new_profile_id("p1"),
new_profile_id("p2"),
new_profile_id("p3"),
];
let filtered_list =
filter_objects_based_on_profile_id_list(Some(profile_id_list), object_list.clone());
let expected_result = vec![Object::new("p1"), Object::new("p2"), Object::new("p2")];
assert_eq!(filtered_list, expected_result);
// non empty object_list and empty profile_id_list
let empty_profile_id_list = vec![];
let filtered_list = filter_objects_based_on_profile_id_list(
Some(empty_profile_id_list),
object_list.clone(),
);
let expected_result = vec![];
assert_eq!(filtered_list, expected_result);
// non empty object_list and None profile_id_list
let profile_id_list_as_none = None;
let filtered_list =
filter_objects_based_on_profile_id_list(profile_id_list_as_none, object_list);
let expected_result = vec![
Object::new("p1"),
Object::new("p2"),
Object::new("p2"),
Object::new("p4"),
Object::new("p5"),
];
assert_eq!(filtered_list, expected_result);
}
}
// Dispute Stage can move linearly from PreDispute -> Dispute -> PreArbitration -> Arbitration -> DisputeReversal
pub fn validate_dispute_stage(
prev_dispute_stage: DisputeStage,
dispute_stage: DisputeStage,
) -> bool {
match prev_dispute_stage {
DisputeStage::PreDispute => true,
DisputeStage::Dispute => !matches!(dispute_stage, DisputeStage::PreDispute),
DisputeStage::PreArbitration => matches!(
dispute_stage,
DisputeStage::PreArbitration
| DisputeStage::Arbitration
| DisputeStage::DisputeReversal
),
DisputeStage::Arbitration => matches!(
dispute_stage,
DisputeStage::Arbitration | DisputeStage::DisputeReversal
),
DisputeStage::DisputeReversal => matches!(dispute_stage, DisputeStage::DisputeReversal),
}
}
//Dispute status can go from Opened -> (Expired | Accepted | Cancelled | Challenged -> (Won | Lost))
pub fn validate_dispute_status(
prev_dispute_status: DisputeStatus,
dispute_status: DisputeStatus,
) -> bool {
match prev_dispute_status {
DisputeStatus::DisputeOpened => true,
DisputeStatus::DisputeExpired => {
matches!(dispute_status, DisputeStatus::DisputeExpired)
}
DisputeStatus::DisputeAccepted => {
matches!(dispute_status, DisputeStatus::DisputeAccepted)
}
DisputeStatus::DisputeCancelled => {
matches!(dispute_status, DisputeStatus::DisputeCancelled)
}
DisputeStatus::DisputeChallenged => matches!(
dispute_status,
DisputeStatus::DisputeChallenged
| DisputeStatus::DisputeWon
| DisputeStatus::DisputeLost
| DisputeStatus::DisputeAccepted
| DisputeStatus::DisputeCancelled
| DisputeStatus::DisputeExpired
),
DisputeStatus::DisputeWon => matches!(dispute_status, DisputeStatus::DisputeWon),
DisputeStatus::DisputeLost => matches!(dispute_status, DisputeStatus::DisputeLost),
}
}
pub fn validate_dispute_stage_and_dispute_status(
prev_dispute_stage: DisputeStage,
prev_dispute_status: DisputeStatus,
dispute_stage: DisputeStage,
dispute_status: DisputeStatus,
) -> CustomResult<(), errors::WebhooksFlowError> {
let dispute_stage_validation = validate_dispute_stage(prev_dispute_stage, dispute_stage);
let dispute_status_validation = if dispute_stage == prev_dispute_stage {
validate_dispute_status(prev_dispute_status, dispute_status)
} else {
true
};
common_utils::fp_utils::when(
!(dispute_stage_validation && dispute_status_validation),
|| {
super::metrics::INCOMING_DISPUTE_WEBHOOK_VALIDATION_FAILURE_METRIC.add(1, &[]);
Err(errors::WebhooksFlowError::DisputeWebhookValidationFailed)?
},
)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn construct_accept_dispute_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
merchant_context: &domain::MerchantContext,
dispute: &storage::Dispute,
) -> RouterResult<types::AcceptDisputeRouterData> {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
&dispute.connector,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method = payment_attempt
.payment_method
.get_required_value("payment_method")?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector: dispute.connector.to_string(),
tenant_id: state.tenant.tenant_id.clone(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
payment_method_type: payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
payment_method_status: None,
request: types::AcceptDisputeRequestData {
dispute_id: dispute.dispute_id.clone(),
connector_dispute_id: dispute.connector_dispute_id.clone(),
dispute_status: dispute.dispute_status,
},
response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
customer_id: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
payment_intent,
payment_attempt,
&dispute.connector,
)?,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[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,
dispute_id: Some(dispute.dispute_id.clone()),
refund_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)]
pub async fn construct_submit_evidence_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
merchant_context: &domain::MerchantContext,
dispute: &storage::Dispute,
submit_evidence_request_data: types::SubmitEvidenceRequestData,
) -> RouterResult<types::SubmitEvidenceRouterData> {
let connector_id = &dispute.connector;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method = payment_attempt
.payment_method
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
payment_method_type: payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
request: submit_evidence_request_data,
response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
customer_id: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
payment_method_status: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
payment_intent,
payment_attempt,
connector_id,
)?,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: Some(dispute.dispute_id.clone()),
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_upload_file_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
merchant_context: &domain::MerchantContext,
create_file_request: &api::CreateFileRequest,
dispute_data: storage::Dispute,
connector_id: &str,
file_key: String,
) -> RouterResult<types::UploadFileRouterData> {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method = payment_attempt
.payment_method
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
payment_method_type: payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
payment_method_status: None,
request: types::UploadFileRequestData {
file_key,
file: create_file_request.file.clone(),
file_type: create_file_request.file_type.clone(),
file_size: create_file_request.file_size,
dispute_id: dispute_data.dispute_id.clone(),
connector_dispute_id: dispute_data.connector_dispute_id.clone(),
},
response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
customer_id: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
payment_intent,
payment_attempt,
connector_id,
)?,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn construct_dispute_list_router_data<'a>(
state: &'a SessionState,
merchant_connector_account: MerchantConnectorAccount,
req: types::FetchDisputesRequestData,
) -> RouterResult<types::FetchDisputesRouterData> {
let merchant_id = merchant_connector_account.merchant_id.clone();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
Ok(types::RouterData {
flow: PhantomData,
merchant_id,
customer_id: None,
connector_customer: None,
connector: merchant_connector_account.connector_name.clone(),
payment_id: consts::IRRELEVANT_PAYMENT_INTENT_ID.to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: consts::IRRELEVANT_PAYMENT_ATTEMPT_ID.to_owned(),
status: common_enums::AttemptStatus::default(),
payment_method: common_enums::PaymentMethod::default(),
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: common_enums::AuthenticationType::default(),
connector_meta_data: merchant_connector_account.get_metadata().clone(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
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: None,
payment_method_balance: None,
connector_api_version: None,
request: req,
response: Err(ErrorResponse::default()),
//TODO
connector_request_reference_id:
"IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW".to_owned(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
payment_method_status: 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,
})
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn construct_dispute_sync_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
merchant_context: &domain::MerchantContext,
dispute: &storage::Dispute,
) -> RouterResult<types::DisputeSyncRouterData> {
let _db = &*state.store;
let connector_id = &dispute.connector;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method = payment_attempt
.payment_method
.get_required_value("payment_method")?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
payment_method_type: payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
payment_method_status: None,
request: types::DisputeSyncData {
dispute_id: dispute.dispute_id.clone(),
connector_dispute_id: dispute.connector_dispute_id.clone(),
},
response: Err(ErrorResponse::get_not_implemented()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
customer_id: None,
connector_customer: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
payment_intent,
payment_attempt,
connector_id,
)?,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: Some(dispute.dispute_id.clone()),
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")]
pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
merchant_connector_account: &MerchantConnectorAccount,
) -> RouterResult<types::PaymentsTaxCalculationRouterData> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn construct_payments_dynamic_tax_calculation_router_data<F: Clone>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
merchant_connector_account: &MerchantConnectorAccount,
) -> RouterResult<types::PaymentsTaxCalculationRouterData> {
let payment_intent = &payment_data.payment_intent.clone();
let payment_attempt = &payment_data.payment_attempt.clone();
#[cfg(feature = "v1")]
let test_mode: Option<bool> = merchant_connector_account.test_mode;
#[cfg(feature = "v2")]
let test_mode = None;
let connector_auth_type: types::ConnectorAuthType = merchant_connector_account
.connector_account_details
.clone()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let shipping_address = payment_data
.tax_data
.clone()
.map(|tax_data| tax_data.shipping_details)
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing shipping_details")?;
let order_details: Option<Vec<OrderDetailsWithAmount>> = payment_intent
.order_details
.clone()
.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<_>, _>>()
})
.transpose()?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
customer_id: None,
connector_customer: None,
connector: merchant_connector_account.connector_name.clone(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
tenant_id: state.tenant.tenant_id.clone(),
status: payment_attempt.status,
payment_method: diesel_models::enums::PaymentMethod::default(),
payment_method_type: payment_attempt.payment_method_type,
connector_auth_type,
description: None,
address: payment_data.address.clone(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
request: types::PaymentsTaxCalculationData {
amount: payment_intent.amount,
shipping_cost: payment_intent.shipping_cost,
order_details,
currency: payment_data.currency,
shipping_address,
},
response: Err(ErrorResponse::default()),
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
payment_intent,
payment_attempt,
&merchant_connector_account.connector_name,
)?,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
payment_method_status: None,
minor_amount_captured: 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)]
pub async fn construct_defend_dispute_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
merchant_context: &domain::MerchantContext,
dispute: &storage::Dispute,
) -> RouterResult<types::DefendDisputeRouterData> {
let _db = &*state.store;
let connector_id = &dispute.connector;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
&profile_id,
connector_id,
payment_attempt.merchant_connector_id.as_ref(),
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method = payment_attempt
.payment_method
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
payment_method_type: payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
payment_method_status: None,
request: types::DefendDisputeRequestData {
dispute_id: dispute.dispute_id.clone(),
connector_dispute_id: dispute.connector_dispute_id.clone(),
},
response: Err(ErrorResponse::get_not_implemented()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
customer_id: None,
connector_customer: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
payment_intent,
payment_attempt,
connector_id,
)?,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: Some(dispute.dispute_id.clone()),
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)
}
#[instrument(skip_all)]
pub async fn construct_retrieve_file_router_data<'a>(
state: &'a SessionState,
merchant_context: &domain::MerchantContext,
file_metadata: &diesel_models::file::FileMetadata,
dispute: Option<storage::Dispute>,
connector_id: &str,
) -> RouterResult<types::RetrieveFileRouterData> {
let profile_id = file_metadata
.profile_id
.as_ref()
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id",
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in file_metadata")?;
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
None,
merchant_context.get_merchant_key_store(),
profile_id,
connector_id,
file_metadata.merchant_connector_id.as_ref(),
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector: connector_id.to_string(),
tenant_id: state.tenant.tenant_id.clone(),
customer_id: None,
connector_customer: None,
payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("dispute")
.get_string_repr()
.to_owned(),
attempt_id: IRRELEVANT_ATTEMPT_ID_IN_DISPUTE_FLOW.to_string(),
status: diesel_models::enums::AttemptStatus::default(),
payment_method: diesel_models::enums::PaymentMethod::default(),
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: diesel_models::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::RetrieveFileRequestData {
provider_file_id: file_metadata
.provider_file_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing provider file id")?,
connector_dispute_id: dispute.map(|dispute_data| dispute_data.connector_dispute_id),
},
response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_request_reference_id: IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLOW
.to_string(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
pub fn is_merchant_enabled_for_payment_id_as_connector_request_id(
conf: &Settings,
merchant_id: &common_utils::id_type::MerchantId,
) -> bool {
let config_map = &conf
.connector_request_reference_id_config
.merchant_ids_send_payment_id_as_connector_request_id;
config_map.contains(merchant_id)
}
#[cfg(feature = "v1")]
pub fn get_connector_request_reference_id(
conf: &Settings,
merchant_id: &common_utils::id_type::MerchantId,
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
connector_name: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
let is_config_enabled_to_send_payment_id_as_connector_request_id =
is_merchant_enabled_for_payment_id_as_connector_request_id(conf, merchant_id);
let connector_data = api::ConnectorData::get_connector_by_name(
&conf.connectors,
connector_name,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| "Failed to construct connector data")?;
let connector_request_reference_id = connector_data
.connector
.generate_connector_request_reference_id(
payment_intent,
payment_attempt,
is_config_enabled_to_send_payment_id_as_connector_request_id,
);
Ok(connector_request_reference_id)
}
// TODO: Based on the connector configuration, the connector_request_reference_id should be generated
#[cfg(feature = "v2")]
pub fn get_connector_request_reference_id(
conf: &Settings,
merchant_id: &common_utils::id_type::MerchantId,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> String {
todo!()
}
/// Validate whether the profile_id exists and is associated with the merchant_id
pub async fn validate_and_get_business_profile(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
profile_id: Option<&common_utils::id_type::ProfileId>,
merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<Option<domain::Profile>> {
profile_id
.async_map(|profile_id| async {
db.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
merchant_key_store,
merchant_id,
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})
})
.await
.transpose()
}
fn connector_needs_business_sub_label(connector_name: &str) -> bool {
let connectors_list = [Connector::Cybersource];
connectors_list
.map(|connector| connector.to_string())
.contains(&connector_name.to_string())
}
/// Create the connector label
/// {connector_name}_{country}_{business_label}
pub fn get_connector_label(
business_country: Option<api_models::enums::CountryAlpha2>,
business_label: Option<&String>,
business_sub_label: Option<&String>,
connector_name: &str,
) -> Option<String> {
business_country
.zip(business_label)
.map(|(business_country, business_label)| {
let mut connector_label =
format!("{connector_name}_{business_country}_{business_label}");
// Business sub label is currently being used only for cybersource
// To ensure backwards compatibality, cybersource mca's created before this change
// will have the business_sub_label value as default.
//
// Even when creating the connector account, if no sub label is provided, default will be used
if connector_needs_business_sub_label(connector_name) {
if let Some(sub_label) = business_sub_label {
connector_label.push_str(&format!("_{sub_label}"));
} else {
connector_label.push_str("_default"); // For backwards compatibality
}
}
connector_label
})
}
#[cfg(feature = "v1")]
/// If profile_id is not passed, use default profile if available, or
/// If business_details (business_country and business_label) are passed, get the business_profile
/// or return a `MissingRequiredField` error
#[allow(clippy::too_many_arguments)]
pub async fn get_profile_id_from_business_details(
key_manager_state: &KeyManagerState,
business_country: Option<api_models::enums::CountryAlpha2>,
business_label: Option<&String>,
merchant_context: &domain::MerchantContext,
request_profile_id: Option<&common_utils::id_type::ProfileId>,
db: &dyn StorageInterface,
should_validate: bool,
) -> RouterResult<common_utils::id_type::ProfileId> {
match request_profile_id.or(merchant_context
.get_merchant_account()
.default_profile
.as_ref())
{
Some(profile_id) => {
// Check whether this business profile belongs to the merchant
if should_validate {
let _ = validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?;
}
Ok(profile_id.clone())
}
None => match business_country.zip(business_label) {
Some((business_country, business_label)) => {
let profile_name = format!("{business_country}_{business_label}");
let business_profile = db
.find_business_profile_by_profile_name_merchant_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_name,
merchant_context.get_merchant_account().get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_name,
})?;
Ok(business_profile.get_id().to_owned())
}
_ => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id or business_country, business_label"
})),
},
}
}
pub fn get_poll_id(merchant_id: &common_utils::id_type::MerchantId, unique_id: String) -> String {
merchant_id.get_poll_id(&unique_id)
}
pub fn get_external_authentication_request_poll_id(
payment_id: &common_utils::id_type::PaymentId,
) -> String {
payment_id.get_external_authentication_request_poll_id()
}
pub fn get_modular_authentication_request_poll_id(
authentication_id: &common_utils::id_type::AuthenticationId,
) -> String {
authentication_id.get_external_authentication_request_poll_id()
}
pub fn get_html_redirect_response_popup(
return_url_with_query_params: String,
) -> RouterResult<String> {
Ok(html! {
head {
title { "Redirect Form" }
(PreEscaped(format!(r#"
<script>
let return_url = "{return_url_with_query_params}";
try {{
// if inside iframe, send post message to parent for redirection
if (window.self !== window.parent) {{
window.parent.postMessage({{openurl_if_required: return_url}}, '*')
// if parent, redirect self to return_url
}} else {{
window.location.href = return_url
}}
}}
catch(err) {{
// if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url
window.parent.postMessage({{openurl_if_required: return_url}}, '*')
setTimeout(function() {{
window.location.href = return_url
}}, 10000);
console.log(err.message)
}}
</script>
"#)))
}
}
.into_string())
}
#[cfg(feature = "v1")]
pub fn get_html_redirect_response_for_external_authentication(
return_url_with_query_params: String,
payment_response: &api_models::payments::PaymentsResponse,
payment_id: common_utils::id_type::PaymentId,
poll_config: &PollConfig,
) -> RouterResult<String> {
// if intent_status is requires_customer_action then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url
let html = match payment_response.status {
IntentStatus::RequiresCustomerAction => {
// Request poll id sent to client for retrieve_poll_status api
let req_poll_id = get_external_authentication_request_poll_id(&payment_id);
let poll_frequency = poll_config.frequency;
let poll_delay_in_secs = poll_config.delay_in_secs;
html! {
head {
title { "Redirect Form" }
(PreEscaped(format!(r#"
<script>
let return_url = "{return_url_with_query_params}";
let poll_status_data = {{
'poll_id': '{req_poll_id}',
'frequency': '{poll_frequency}',
'delay_in_secs': '{poll_delay_in_secs}',
'return_url_with_query_params': return_url
}};
try {{
// if inside iframe, send post message to parent for redirection
if (window.self !== window.parent) {{
window.parent.postMessage({{poll_status: poll_status_data}}, '*')
// if parent, redirect self to return_url
}} else {{
window.location.href = return_url
}}
}}
catch(err) {{
// if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url
window.parent.postMessage({{poll_status: poll_status_data}}, '*')
setTimeout(function() {{
window.location.href = return_url
}}, 10000);
console.log(err.message)
}}
</script>
"#)))
}
}
.into_string()
},
_ => {
html! {
head {
title { "Redirect Form" }
(PreEscaped(format!(r#"
<script>
let return_url = "{return_url_with_query_params}";
try {{
// if inside iframe, send post message to parent for redirection
if (window.self !== window.parent) {{
window.parent.postMessage({{openurl_if_required: return_url}}, '*')
// if parent, redirect self to return_url
}} else {{
window.location.href = return_url
}}
}}
catch(err) {{
// if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url
window.parent.postMessage({{openurl_if_required: return_url}}, '*')
setTimeout(function() {{
window.location.href = return_url
}}, 10000);
console.log(err.message)
}}
</script>
"#)))
}
}
.into_string()
},
};
Ok(html)
}
#[cfg(feature = "v1")]
pub fn get_html_redirect_response_for_external_modular_authentication(
return_url_with_query_params: String,
authentication_response: &api_models::authentication::AuthenticationResponse,
authentication_id: common_utils::id_type::AuthenticationId,
poll_config: &PollConfig,
) -> RouterResult<String> {
// if authentication_status is pending then set poll_id, fetch poll config and do a poll_status post message, else do open_url post message to redirect to return_url
let html = match authentication_response.status {
common_enums::AuthenticationStatus::Pending => {
// Request poll id sent to client for retrieve_poll_status api
let req_poll_id = get_modular_authentication_request_poll_id(&authentication_id);
let poll_frequency = poll_config.frequency;
let poll_delay_in_secs = poll_config.delay_in_secs;
html! {
head {
title { "Redirect Form" }
(PreEscaped(format!(r#"
<script>
let return_url = "{return_url_with_query_params}";
let poll_status_data = {{
'poll_id': '{req_poll_id}',
'frequency': '{poll_frequency}',
'delay_in_secs': '{poll_delay_in_secs}',
'return_url_with_query_params': return_url
}};
try {{
// if inside iframe, send post message to parent for redirection
if (window.self !== window.parent) {{
window.parent.postMessage({{poll_status: poll_status_data}}, '*')
// if parent, redirect self to return_url
}} else {{
window.location.href = return_url
}}
}}
catch(err) {{
// if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url
window.parent.postMessage({{poll_status: poll_status_data}}, '*')
setTimeout(function() {{
window.location.href = return_url
}}, 10000);
console.log(err.message)
}}
</script>
"#)))
}
}
.into_string()
},
_ => {
html! {
head {
title { "Redirect Form" }
(PreEscaped(format!(r#"
<script>
let return_url = "{return_url_with_query_params}";
try {{
// if inside iframe, send post message to parent for redirection
if (window.self !== window.parent) {{
window.parent.postMessage({{openurl_if_required: return_url}}, '*')
// if parent, redirect self to return_url
}} else {{
window.location.href = return_url
}}
}}
catch(err) {{
// if error occurs, send post message to parent and wait for 10 secs to redirect. if doesn't redirect, redirect self to return_url
window.parent.postMessage({{openurl_if_required: return_url}}, '*')
setTimeout(function() {{
window.location.href = return_url
}}, 10000);
console.log(err.message)
}}
</script>
"#)))
}
}
.into_string()
},
};
Ok(html)
}
#[inline]
pub 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())
}
pub fn get_request_incremental_authorization_value(
request_incremental_authorization: Option<bool>,
capture_method: Option<common_enums::CaptureMethod>,
) -> RouterResult<Option<RequestIncrementalAuthorization>> {
Some(request_incremental_authorization
.map(|request_incremental_authorization| {
if request_incremental_authorization {
if matches!(
capture_method,
Some(common_enums::CaptureMethod::Automatic) | Some(common_enums::CaptureMethod::SequentialAutomatic)
) {
Err(errors::ApiErrorResponse::NotSupported { message: "incremental authorization is not supported when capture_method is automatic".to_owned() })?
}
Ok(RequestIncrementalAuthorization::True)
} else {
Ok(RequestIncrementalAuthorization::False)
}
})
.unwrap_or(Ok(RequestIncrementalAuthorization::default()))).transpose()
}
pub fn get_incremental_authorization_allowed_value(
incremental_authorization_allowed: Option<bool>,
request_incremental_authorization: Option<RequestIncrementalAuthorization>,
) -> Option<bool> {
if request_incremental_authorization == Some(RequestIncrementalAuthorization::False) {
Some(false)
} else {
incremental_authorization_allowed
}
}
pub(crate) trait GetProfileId {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId>;
}
impl GetProfileId for MerchantConnectorAccount {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
Some(&self.profile_id)
}
}
impl GetProfileId for storage::PaymentIntent {
#[cfg(feature = "v1")]
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
self.profile_id.as_ref()
}
// TODO: handle this in a better way for v2
#[cfg(feature = "v2")]
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
Some(&self.profile_id)
}
}
impl<A> GetProfileId for (storage::PaymentIntent, A) {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
self.0.get_profile_id()
}
}
impl GetProfileId for diesel_models::Dispute {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
self.profile_id.as_ref()
}
}
impl GetProfileId for diesel_models::Refund {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
self.profile_id.as_ref()
}
}
#[cfg(feature = "v1")]
impl GetProfileId for api_models::routing::RoutingConfigRequest {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
self.profile_id.as_ref()
}
}
#[cfg(feature = "v2")]
impl GetProfileId for api_models::routing::RoutingConfigRequest {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
Some(&self.profile_id)
}
}
impl GetProfileId for api_models::routing::RoutingRetrieveLinkQuery {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
self.profile_id.as_ref()
}
}
impl GetProfileId for diesel_models::routing_algorithm::RoutingProfileMetadata {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
Some(&self.profile_id)
}
}
impl GetProfileId for domain::Profile {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
Some(self.get_id())
}
}
#[cfg(feature = "payouts")]
impl GetProfileId for storage::Payouts {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
Some(&self.profile_id)
}
}
#[cfg(feature = "payouts")]
impl<T, F, R> GetProfileId for (storage::Payouts, T, F, R) {
fn get_profile_id(&self) -> Option<&common_utils::id_type::ProfileId> {
self.0.get_profile_id()
}
}
/// Filter Objects based on profile ids
pub(super) fn filter_objects_based_on_profile_id_list<
T: GetProfileId,
U: IntoIterator<Item = T> + FromIterator<T>,
>(
profile_id_list_auth_layer: Option<Vec<common_utils::id_type::ProfileId>>,
object_list: U,
) -> U {
if let Some(profile_id_list) = profile_id_list_auth_layer {
let profile_ids_to_filter: HashSet<_> = profile_id_list.iter().collect();
object_list
.into_iter()
.filter_map(|item| {
if item
.get_profile_id()
.is_some_and(|profile_id| profile_ids_to_filter.contains(profile_id))
{
Some(item)
} else {
None
}
})
.collect()
} else {
object_list
}
}
pub(crate) fn validate_profile_id_from_auth_layer<T: GetProfileId + std::fmt::Debug>(
profile_id_auth_layer: Option<common_utils::id_type::ProfileId>,
object: &T,
) -> RouterResult<()> {
match (profile_id_auth_layer, object.get_profile_id()) {
(Some(auth_profile_id), Some(object_profile_id)) => {
auth_profile_id.eq(object_profile_id).then_some(()).ok_or(
errors::ApiErrorResponse::PreconditionFailed {
message: "Profile id authentication failed. Please use the correct JWT token"
.to_string(),
}
.into(),
)
}
(Some(_auth_profile_id), None) => RouterResult::Err(
errors::ApiErrorResponse::PreconditionFailed {
message: "Couldn't find profile_id in record for authentication".to_string(),
}
.into(),
)
.attach_printable(format!("Couldn't find profile_id in entity {object:?}")),
(None, None) | (None, Some(_)) => Ok(()),
}
}
pub async fn construct_vault_router_data<F>(
state: &SessionState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_account: &MerchantConnectorAccount,
payment_method_vaulting_data: Option<
hyperswitch_domain_models::vault::PaymentMethodVaultingData,
>,
connector_vault_id: Option<String>,
connector_customer_id: Option<String>,
) -> RouterResult<VaultRouterDataV2<F>> {
let connector_auth_type = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let resource_common_data = VaultConnectorFlowData {
merchant_id: merchant_id.to_owned(),
};
let router_data = types::RouterDataV2 {
flow: PhantomData,
resource_common_data,
tenant_id: state.tenant.tenant_id.clone(),
connector_auth_type,
request: types::VaultRequestData {
payment_method_vaulting_data,
connector_vault_id,
connector_customer_id,
},
response: Ok(types::VaultResponseData::default()),
};
Ok(router_data)
}
pub fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> {
match data {
types::MerchantAccountData::Iban { iban, .. } => validate_iban(iban),
types::MerchantAccountData::Sepa { iban, .. } => validate_iban(iban),
types::MerchantAccountData::SepaInstant { iban, .. } => validate_iban(iban),
types::MerchantAccountData::Bacs {
account_number,
sort_code,
..
} => validate_uk_account(account_number, sort_code),
types::MerchantAccountData::FasterPayments {
account_number,
sort_code,
..
} => validate_uk_account(account_number, sort_code),
types::MerchantAccountData::Elixir { iban, .. } => validate_elixir_account(iban),
types::MerchantAccountData::Bankgiro { number, .. } => validate_bankgiro_number(number),
types::MerchantAccountData::Plusgiro { number, .. } => validate_plusgiro_number(number),
}
}
fn validate_iban(iban: &Secret<String>) -> RouterResult<()> {
let iban_str = iban.peek();
if iban_str.len() > consts::IBAN_MAX_LENGTH || iban_str.len() < consts::IBAN_MIN_LENGTH {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"IBAN length must be between {} and {} characters",
consts::IBAN_MIN_LENGTH,
consts::IBAN_MAX_LENGTH
),
}
.into());
}
if iban.peek().len() > consts::IBAN_MAX_LENGTH {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "IBAN length must be up to 34 characters".to_string(),
}
.into());
}
let pattern = Regex::new(r"^[A-Z0-9]*$")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to create regex pattern")?;
let mut iban = iban.peek().to_string();
if !pattern.is_match(iban.as_str()) {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "IBAN data must be alphanumeric".to_string(),
}
.into());
}
// MOD check
let first_4 = iban.chars().take(4).collect::<String>();
iban.push_str(first_4.as_str());
let len = iban.len();
let rearranged_iban = iban
.chars()
.rev()
.take(len - 4)
.collect::<String>()
.chars()
.rev()
.collect::<String>();
let mut result = String::new();
rearranged_iban.chars().for_each(|c| {
if c.is_ascii_uppercase() {
let digit = (u32::from(c) - u32::from('A')) + 10;
result.push_str(&format!("{digit:02}"));
} else {
result.push(c);
}
});
let num = result
.parse::<u128>()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to validate IBAN")?;
if num % 97 != 1 {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid IBAN".to_string(),
}
.into());
}
Ok(())
}
fn validate_uk_account(
account_number: &Secret<String>,
sort_code: &Secret<String>,
) -> RouterResult<()> {
if account_number.peek().len() > consts::BACS_MAX_ACCOUNT_NUMBER_LENGTH
|| sort_code.peek().len() != consts::BACS_SORT_CODE_LENGTH
{
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid BACS numbers".to_string(),
}
.into());
}
Ok(())
}
fn validate_elixir_account(iban: &Secret<String>) -> RouterResult<()> {
let iban_str = iban.peek();
// Validate IBAN first
validate_iban(iban)?;
// Check if IBAN is Polish
if !iban_str.starts_with("PL") {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Elixir IBAN must be Polish (PL)".to_string(),
}
.into());
}
// Validate IBAN length for Poland
if iban_str.len() != consts::ELIXIR_IBAN_LENGTH {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Polish IBAN must be 28 characters".to_string(),
}
.into());
}
Ok(())
}
fn validate_bankgiro_number(number: &Secret<String>) -> RouterResult<()> {
let num_str = number.peek();
let clean_number = num_str.replace("-", "").replace(" ", "");
// Length validation
if clean_number.len() < consts::BANKGIRO_MIN_LENGTH
|| clean_number.len() > consts::BANKGIRO_MAX_LENGTH
{
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Bankgiro number must be between {} and {} digits",
consts::BANKGIRO_MIN_LENGTH,
consts::BANKGIRO_MAX_LENGTH
),
}
.into());
}
// Must be numeric
if !clean_number.chars().all(|c| c.is_ascii_digit()) {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Bankgiro number must be numeric".to_string(),
}
.into());
}
Ok(())
}
fn validate_plusgiro_number(number: &Secret<String>) -> RouterResult<()> {
let num_str = number.peek();
let clean_number = num_str.replace("-", "").replace(" ", "");
// Length validation
if clean_number.len() < consts::PLUSGIRO_MIN_LENGTH
|| clean_number.len() > consts::PLUSGIRO_MAX_LENGTH
{
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Plusgiro number must be between {} and {} digits",
consts::PLUSGIRO_MIN_LENGTH,
consts::PLUSGIRO_MAX_LENGTH
),
}
.into());
}
// Must be numeric
if !clean_number.chars().all(|c| c.is_ascii_digit()) {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Plusgiro number must be numeric".to_string(),
}
.into());
}
Ok(())
}
pub fn should_add_dispute_sync_task_to_pt(state: &SessionState, connector_name: Connector) -> bool {
let list_dispute_supported_connectors = state
.conf
.list_dispute_supported_connectors
.connector_list
.clone();
list_dispute_supported_connectors.contains(&connector_name)
}
pub fn should_proceed_with_submit_evidence(
dispute_stage: DisputeStage,
dispute_status: DisputeStatus,
) -> bool {
matches!(
dispute_stage,
DisputeStage::PreDispute
| DisputeStage::Dispute
| DisputeStage::PreArbitration
| DisputeStage::Arbitration
) && matches!(
dispute_status,
DisputeStatus::DisputeOpened | DisputeStatus::DisputeChallenged
)
}
pub fn should_proceed_with_accept_dispute(
dispute_stage: DisputeStage,
dispute_status: DisputeStatus,
) -> bool {
matches!(
dispute_stage,
DisputeStage::PreDispute
| DisputeStage::Dispute
| DisputeStage::PreArbitration
| DisputeStage::Arbitration
) && matches!(
dispute_status,
DisputeStatus::DisputeChallenged | DisputeStatus::DisputeOpened
)
}
| crates/router/src/core/utils.rs | router::src::core::utils | 20,623 | true |
// File: crates/router/src/core/admin.rs
// Module: router::src::core::admin
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,
merchant_context: &domain::MerchantContext,
) {
let state = state.clone();
let publishable_key = merchant_context
.get_merchant_account()
.publishable_key
.clone();
let merchant_id = merchant_context.get_merchant_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: 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::Encrypt(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?;
let key_manager_state = &(&state).into();
db.insert_merchant_key_store(
key_manager_state,
key_store.clone(),
&master_key.to_vec().into(),
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
let merchant_account = db
.insert_merchant(key_manager_state, domain_merchant_account, &key_store)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
add_publishable_key_to_decision_service(&state, &merchant_context);
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(
&state.into(),
&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(
&(&state).into(),
&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(&(&state).into(), &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_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&req.merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, &req.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok(service_api::ApplicationResponse::Json(
api::MerchantAccountResponse::foreign_try_from(merchant_account)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct response")?,
))
}
#[cfg(feature = "v1")]
/// For backwards compatibility, whenever new business labels are passed in
/// primary_business_details, create a profile
pub async fn create_profile_from_business_labels(
state: &SessionState,
db: &dyn StorageInterface,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
new_business_details: Vec<admin_types::PrimaryBusinessDetails>,
) -> RouterResult<()> {
let key_manager_state = &state.into();
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let old_business_details = merchant_account
.primary_business_details
.clone()
.parse_value::<Vec<admin_types::PrimaryBusinessDetails>>("PrimaryBusinessDetails")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "routing_algorithm",
})
.attach_printable("Invalid routing algorithm given")?;
// find the diff between two vectors
let business_profiles_to_create = new_business_details
.into_iter()
.filter(|business_details| !old_business_details.contains(business_details))
.collect::<Vec<_>>();
for business_profile in business_profiles_to_create {
let profile_name = format!("{}_{}", business_profile.country, business_profile.business);
let profile_create_request = admin_types::ProfileCreate {
profile_name: Some(profile_name),
..Default::default()
};
let profile_create_result = create_and_insert_business_profile(
state,
profile_create_request,
merchant_account.clone(),
key_store,
)
.await
.map_err(|profile_insert_error| {
// If there is any duplicate error, we need not take any action
logger::warn!("Profile already exists {profile_insert_error:?}");
});
// If a profile is created, then unset the default profile
if profile_create_result.is_ok() && merchant_account.default_profile.is_some() {
let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile;
db.update_merchant(
key_manager_state,
merchant_account.clone(),
unset_default_profile,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
}
}
Ok(())
}
#[cfg(any(feature = "v1", feature = "v2", feature = "olap"))]
#[async_trait::async_trait]
trait MerchantAccountUpdateBridge {
async fn get_update_merchant_object(
self,
state: &SessionState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<storage::MerchantAccountUpdate>;
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {
async fn get_update_merchant_object(
self,
state: &SessionState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<storage::MerchantAccountUpdate> {
let key_manager_state = &state.into();
let key = key_store.key.get_inner().peek();
let db = state.store.as_ref();
let primary_business_details = self.get_primary_details_as_value().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "primary_business_details",
},
)?;
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",
},
)?;
let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);
let parent_merchant_id = get_parent_merchant(
state,
self.sub_merchants_enabled,
self.parent_merchant_id.as_ref(),
key_store,
)
.await?;
// This supports changing the business profile by passing in the profile_id
let business_profile_id_update = if let Some(ref profile_id) = self.default_profile {
// Validate whether profile_id passed in request is valid and is linked to the merchant
core_utils::validate_and_get_business_profile(
state.store.as_ref(),
key_manager_state,
key_store,
Some(profile_id),
merchant_id,
)
.await?
.map(|business_profile| Some(business_profile.get_id().to_owned()))
} else {
None
};
#[cfg(any(feature = "v1", feature = "v2"))]
// In order to support backwards compatibility, if a business_labels are passed in the update
// call, then create new profiles with the profile_name as business_label
self.primary_business_details
.clone()
.async_map(|primary_business_details| async {
let _ = create_profile_from_business_labels(
state,
db,
key_store,
merchant_id,
primary_business_details,
)
.await;
})
.await;
let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone());
Ok(storage::MerchantAccountUpdate::Update {
merchant_name: self
.merchant_name
.map(Secret::new)
.async_lift(|inner| async {
domain_types::crypto_operation(
key_manager_state,
type_name!(storage::MerchantAccount),
domain_types::CryptoOperation::EncryptOptional(inner),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt merchant name")?,
merchant_details: merchant_details
.async_lift(|inner| async {
domain_types::crypto_operation(
key_manager_state,
type_name!(storage::MerchantAccount),
domain_types::CryptoOperation::EncryptOptional(inner),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt merchant details")?,
return_url: self.return_url.map(|a| a.to_string()),
webhook_details,
sub_merchants_enabled: self.sub_merchants_enabled,
parent_merchant_id,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
locker_id: self.locker_id,
metadata: self.metadata,
publishable_key: None,
primary_business_details,
frm_routing_algorithm: self.frm_routing_algorithm,
intent_fulfillment_time: None,
#[cfg(feature = "payouts")]
payout_routing_algorithm: self.payout_routing_algorithm,
#[cfg(not(feature = "payouts"))]
payout_routing_algorithm: None,
default_profile: business_profile_id_update,
payment_link_config: None,
pm_collect_link_config,
routing_algorithm: self.routing_algorithm,
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {
async fn get_update_merchant_object(
self,
state: &SessionState,
_merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<storage::MerchantAccountUpdate> {
let key_manager_state = &state.into();
let key = key_store.key.get_inner().peek();
let merchant_details = self.get_merchant_details_as_secret().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "merchant_details",
},
)?;
let metadata = self.get_metadata_as_secret().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "metadata",
},
)?;
let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone());
Ok(storage::MerchantAccountUpdate::Update {
merchant_name: self
.merchant_name
.map(Secret::new)
.async_lift(|inner| async {
domain_types::crypto_operation(
key_manager_state,
type_name!(storage::MerchantAccount),
domain_types::CryptoOperation::EncryptOptional(inner),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt merchant name")?,
merchant_details: merchant_details
.async_lift(|inner| async {
domain_types::crypto_operation(
key_manager_state,
type_name!(storage::MerchantAccount),
domain_types::CryptoOperation::EncryptOptional(inner),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt merchant details")?,
metadata: metadata.map(Box::new),
publishable_key: None,
})
}
}
pub async fn merchant_account_update(
state: SessionState,
merchant_id: &id_type::MerchantId,
_profile_id: Option<id_type::ProfileId>,
req: api::MerchantAccountUpdate,
) -> RouterResponse<api::MerchantAccountResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account_storage_object = req
.get_update_merchant_object(&state, merchant_id, &key_store)
.await
.attach_printable("Failed to create merchant account update object")?;
let response = db
.update_specific_fields_in_merchant(
key_manager_state,
merchant_id,
merchant_account_storage_object,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok(service_api::ApplicationResponse::Json(
api::MerchantAccountResponse::foreign_try_from(response)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while generating response")?,
))
}
pub async fn merchant_account_delete(
state: SessionState,
merchant_id: id_type::MerchantId,
) -> RouterResponse<api::MerchantAccountDeleteResponse> {
let mut is_deleted = false;
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &merchant_key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let is_merchant_account_deleted = db
.delete_merchant_account_by_merchant_id(&merchant_id)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
if is_merchant_account_deleted {
let is_merchant_key_store_deleted = db
.delete_merchant_key_store_by_merchant_id(&merchant_id)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
is_deleted = is_merchant_account_deleted && is_merchant_key_store_deleted;
}
let state = state.clone();
authentication::decision::spawn_tracked_job(
async move {
authentication::decision::revoke_api_key(
&state,
merchant_account.publishable_key.into(),
)
.await
},
authentication::decision::REVOKE,
);
match db
.delete_config_by_key(merchant_id.get_requires_cvv_key().as_str())
.await
{
Ok(_) => Ok::<_, errors::ApiErrorResponse>(()),
Err(err) => {
if err.current_context().is_db_not_found() {
logger::error!("requires_cvv config not found in db: {err:?}");
Ok(())
} else {
Err(err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while deleting requires_cvv config"))?
}
}
}
.ok();
let response = api::MerchantAccountDeleteResponse {
merchant_id,
deleted: is_deleted,
};
Ok(service_api::ApplicationResponse::Json(response))
}
#[cfg(feature = "v1")]
async fn get_parent_merchant(
state: &SessionState,
sub_merchants_enabled: Option<bool>,
parent_merchant: Option<&id_type::MerchantId>,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Option<id_type::MerchantId>> {
Ok(match sub_merchants_enabled {
Some(true) => {
Some(
parent_merchant.ok_or_else(|| {
report!(errors::ValidationError::MissingRequiredField {
field_name: "parent_merchant_id".to_string()
})
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "If `sub_merchants_enabled` is `true`, then `parent_merchant_id` is mandatory".to_string(),
})
})
.map(|id| validate_merchant_id(state, id,key_store).change_context(
errors::ApiErrorResponse::InvalidDataValue { field_name: "parent_merchant_id" }
))?
.await?
.get_id().to_owned()
)
}
_ => None,
})
}
#[cfg(feature = "v1")]
async fn validate_merchant_id(
state: &SessionState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<domain::MerchantAccount> {
let db = &*state.store;
db.find_merchant_account_by_merchant_id(&state.into(), merchant_id, key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
}
struct ConnectorStatusAndDisabledValidation<'a> {
status: &'a Option<api_enums::ConnectorStatus>,
disabled: &'a Option<bool>,
auth: &'a types::ConnectorAuthType,
current_status: &'a api_enums::ConnectorStatus,
}
impl ConnectorStatusAndDisabledValidation<'_> {
fn validate_status_and_disabled(
&self,
) -> RouterResult<(api_enums::ConnectorStatus, Option<bool>)> {
let connector_status = match (self.status, self.auth) {
(
Some(common_enums::ConnectorStatus::Active),
types::ConnectorAuthType::TemporaryAuth,
) => {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Connector status cannot be active when using TemporaryAuth"
.to_string(),
}
.into());
}
(Some(status), _) => status,
(None, types::ConnectorAuthType::TemporaryAuth) => {
&common_enums::ConnectorStatus::Inactive
}
(None, _) => self.current_status,
};
let disabled = match (self.disabled, connector_status) {
(Some(false), common_enums::ConnectorStatus::Inactive) => {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Connector cannot be enabled when connector_status is inactive or when using TemporaryAuth"
.to_string(),
}
.into());
}
(Some(disabled), _) => Some(*disabled),
(None, common_enums::ConnectorStatus::Inactive) => Some(true),
// Enable the connector if nothing is passed in the request
(None, _) => Some(false),
};
Ok((*connector_status, disabled))
}
}
struct ConnectorMetadata<'a> {
connector_metadata: &'a Option<pii::SecretSerdeValue>,
}
impl ConnectorMetadata<'_> {
fn validate_apple_pay_certificates_in_mca_metadata(&self) -> RouterResult<()> {
self.connector_metadata
.clone()
.map(api_models::payments::ConnectorMetadata::from_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "metadata".to_string(),
expected_format: "connector metadata".to_string(),
})?
.and_then(|metadata| metadata.get_apple_pay_certificates())
.map(|(certificate, certificate_key)| {
client::create_identity_from_certificate_and_key(certificate, certificate_key)
})
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "certificate/certificate key",
})?;
Ok(())
}
}
struct PMAuthConfigValidation<'a> {
connector_type: &'a api_enums::ConnectorType,
pm_auth_config: &'a Option<pii::SecretSerdeValue>,
db: &'a dyn StorageInterface,
merchant_id: &'a id_type::MerchantId,
profile_id: &'a id_type::ProfileId,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
}
impl PMAuthConfigValidation<'_> {
async fn validate_pm_auth(&self, val: &pii::SecretSerdeValue) -> RouterResponse<()> {
let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(
val.clone().expose(),
)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "invalid data received for payment method auth config".to_string(),
})
.attach_printable("Failed to deserialize Payment Method Auth config")?;
let all_mcas = self
.db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
self.key_manager_state,
self.merchant_id,
true,
self.key_store,
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: self.merchant_id.get_string_repr().to_owned(),
})?;
for conn_choice in config.enabled_payment_methods {
let pm_auth_mca = all_mcas
.iter()
.find(|mca| mca.get_id() == conn_choice.mca_id)
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector account not found".to_string(),
})?;
if &pm_auth_mca.profile_id != self.profile_id {
return Err(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method auth profile_id differs from connector profile_id"
.to_string(),
}
.into());
}
}
Ok(services::ApplicationResponse::StatusOk)
}
async fn validate_pm_auth_config(&self) -> RouterResult<()> {
if self.connector_type != &api_enums::ConnectorType::PaymentMethodAuth {
if let Some(val) = self.pm_auth_config.clone() {
self.validate_pm_auth(&val).await?;
}
}
Ok(())
}
}
struct ConnectorTypeAndConnectorName<'a> {
connector_type: &'a api_enums::ConnectorType,
connector_name: &'a api_enums::Connector,
}
impl ConnectorTypeAndConnectorName<'_> {
fn get_routable_connector(&self) -> RouterResult<Option<api_enums::RoutableConnectors>> {
let mut routable_connector =
api_enums::RoutableConnectors::from_str(&self.connector_name.to_string()).ok();
let vault_connector =
api_enums::convert_vault_connector(self.connector_name.to_string().as_str());
let pm_auth_connector =
api_enums::convert_pm_auth_connector(self.connector_name.to_string().as_str());
let authentication_connector =
api_enums::convert_authentication_connector(self.connector_name.to_string().as_str());
let tax_connector =
api_enums::convert_tax_connector(self.connector_name.to_string().as_str());
let billing_connector =
api_enums::convert_billing_connector(self.connector_name.to_string().as_str());
if pm_auth_connector.is_some() {
if self.connector_type != &api_enums::ConnectorType::PaymentMethodAuth
&& self.connector_type != &api_enums::ConnectorType::PaymentProcessor
{
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector type given".to_string(),
}
.into());
}
} else if authentication_connector.is_some() {
if self.connector_type != &api_enums::ConnectorType::AuthenticationProcessor {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector type given".to_string(),
}
.into());
}
} else if tax_connector.is_some() {
if self.connector_type != &api_enums::ConnectorType::TaxProcessor {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector type given".to_string(),
}
.into());
}
} else if billing_connector.is_some() {
if self.connector_type != &api_enums::ConnectorType::BillingProcessor {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector type given".to_string(),
}
.into());
}
} else if vault_connector.is_some() {
if self.connector_type != &api_enums::ConnectorType::VaultProcessor {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector type given".to_string(),
}
.into());
}
} else {
let routable_connector_option = self
.connector_name
.to_string()
.parse::<api_enums::RoutableConnectors>()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector name given".to_string(),
})?;
routable_connector = Some(routable_connector_option);
};
Ok(routable_connector)
}
}
#[cfg(feature = "v1")]
struct MerchantDefaultConfigUpdate<'a> {
routable_connector: &'a Option<api_enums::RoutableConnectors>,
merchant_connector_id: &'a id_type::MerchantConnectorAccountId,
store: &'a dyn StorageInterface,
merchant_id: &'a id_type::MerchantId,
profile_id: &'a id_type::ProfileId,
transaction_type: &'a api_enums::TransactionType,
}
#[cfg(feature = "v1")]
impl MerchantDefaultConfigUpdate<'_> {
async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists(
&self,
) -> RouterResult<()> {
let mut default_routing_config = routing::helpers::get_merchant_default_config(
self.store,
self.merchant_id.get_string_repr(),
self.transaction_type,
)
.await?;
let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config(
self.store,
self.profile_id.get_string_repr(),
self.transaction_type,
)
.await?;
if let Some(routable_connector_val) = self.routable_connector {
let choice = routing_types::RoutableConnectorChoice {
choice_kind: routing_types::RoutableChoiceKind::FullStruct,
connector: *routable_connector_val,
merchant_connector_id: Some(self.merchant_connector_id.clone()),
};
if !default_routing_config.contains(&choice) {
default_routing_config.push(choice.clone());
routing::helpers::update_merchant_default_config(
self.store,
self.merchant_id.get_string_repr(),
default_routing_config.clone(),
self.transaction_type,
)
.await?;
}
if !default_routing_config_for_profile.contains(&choice.clone()) {
default_routing_config_for_profile.push(choice);
routing::helpers::update_merchant_default_config(
self.store,
self.profile_id.get_string_repr(),
default_routing_config_for_profile.clone(),
self.transaction_type,
)
.await?;
}
}
Ok(())
}
async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists(
&self,
) -> RouterResult<()> {
let mut default_routing_config = routing::helpers::get_merchant_default_config(
self.store,
self.merchant_id.get_string_repr(),
self.transaction_type,
)
.await?;
let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config(
self.store,
self.profile_id.get_string_repr(),
self.transaction_type,
)
.await?;
if let Some(routable_connector_val) = self.routable_connector {
let choice = routing_types::RoutableConnectorChoice {
choice_kind: routing_types::RoutableChoiceKind::FullStruct,
connector: *routable_connector_val,
merchant_connector_id: Some(self.merchant_connector_id.clone()),
};
if default_routing_config.contains(&choice) {
default_routing_config.retain(|mca| {
mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id)
});
routing::helpers::update_merchant_default_config(
self.store,
self.merchant_id.get_string_repr(),
default_routing_config.clone(),
self.transaction_type,
)
.await?;
}
if default_routing_config_for_profile.contains(&choice.clone()) {
default_routing_config_for_profile.retain(|mca| {
mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id)
});
routing::helpers::update_merchant_default_config(
self.store,
self.profile_id.get_string_repr(),
default_routing_config_for_profile.clone(),
self.transaction_type,
)
.await?;
}
}
Ok(())
}
}
#[cfg(feature = "v2")]
struct DefaultFallbackRoutingConfigUpdate<'a> {
routable_connector: &'a Option<api_enums::RoutableConnectors>,
merchant_connector_id: &'a id_type::MerchantConnectorAccountId,
store: &'a dyn StorageInterface,
business_profile: domain::Profile,
key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
}
#[cfg(feature = "v2")]
impl DefaultFallbackRoutingConfigUpdate<'_> {
async fn retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists(
&self,
) -> RouterResult<()> {
let profile_wrapper = ProfileWrapper::new(self.business_profile.clone());
let default_routing_config_for_profile =
&mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;
if let Some(routable_connector_val) = self.routable_connector {
let choice = routing_types::RoutableConnectorChoice {
choice_kind: routing_types::RoutableChoiceKind::FullStruct,
connector: *routable_connector_val,
merchant_connector_id: Some(self.merchant_connector_id.clone()),
};
if !default_routing_config_for_profile.contains(&choice.clone()) {
default_routing_config_for_profile.push(choice);
profile_wrapper
.update_default_fallback_routing_of_connectors_under_profile(
self.store,
default_routing_config_for_profile,
self.key_manager_state,
&self.key_store,
)
.await?
}
}
Ok(())
}
async fn retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists(
&self,
) -> RouterResult<()> {
let profile_wrapper = ProfileWrapper::new(self.business_profile.clone());
let default_routing_config_for_profile =
&mut profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;
if let Some(routable_connector_val) = self.routable_connector {
let choice = routing_types::RoutableConnectorChoice {
choice_kind: routing_types::RoutableChoiceKind::FullStruct,
connector: *routable_connector_val,
merchant_connector_id: Some(self.merchant_connector_id.clone()),
};
if default_routing_config_for_profile.contains(&choice.clone()) {
default_routing_config_for_profile.retain(|mca| {
mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id)
});
profile_wrapper
.update_default_fallback_routing_of_connectors_under_profile(
self.store,
default_routing_config_for_profile,
self.key_manager_state,
&self.key_store,
)
.await?
}
}
Ok(())
}
}
#[cfg(any(feature = "v1", feature = "v2", feature = "olap"))]
#[async_trait::async_trait]
trait MerchantConnectorAccountUpdateBridge {
async fn get_merchant_connector_account_from_id(
self,
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &id_type::MerchantConnectorAccountId,
key_store: &domain::MerchantKeyStore,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount>;
async fn create_domain_model_from_request(
self,
state: &SessionState,
mca: &domain::MerchantConnectorAccount,
key_manager_state: &KeyManagerState,
merchant_context: &domain::MerchantContext,
) -> RouterResult<domain::MerchantConnectorAccountUpdate>;
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[async_trait::async_trait]
impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectorUpdate {
async fn get_merchant_connector_account_from_id(
self,
db: &dyn StorageInterface,
_merchant_id: &id_type::MerchantId,
merchant_connector_id: &id_type::MerchantConnectorAccountId,
key_store: &domain::MerchantKeyStore,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount> {
db.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
}
async fn create_domain_model_from_request(
self,
state: &SessionState,
mca: &domain::MerchantConnectorAccount,
key_manager_state: &KeyManagerState,
merchant_context: &domain::MerchantContext,
) -> RouterResult<domain::MerchantConnectorAccountUpdate> {
let frm_configs = self.get_frm_config_as_secret();
let payment_methods_enabled = self.payment_methods_enabled;
let auth = types::ConnectorAuthType::from_secret_value(
self.connector_account_details
.clone()
.unwrap_or(mca.connector_account_details.clone().into_inner()),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_account_details".to_string(),
expected_format: "auth_type and api_key".to_string(),
})?;
let metadata = self.metadata.clone().or(mca.metadata.clone());
let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation {
connector_name: &mca.connector_name,
auth_type: &auth,
connector_meta_data: &metadata,
};
connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?;
let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation {
status: &self.status,
disabled: &self.disabled,
auth: &auth,
current_status: &mca.status,
};
let (connector_status, disabled) =
connector_status_and_disabled_validation.validate_status_and_disabled()?;
let pm_auth_config_validation = PMAuthConfigValidation {
connector_type: &self.connector_type,
pm_auth_config: &self.pm_auth_config,
db: state.store.as_ref(),
merchant_id: merchant_context.get_merchant_account().get_id(),
profile_id: &mca.profile_id.clone(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
};
pm_auth_config_validation.validate_pm_auth_config().await?;
let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data {
Some(
process_open_banking_connectors(
state,
merchant_context.get_merchant_account().get_id(),
&auth,
&self.connector_type,
&mca.connector_name,
types::AdditionalMerchantData::foreign_from(data.clone()),
merchant_context.get_merchant_key_store(),
)
.await?,
)
} else {
None
}
.map(|data| {
serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData(
data,
))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
let encrypted_data = domain_types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain_types::CryptoOperation::BatchEncrypt(
UpdateEncryptableMerchantConnectorAccount::to_encryptable(
UpdateEncryptableMerchantConnectorAccount {
connector_account_details: self.connector_account_details,
connector_wallets_details:
helpers::get_connector_wallets_details_with_apple_pay_certificates(
&self.metadata,
&self.connector_wallets_details,
)
.await?,
additional_merchant_data: merchant_recipient_data.map(Secret::new),
},
),
),
km_types::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details".to_string())?;
let encrypted_data =
UpdateEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details")?;
let feature_metadata = self
.feature_metadata
.as_ref()
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
Ok(storage::MerchantConnectorAccountUpdate::Update {
connector_type: Some(self.connector_type),
connector_label: self.connector_label.clone(),
connector_account_details: Box::new(encrypted_data.connector_account_details),
disabled,
payment_methods_enabled,
metadata: self.metadata,
frm_configs,
connector_webhook_details: match &self.connector_webhook_details {
Some(connector_webhook_details) => Box::new(
connector_webhook_details
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(Some)?
.map(Secret::new),
),
None => Box::new(None),
},
applepay_verified_domains: None,
pm_auth_config: Box::new(self.pm_auth_config),
status: Some(connector_status),
additional_merchant_data: Box::new(encrypted_data.additional_merchant_data),
connector_wallets_details: Box::new(encrypted_data.connector_wallets_details),
feature_metadata: Box::new(feature_metadata),
})
}
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[async_trait::async_trait]
impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectorUpdate {
async fn get_merchant_connector_account_from_id(
self,
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &id_type::MerchantConnectorAccountId,
key_store: &domain::MerchantKeyStore,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount> {
db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)
}
async fn create_domain_model_from_request(
self,
state: &SessionState,
mca: &domain::MerchantConnectorAccount,
key_manager_state: &KeyManagerState,
merchant_context: &domain::MerchantContext,
) -> RouterResult<domain::MerchantConnectorAccountUpdate> {
let payment_methods_enabled = self.payment_methods_enabled.map(|pm_enabled| {
pm_enabled
.iter()
.flat_map(Encode::encode_to_value)
.map(Secret::new)
.collect::<Vec<pii::SecretSerdeValue>>()
});
let frm_configs = get_frm_config_as_secret(self.frm_configs);
let auth: types::ConnectorAuthType = self
.connector_account_details
.clone()
.unwrap_or(mca.connector_account_details.clone().into_inner())
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_account_details".to_string(),
expected_format: "auth_type and api_key".to_string(),
})?;
let metadata = self.metadata.clone().or(mca.metadata.clone());
let connector_name = mca.connector_name.as_ref();
let connector_enum = api_models::enums::Connector::from_str(connector_name)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector_name:?}")
})?;
let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation {
connector_name: &connector_enum,
auth_type: &auth,
connector_meta_data: &metadata,
};
connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?;
let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation {
status: &self.status,
disabled: &self.disabled,
auth: &auth,
current_status: &mca.status,
};
let (connector_status, disabled) =
connector_status_and_disabled_validation.validate_status_and_disabled()?;
if self.connector_type != api_enums::ConnectorType::PaymentMethodAuth {
if let Some(val) = self.pm_auth_config.clone() {
validate_pm_auth(
val,
state,
merchant_context.get_merchant_account().get_id(),
merchant_context.clone(),
&mca.profile_id,
)
.await?;
}
}
let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data {
Some(
process_open_banking_connectors(
state,
merchant_context.get_merchant_account().get_id(),
&auth,
&self.connector_type,
&connector_enum,
types::AdditionalMerchantData::foreign_from(data.clone()),
merchant_context.get_merchant_key_store(),
)
.await?,
)
} else {
None
}
.map(|data| {
serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData(
data,
))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
let encrypted_data = domain_types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain_types::CryptoOperation::BatchEncrypt(
UpdateEncryptableMerchantConnectorAccount::to_encryptable(
UpdateEncryptableMerchantConnectorAccount {
connector_account_details: self.connector_account_details,
connector_wallets_details:
helpers::get_connector_wallets_details_with_apple_pay_certificates(
&self.metadata,
&self.connector_wallets_details,
)
.await?,
additional_merchant_data: merchant_recipient_data.map(Secret::new),
},
),
),
km_types::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details".to_string())?;
let encrypted_data =
UpdateEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details")?;
Ok(storage::MerchantConnectorAccountUpdate::Update {
connector_type: Some(self.connector_type),
connector_name: None,
merchant_connector_id: None,
connector_label: self.connector_label.clone(),
connector_account_details: Box::new(encrypted_data.connector_account_details),
test_mode: self.test_mode,
disabled,
payment_methods_enabled,
metadata: self.metadata,
frm_configs,
connector_webhook_details: match &self.connector_webhook_details {
Some(connector_webhook_details) => Box::new(
connector_webhook_details
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.map(Some)?
.map(Secret::new),
),
None => Box::new(None),
},
applepay_verified_domains: None,
pm_auth_config: Box::new(self.pm_auth_config),
status: Some(connector_status),
additional_merchant_data: Box::new(encrypted_data.additional_merchant_data),
connector_wallets_details: Box::new(encrypted_data.connector_wallets_details),
})
}
}
#[cfg(any(feature = "v1", feature = "v2", feature = "olap"))]
#[async_trait::async_trait]
trait MerchantConnectorAccountCreateBridge {
async fn create_domain_model_from_request(
self,
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: &domain::Profile,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount>;
async fn validate_and_get_business_profile(
self,
merchant_context: &domain::MerchantContext,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::Profile>;
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[async_trait::async_trait]
impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
async fn create_domain_model_from_request(
self,
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: &domain::Profile,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount> {
// If connector label is not passed in the request, generate one
let connector_label = self.get_connector_label(business_profile.profile_name.clone());
let frm_configs = self.get_frm_config_as_secret();
let payment_methods_enabled = self.payment_methods_enabled;
// Validate Merchant api details and return error if not in correct format
let auth = types::ConnectorAuthType::from_option_secret_value(
self.connector_account_details.clone(),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_account_details".to_string(),
expected_format: "auth_type and api_key".to_string(),
})?;
let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation {
connector_name: &self.connector_name,
auth_type: &auth,
connector_meta_data: &self.metadata,
};
connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?;
let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation {
status: &self.status,
disabled: &self.disabled,
auth: &auth,
current_status: &api_enums::ConnectorStatus::Active,
};
let (connector_status, disabled) =
connector_status_and_disabled_validation.validate_status_and_disabled()?;
let identifier = km_types::Identifier::Merchant(business_profile.merchant_id.clone());
let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data {
Some(
process_open_banking_connectors(
state,
&business_profile.merchant_id,
&auth,
&self.connector_type,
&self.connector_name,
types::AdditionalMerchantData::foreign_from(data.clone()),
&key_store,
)
.await?,
)
} else {
None
}
.map(|data| {
serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData(
data,
))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
let encrypted_data = domain_types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain_types::CryptoOperation::BatchEncrypt(
FromRequestEncryptableMerchantConnectorAccount::to_encryptable(
FromRequestEncryptableMerchantConnectorAccount {
connector_account_details: self.connector_account_details.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector_account_details",
},
)?,
connector_wallets_details:
helpers::get_connector_wallets_details_with_apple_pay_certificates(
&self.metadata,
&self.connector_wallets_details,
)
.await?,
additional_merchant_data: merchant_recipient_data.map(Secret::new),
},
),
),
identifier.clone(),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details".to_string())?;
let encrypted_data =
FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details")?;
let feature_metadata = self
.feature_metadata
.as_ref()
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
Ok(domain::MerchantConnectorAccount {
merchant_id: business_profile.merchant_id.clone(),
connector_type: self.connector_type,
connector_name: self.connector_name,
connector_account_details: encrypted_data.connector_account_details,
payment_methods_enabled,
disabled,
metadata: self.metadata.clone(),
frm_configs,
connector_label: Some(connector_label.clone()),
created_at: date_time::now(),
modified_at: date_time::now(),
id: common_utils::generate_merchant_connector_account_id_of_default_length(),
connector_webhook_details: match self.connector_webhook_details {
Some(connector_webhook_details) => {
connector_webhook_details.encode_to_value(
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id))
.map(Some)?
.map(Secret::new)
}
None => None,
},
profile_id: business_profile.get_id().to_owned(),
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config.clone(),
status: connector_status,
connector_wallets_details: encrypted_data.connector_wallets_details,
additional_merchant_data: encrypted_data.additional_merchant_data,
version: common_types::consts::API_VERSION,
feature_metadata,
})
}
async fn validate_and_get_business_profile(
self,
merchant_context: &domain::MerchantContext,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::Profile> {
let profile_id = self.profile_id;
// Check whether this profile belongs to the merchant
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(business_profile)
}
}
#[cfg(feature = "v1")]
struct PaymentMethodsEnabled<'a> {
payment_methods_enabled: &'a Option<Vec<api_models::admin::PaymentMethodsEnabled>>,
}
#[cfg(feature = "v1")]
impl PaymentMethodsEnabled<'_> {
fn get_payment_methods_enabled(&self) -> RouterResult<Option<Vec<pii::SecretSerdeValue>>> {
let mut vec = Vec::new();
let payment_methods_enabled = match self.payment_methods_enabled.clone() {
Some(val) => {
for pm in val.into_iter() {
let pm_value = pm
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed while encoding to serde_json::Value, PaymentMethod",
)?;
vec.push(Secret::new(pm_value))
}
Some(vec)
}
None => None,
};
Ok(payment_methods_enabled)
}
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[async_trait::async_trait]
impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
async fn create_domain_model_from_request(
self,
state: &SessionState,
key_store: domain::MerchantKeyStore,
business_profile: &domain::Profile,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::MerchantConnectorAccount> {
// If connector label is not passed in the request, generate one
let connector_label = self
.connector_label
.clone()
.or(core_utils::get_connector_label(
self.business_country,
self.business_label.as_ref(),
self.business_sub_label.as_ref(),
&self.connector_name.to_string(),
))
.unwrap_or(format!(
"{}_{}",
self.connector_name, business_profile.profile_name
));
let payment_methods_enabled = PaymentMethodsEnabled {
payment_methods_enabled: &self.payment_methods_enabled,
};
let payment_methods_enabled = payment_methods_enabled.get_payment_methods_enabled()?;
let frm_configs = self.get_frm_config_as_secret();
// Validate Merchant api details and return error if not in correct format
let auth = types::ConnectorAuthType::from_option_secret_value(
self.connector_account_details.clone(),
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_account_details".to_string(),
expected_format: "auth_type and api_key".to_string(),
})?;
let connector_auth_type_and_metadata_validation = ConnectorAuthTypeAndMetadataValidation {
connector_name: &self.connector_name,
auth_type: &auth,
connector_meta_data: &self.metadata,
};
connector_auth_type_and_metadata_validation.validate_auth_and_metadata_type()?;
let connector_status_and_disabled_validation = ConnectorStatusAndDisabledValidation {
status: &self.status,
disabled: &self.disabled,
auth: &auth,
current_status: &api_enums::ConnectorStatus::Active,
};
let (connector_status, disabled) =
connector_status_and_disabled_validation.validate_status_and_disabled()?;
let identifier = km_types::Identifier::Merchant(business_profile.merchant_id.clone());
let merchant_recipient_data = if let Some(data) = &self.additional_merchant_data {
Some(
process_open_banking_connectors(
state,
&business_profile.merchant_id,
&auth,
&self.connector_type,
&self.connector_name,
types::AdditionalMerchantData::foreign_from(data.clone()),
&key_store,
)
.await?,
)
} else {
None
}
.map(|data| {
serde_json::to_value(types::AdditionalMerchantData::OpenBankingRecipientData(
data,
))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantRecipientData")?;
let encrypted_data = domain_types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain_types::CryptoOperation::BatchEncrypt(
FromRequestEncryptableMerchantConnectorAccount::to_encryptable(
FromRequestEncryptableMerchantConnectorAccount {
connector_account_details: self.connector_account_details.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector_account_details",
},
)?,
connector_wallets_details:
helpers::get_connector_wallets_details_with_apple_pay_certificates(
&self.metadata,
&self.connector_wallets_details,
)
.await?,
additional_merchant_data: merchant_recipient_data.map(Secret::new),
},
),
),
identifier.clone(),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details".to_string())?;
let encrypted_data =
FromRequestEncryptableMerchantConnectorAccount::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while decrypting connector account details")?;
Ok(domain::MerchantConnectorAccount {
merchant_id: business_profile.merchant_id.clone(),
connector_type: self.connector_type,
connector_name: self.connector_name.to_string(),
merchant_connector_id: common_utils::generate_merchant_connector_account_id_of_default_length(),
connector_account_details: encrypted_data.connector_account_details,
payment_methods_enabled,
disabled,
metadata: self.metadata.clone(),
frm_configs,
connector_label: Some(connector_label.clone()),
created_at: date_time::now(),
modified_at: date_time::now(),
connector_webhook_details: match self.connector_webhook_details {
Some(connector_webhook_details) => {
connector_webhook_details.encode_to_value(
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", business_profile.merchant_id))
.map(Some)?
.map(Secret::new)
}
None => None,
},
profile_id: business_profile.get_id().to_owned(),
applepay_verified_domains: None,
pm_auth_config: self.pm_auth_config.clone(),
status: connector_status,
connector_wallets_details: encrypted_data.connector_wallets_details,
test_mode: self.test_mode,
business_country: self.business_country,
business_label: self.business_label.clone(),
business_sub_label: self.business_sub_label.clone(),
additional_merchant_data: encrypted_data.additional_merchant_data,
version: common_types::consts::API_VERSION,
})
}
/// If profile_id is not passed, use default profile if available, or
/// If business_details (business_country and business_label) are passed, get the business_profile
/// or return a `MissingRequiredField` error
async fn validate_and_get_business_profile(
self,
merchant_context: &domain::MerchantContext,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
) -> RouterResult<domain::Profile> {
match self.profile_id.or(merchant_context
.get_merchant_account()
.default_profile
.clone())
{
Some(profile_id) => {
// Check whether this business profile belongs to the merchant
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(business_profile)
}
None => match self.business_country.zip(self.business_label) {
Some((business_country, business_label)) => {
let profile_name = format!("{business_country}_{business_label}");
let business_profile = db
.find_business_profile_by_profile_name_merchant_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_name,
merchant_context.get_merchant_account().get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_name,
})?;
Ok(business_profile)
}
_ => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id or business_country, business_label"
})),
},
}
}
}
pub async fn create_connector(
state: SessionState,
req: api::MerchantConnectorCreate,
merchant_context: domain::MerchantContext,
auth_profile_id: Option<id_type::ProfileId>,
) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
#[cfg(feature = "dummy_connector")]
fp_utils::when(
req.connector_name
.validate_dummy_connector_create(state.conf.dummy_connector.enabled),
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector name".to_string(),
})
},
)?;
let connector_metadata = ConnectorMetadata {
connector_metadata: &req.metadata,
};
let merchant_id = merchant_context.get_merchant_account().get_id();
connector_metadata.validate_apple_pay_certificates_in_mca_metadata()?;
#[cfg(feature = "v1")]
helpers::validate_business_details(
req.business_country,
req.business_label.as_ref(),
&merchant_context,
)?;
let business_profile = req
.clone()
.validate_and_get_business_profile(&merchant_context, store, key_manager_state)
.await?;
#[cfg(feature = "v2")]
if req.connector_type == common_enums::ConnectorType::BillingProcessor {
let profile_wrapper = ProfileWrapper::new(business_profile.clone());
profile_wrapper
.update_revenue_recovery_algorithm_under_profile(
store,
key_manager_state,
merchant_context.get_merchant_key_store(),
common_enums::RevenueRecoveryAlgorithmType::Monitoring,
)
.await?;
}
core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &business_profile)?;
let pm_auth_config_validation = PMAuthConfigValidation {
connector_type: &req.connector_type,
pm_auth_config: &req.pm_auth_config,
db: store,
merchant_id,
profile_id: business_profile.get_id(),
key_store: merchant_context.get_merchant_key_store(),
key_manager_state,
};
pm_auth_config_validation.validate_pm_auth_config().await?;
let connector_type_and_connector_enum = ConnectorTypeAndConnectorName {
connector_type: &req.connector_type,
connector_name: &req.connector_name,
};
let routable_connector = connector_type_and_connector_enum.get_routable_connector()?;
// The purpose of this merchant account update is just to update the
// merchant account `modified_at` field for KGraph cache invalidation
state
.store
.update_specific_fields_in_merchant(
key_manager_state,
merchant_id,
storage::MerchantAccountUpdate::ModifiedAtUpdate,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error updating the merchant account when creating payment connector")?;
let merchant_connector_account = req
.clone()
.create_domain_model_from_request(
&state,
merchant_context.get_merchant_key_store().clone(),
&business_profile,
key_manager_state,
)
.await?;
let mca = state
.store
.insert_merchant_connector_account(
key_manager_state,
merchant_connector_account.clone(),
merchant_context.get_merchant_key_store(),
)
.await
.to_duplicate_response(
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
profile_id: business_profile.get_id().get_string_repr().to_owned(),
connector_label: merchant_connector_account
.connector_label
.unwrap_or_default(),
},
)?;
// redact cgraph cache on new connector creation
redact_cgraph_cache(&state, merchant_id, business_profile.get_id()).await?;
#[cfg(feature = "v1")]
disputes::schedule_dispute_sync_task(&state, &business_profile, &mca).await?;
#[cfg(feature = "v1")]
//update merchant default config
let merchant_default_config_update = MerchantDefaultConfigUpdate {
routable_connector: &routable_connector,
merchant_connector_id: &mca.get_id(),
store,
merchant_id,
profile_id: business_profile.get_id(),
transaction_type: &req.get_transaction_type(),
};
#[cfg(feature = "v2")]
//update merchant default config
let merchant_default_config_update = DefaultFallbackRoutingConfigUpdate {
routable_connector: &routable_connector,
merchant_connector_id: &mca.get_id(),
store,
business_profile,
key_store: merchant_context.get_merchant_key_store().to_owned(),
key_manager_state,
};
merchant_default_config_update
.retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists()
.await?;
metrics::MCA_CREATE.add(
1,
router_env::metric_attributes!(
("connector", req.connector_name.to_string()),
("merchant", merchant_id.clone()),
),
);
let mca_response = mca.foreign_try_into()?;
Ok(service_api::ApplicationResponse::Json(mca_response))
}
#[cfg(feature = "v1")]
async fn validate_pm_auth(
val: pii::SecretSerdeValue,
state: &SessionState,
merchant_id: &id_type::MerchantId,
merchant_context: domain::MerchantContext,
profile_id: &id_type::ProfileId,
) -> RouterResponse<()> {
let config =
serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(val.expose())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "invalid data received for payment method auth config".to_string(),
})
.attach_printable("Failed to deserialize Payment Method Auth config")?;
let all_mcas = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_id,
true,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_context
.get_merchant_account()
.get_id()
.get_string_repr()
.to_owned(),
})?;
for conn_choice in config.enabled_payment_methods {
let pm_auth_mca = all_mcas
.iter()
.find(|mca| mca.get_id() == conn_choice.mca_id)
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector account not found".to_string(),
})?;
if &pm_auth_mca.profile_id != profile_id {
return Err(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method auth profile_id differs from connector profile_id"
.to_string(),
}
.into());
}
}
Ok(services::ApplicationResponse::StatusOk)
}
#[cfg(feature = "v1")]
pub async fn retrieve_connector(
state: SessionState,
merchant_id: id_type::MerchantId,
profile_id: Option<id_type::ProfileId>,
merchant_connector_id: id_type::MerchantConnectorAccountId,
) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let _merchant_account = store
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let mca = store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&merchant_id,
&merchant_connector_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
})?;
core_utils::validate_profile_id_from_auth_layer(profile_id, &mca)?;
Ok(service_api::ApplicationResponse::Json(
mca.foreign_try_into()?,
))
}
#[cfg(feature = "v2")]
pub async fn retrieve_connector(
state: SessionState,
merchant_context: domain::MerchantContext,
id: id_type::MerchantConnectorAccountId,
) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let mca = store
.find_merchant_connector_account_by_id(
key_manager_state,
&id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: id.clone().get_string_repr().to_string(),
})?;
// Validate if the merchant_id sent in the request is valid
if mca.merchant_id != *merchant_id {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Invalid merchant_id {} provided for merchant_connector_account {:?}",
merchant_id.get_string_repr(),
id
),
}
.into());
}
Ok(service_api::ApplicationResponse::Json(
mca.foreign_try_into()?,
))
}
#[cfg(all(feature = "olap", feature = "v2"))]
pub async fn list_connectors_for_a_profile(
state: SessionState,
key_store: domain::MerchantKeyStore,
profile_id: id_type::ProfileId,
) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_connector_accounts = store
.list_connector_account_by_profile_id(key_manager_state, &profile_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let mut response = vec![];
for mca in merchant_connector_accounts.into_iter() {
response.push(mca.foreign_try_into()?);
}
Ok(service_api::ApplicationResponse::Json(response))
}
pub async fn list_payment_connectors(
state: SessionState,
merchant_id: id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
// Validate merchant account
store
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_connector_accounts = store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
&merchant_id,
true,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let merchant_connector_accounts = core_utils::filter_objects_based_on_profile_id_list(
profile_id_list,
merchant_connector_accounts,
);
let mut response = vec![];
// The can be eliminated once [#79711](https://github.com/rust-lang/rust/issues/79711) is stabilized
for mca in merchant_connector_accounts.into_iter() {
response.push(mca.foreign_try_into()?);
}
Ok(service_api::ApplicationResponse::Json(response))
}
pub async fn update_connector(
state: SessionState,
merchant_id: &id_type::MerchantId,
profile_id: Option<id_type::ProfileId>,
merchant_connector_id: &id_type::MerchantConnectorAccountId,
req: api_models::admin::MerchantConnectorUpdate,
) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let mca = req
.clone()
.get_merchant_connector_account_from_id(
db,
merchant_id,
merchant_connector_id,
&key_store,
key_manager_state,
)
.await?;
core_utils::validate_profile_id_from_auth_layer(profile_id, &mca)?;
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
let payment_connector = req
.clone()
.create_domain_model_from_request(&state, &mca, key_manager_state, &merchant_context)
.await?;
// Profile id should always be present
let profile_id = mca.profile_id.clone();
let request_connector_label = req.connector_label;
let updated_mca = db
.update_merchant_connector_account(
key_manager_state,
mca.clone(),
payment_connector.into(),
&key_store,
)
.await
.change_context(
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
profile_id: profile_id.get_string_repr().to_owned(),
connector_label: request_connector_label.unwrap_or_default(),
},
)
.attach_printable_lazy(|| {
format!(
"Failed while updating MerchantConnectorAccount: id: {merchant_connector_id:?}",
)
})?;
// redact cgraph cache on connector updation
redact_cgraph_cache(&state, merchant_id, &profile_id).await?;
// redact routing cache on connector updation
#[cfg(feature = "v1")]
let merchant_config = MerchantDefaultConfigUpdate {
routable_connector: &Some(
common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| {
errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector_name",
}
})?,
),
merchant_connector_id: &mca.get_id(),
store: db,
merchant_id,
profile_id: &mca.profile_id,
transaction_type: &mca.connector_type.into(),
};
#[cfg(feature = "v1")]
if req.disabled.unwrap_or(false) {
merchant_config
.retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists()
.await?;
} else {
merchant_config
.retrieve_and_update_default_fallback_routing_algorithm_if_routable_connector_exists()
.await?;
}
let response = updated_mca.foreign_try_into()?;
Ok(service_api::ApplicationResponse::Json(response))
}
#[cfg(feature = "v1")]
pub async fn delete_connector(
state: SessionState,
merchant_id: id_type::MerchantId,
merchant_connector_id: id_type::MerchantConnectorAccountId,
) -> RouterResponse<api::MerchantConnectorDeleteResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let _merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&merchant_id,
&merchant_connector_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
})?;
let is_deleted = db
.delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&merchant_id,
&merchant_connector_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
})?;
// delete the mca from the config as well
let merchant_default_config_delete = MerchantDefaultConfigUpdate {
routable_connector: &Some(
common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| {
errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector_name",
}
})?,
),
merchant_connector_id: &mca.get_id(),
store: db,
merchant_id: &merchant_id,
profile_id: &mca.profile_id,
transaction_type: &mca.connector_type.into(),
};
merchant_default_config_delete
.retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists()
.await?;
// redact cgraph cache on connector deletion
redact_cgraph_cache(&state, &merchant_id, &mca.profile_id).await?;
let response = api::MerchantConnectorDeleteResponse {
merchant_id,
merchant_connector_id,
deleted: is_deleted,
};
Ok(service_api::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn delete_connector(
state: SessionState,
merchant_context: domain::MerchantContext,
id: id_type::MerchantConnectorAccountId,
) -> RouterResponse<api::MerchantConnectorDeleteResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
&id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: id.clone().get_string_repr().to_string(),
})?;
// Validate if the merchant_id sent in the request is valid
if mca.merchant_id != *merchant_id {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Invalid merchant_id {} provided for merchant_connector_account {:?}",
merchant_id.get_string_repr(),
id
),
}
.into());
}
let is_deleted = db
.delete_merchant_connector_account_by_id(&id)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: id.clone().get_string_repr().to_string(),
})?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&mca.profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: mca.profile_id.get_string_repr().to_owned(),
})?;
let merchant_default_config_delete = DefaultFallbackRoutingConfigUpdate {
routable_connector: &Some(
common_enums::RoutableConnectors::from_str(&mca.connector_name.to_string()).map_err(
|_| errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector_name",
},
)?,
),
merchant_connector_id: &mca.get_id(),
store: db,
business_profile,
key_store: merchant_context.get_merchant_key_store().to_owned(),
key_manager_state,
};
merchant_default_config_delete
.retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists()
.await?;
let response = api::MerchantConnectorDeleteResponse {
merchant_id: merchant_id.clone(),
id,
deleted: is_deleted,
};
Ok(service_api::ApplicationResponse::Json(response))
}
pub async fn kv_for_merchant(
state: SessionState,
merchant_id: id_type::MerchantId,
enable: bool,
) -> RouterResponse<api_models::admin::ToggleKVResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
// check if the merchant account exists
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let updated_merchant_account = match (enable, merchant_account.storage_scheme) {
(true, MerchantStorageScheme::RedisKv) | (false, MerchantStorageScheme::PostgresOnly) => {
Ok(merchant_account)
}
(true, MerchantStorageScheme::PostgresOnly) => {
if state.conf.as_ref().is_kv_soft_kill_mode() {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Kv cannot be enabled when application is in soft_kill_mode"
.to_owned(),
})?
}
db.update_merchant(
key_manager_state,
merchant_account,
storage::MerchantAccountUpdate::StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme::RedisKv,
},
&key_store,
)
.await
}
(false, MerchantStorageScheme::RedisKv) => {
db.update_merchant(
key_manager_state,
merchant_account,
storage::MerchantAccountUpdate::StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme::PostgresOnly,
},
&key_store,
)
.await
}
}
.map_err(|error| {
error
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to switch merchant_storage_scheme")
})?;
let kv_status = matches!(
updated_merchant_account.storage_scheme,
MerchantStorageScheme::RedisKv
);
Ok(service_api::ApplicationResponse::Json(
api_models::admin::ToggleKVResponse {
merchant_id: updated_merchant_account.get_id().to_owned(),
kv_enabled: kv_status,
},
))
}
pub async fn toggle_kv_for_all_merchants(
state: SessionState,
enable: bool,
) -> RouterResponse<api_models::admin::ToggleAllKVResponse> {
let db = state.store.as_ref();
let storage_scheme = if enable {
MerchantStorageScheme::RedisKv
} else {
MerchantStorageScheme::PostgresOnly
};
let total_update = db
.update_all_merchant_account(storage::MerchantAccountUpdate::StorageSchemeUpdate {
storage_scheme,
})
.await
.map_err(|error| {
error
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to switch merchant_storage_scheme for all merchants")
})?;
Ok(service_api::ApplicationResponse::Json(
api_models::admin::ToggleAllKVResponse {
total_updated: total_update,
kv_enabled: enable,
},
))
}
pub async fn check_merchant_account_kv_status(
state: SessionState,
merchant_id: id_type::MerchantId,
) -> RouterResponse<api_models::admin::ToggleKVResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
// check if the merchant account exists
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let kv_status = matches!(
merchant_account.storage_scheme,
MerchantStorageScheme::RedisKv
);
Ok(service_api::ApplicationResponse::Json(
api_models::admin::ToggleKVResponse {
merchant_id: merchant_account.get_id().to_owned(),
kv_enabled: kv_status,
},
))
}
pub fn get_frm_config_as_secret(
frm_configs: Option<Vec<api_models::admin::FrmConfigs>>,
) -> Option<Vec<Secret<serde_json::Value>>> {
match frm_configs.as_ref() {
Some(frm_value) => {
let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value
.iter()
.map(|config| {
config
.encode_to_value()
.change_context(errors::ApiErrorResponse::ConfigNotFound)
.map(Secret::new)
})
.collect::<Result<Vec<_>, _>>()
.ok()?;
Some(configs_for_frm_value)
}
None => None,
}
}
#[cfg(feature = "v1")]
pub async fn create_and_insert_business_profile(
state: &SessionState,
request: api::ProfileCreate,
merchant_account: domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<domain::Profile> {
let business_profile_new =
admin::create_profile_from_merchant_account(state, merchant_account, request, key_store)
.await?;
let profile_name = business_profile_new.profile_name.clone();
state
.store
.insert_business_profile(&state.into(), key_store, business_profile_new)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: format!(
"Business Profile with the profile_name {profile_name} already exists"
),
})
.attach_printable("Failed to insert Business profile because of duplication error")
}
#[cfg(feature = "olap")]
#[async_trait::async_trait]
trait ProfileCreateBridge {
#[cfg(feature = "v1")]
async fn create_domain_model_from_request(
self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
) -> RouterResult<domain::Profile>;
#[cfg(feature = "v2")]
async fn create_domain_model_from_request(
self,
state: &SessionState,
key: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
) -> RouterResult<domain::Profile>;
}
#[cfg(feature = "olap")]
#[async_trait::async_trait]
impl ProfileCreateBridge for api::ProfileCreate {
#[cfg(feature = "v1")]
async fn create_domain_model_from_request(
self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
) -> RouterResult<domain::Profile> {
use common_utils::ext_traits::AsyncExt;
if let Some(session_expiry) = &self.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
if let Some(intent_fulfillment_expiry) = self.intent_fulfillment_time {
helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry)?;
}
if let Some(ref routing_algorithm) = self.routing_algorithm {
let _: api_models::routing::StaticRoutingAlgorithm = routing_algorithm
.clone()
.parse_value("RoutingAlgorithm")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "routing_algorithm",
})
.attach_printable("Invalid routing algorithm given")?;
}
// Generate a unique profile id
let profile_id = common_utils::generate_profile_id_of_default_length();
let profile_name = self.profile_name.unwrap_or("default".to_string());
let current_time = date_time::now();
let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);
let payment_response_hash_key = self
.payment_response_hash_key
.or(merchant_context
.get_merchant_account()
.payment_response_hash_key
.clone())
.unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64));
let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into);
let key_manager_state = state.into();
let outgoing_webhook_custom_http_headers = self
.outgoing_webhook_custom_http_headers
.async_map(|headers| {
cards::create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
headers,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?;
let payout_link_config = self
.payout_link_config
.map(|payout_conf| match payout_conf.config.validate() {
Ok(_) => Ok(payout_conf.foreign_into()),
Err(e) => Err(error_stack::report!(
errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string()
}
)),
})
.transpose()?;
let key = merchant_context
.get_merchant_key_store()
.key
.clone()
.into_inner();
let key_manager_state = state.into();
let card_testing_secret_key = Some(Secret::new(utils::generate_id(
consts::FINGERPRINT_SECRET_LENGTH,
"fs",
)));
let card_testing_guard_config = self
.card_testing_guard_config
.map(CardTestingGuardConfig::foreign_from)
.or(Some(CardTestingGuardConfig::default()));
let mut dynamic_routing_algorithm_ref =
routing_types::DynamicRoutingAlgorithmRef::default();
if self.is_debit_routing_enabled == Some(true) {
routing::helpers::create_merchant_in_decision_engine_if_not_exists(
state,
&profile_id,
&mut dynamic_routing_algorithm_ref,
)
.await;
}
let dynamic_routing_algorithm = serde_json::to_value(dynamic_routing_algorithm_ref)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error serializing dynamic_routing_algorithm_ref to JSON Value")?;
self.merchant_country_code
.as_ref()
.map(|country_code| country_code.validate_and_get_country_from_merchant_country_code())
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid merchant country code".to_string(),
})?;
Ok(domain::Profile::from(domain::ProfileSetter {
profile_id,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
profile_name,
created_at: current_time,
modified_at: current_time,
return_url: self
.return_url
.map(|return_url| return_url.to_string())
.or(merchant_context.get_merchant_account().return_url.clone()),
enable_payment_response_hash: self.enable_payment_response_hash.unwrap_or(
merchant_context
.get_merchant_account()
.enable_payment_response_hash,
),
payment_response_hash_key: Some(payment_response_hash_key),
redirect_to_merchant_with_http_post: self
.redirect_to_merchant_with_http_post
.unwrap_or(
merchant_context
.get_merchant_account()
.redirect_to_merchant_with_http_post,
),
webhook_details: webhook_details.or(merchant_context
.get_merchant_account()
.webhook_details
.clone()),
metadata: self.metadata,
routing_algorithm: None,
intent_fulfillment_time: self
.intent_fulfillment_time
.map(i64::from)
.or(merchant_context
.get_merchant_account()
.intent_fulfillment_time)
.or(Some(common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME)),
frm_routing_algorithm: self.frm_routing_algorithm.or(merchant_context
.get_merchant_account()
.frm_routing_algorithm
.clone()),
#[cfg(feature = "payouts")]
payout_routing_algorithm: self.payout_routing_algorithm.or(merchant_context
.get_merchant_account()
.payout_routing_algorithm
.clone()),
#[cfg(not(feature = "payouts"))]
payout_routing_algorithm: None,
is_recon_enabled: merchant_context.get_merchant_account().is_recon_enabled,
applepay_verified_domains: self.applepay_verified_domains,
payment_link_config,
session_expiry: self
.session_expiry
.map(i64::from)
.or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)),
authentication_connector_details: self
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
use_billing_as_payment_method_billing: self
.use_billing_as_payment_method_billing
.or(Some(true)),
collect_shipping_details_from_wallet_connector: self
.collect_shipping_details_from_wallet_connector
.or(Some(false)),
collect_billing_details_from_wallet_connector: self
.collect_billing_details_from_wallet_connector
.or(Some(false)),
outgoing_webhook_custom_http_headers,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: self.is_tax_connector_enabled,
always_collect_billing_details_from_wallet_connector: self
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
dynamic_routing_algorithm: Some(dynamic_routing_algorithm),
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: self.is_auto_retries_enabled.unwrap_or_default(),
max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from),
always_request_extended_authorization: self.always_request_extended_authorization,
is_click_to_pay_enabled: self.is_click_to_pay_enabled,
authentication_product_ids: self.authentication_product_ids,
card_testing_guard_config,
card_testing_secret_key: card_testing_secret_key
.async_lift(|inner| async {
domain_types::crypto_operation(
&key_manager_state,
common_utils::type_name!(domain::Profile),
domain_types::CryptoOperation::EncryptOptional(inner),
km_types::Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while generating card testing secret key")?,
is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(),
force_3ds_challenge: self.force_3ds_challenge.unwrap_or_default(),
is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(),
merchant_business_country: self.merchant_business_country,
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled: self
.is_pre_network_tokenization_enabled
.unwrap_or_default(),
merchant_category_code: self.merchant_category_code,
merchant_country_code: self.merchant_country_code,
dispute_polling_interval: self.dispute_polling_interval,
is_manual_retry_enabled: self.is_manual_retry_enabled,
always_enable_overcapture: self.always_enable_overcapture,
external_vault_details: domain::ExternalVaultDetails::try_from((
self.is_external_vault_enabled,
self.external_vault_connector_details
.map(ForeignFrom::foreign_from),
))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while generating external vault details")?,
billing_processor_id: self.billing_processor_id,
is_l2_l3_enabled: self.is_l2_l3_enabled.unwrap_or(false),
}))
}
#[cfg(feature = "v2")]
async fn create_domain_model_from_request(
self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
merchant_id: &id_type::MerchantId,
) -> RouterResult<domain::Profile> {
if let Some(session_expiry) = &self.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
// Generate a unique profile id
// TODO: the profile_id should be generated from the profile_name
let profile_id = common_utils::generate_profile_id_of_default_length();
let profile_name = self.profile_name;
let current_time = date_time::now();
let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);
let payment_response_hash_key = self
.payment_response_hash_key
.unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64));
let payment_link_config = self.payment_link_config.map(ForeignInto::foreign_into);
let key_manager_state = state.into();
let outgoing_webhook_custom_http_headers = self
.outgoing_webhook_custom_http_headers
.async_map(|headers| {
cards::create_encrypted_data(&key_manager_state, key_store, headers)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?;
let payout_link_config = self
.payout_link_config
.map(|payout_conf| match payout_conf.config.validate() {
Ok(_) => Ok(payout_conf.foreign_into()),
Err(e) => Err(error_stack::report!(
errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string()
}
)),
})
.transpose()?;
let key = key_store.key.clone().into_inner();
let key_manager_state = state.into();
let card_testing_secret_key = Some(Secret::new(utils::generate_id(
consts::FINGERPRINT_SECRET_LENGTH,
"fs",
)));
let card_testing_guard_config = self
.card_testing_guard_config
.map(CardTestingGuardConfig::foreign_from)
.or(Some(CardTestingGuardConfig::default()));
Ok(domain::Profile::from(domain::ProfileSetter {
id: profile_id,
merchant_id: merchant_id.clone(),
profile_name,
created_at: current_time,
modified_at: current_time,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash.unwrap_or(true),
payment_response_hash_key: Some(payment_response_hash_key),
redirect_to_merchant_with_http_post: self
.redirect_to_merchant_with_http_post
.unwrap_or(true),
webhook_details,
metadata: self.metadata,
is_recon_enabled: false,
applepay_verified_domains: self.applepay_verified_domains,
payment_link_config,
session_expiry: self
.session_expiry
.map(i64::from)
.or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)),
authentication_connector_details: self
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
use_billing_as_payment_method_billing: self
.use_billing_as_payment_method_billing
.or(Some(true)),
collect_shipping_details_from_wallet_connector: self
.collect_shipping_details_from_wallet_connector_if_required
.or(Some(false)),
collect_billing_details_from_wallet_connector: self
.collect_billing_details_from_wallet_connector_if_required
.or(Some(false)),
outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector: self
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
routing_algorithm_id: None,
frm_routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: self
.order_fulfillment_time
.map(|order_fulfillment_time| order_fulfillment_time.into_inner())
.or(Some(common_utils::consts::DEFAULT_ORDER_FULFILLMENT_TIME)),
order_fulfillment_time_origin: self.order_fulfillment_time_origin,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: self.is_tax_connector_enabled,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_click_to_pay_enabled: self.is_click_to_pay_enabled,
authentication_product_ids: self.authentication_product_ids,
three_ds_decision_manager_config: None,
card_testing_guard_config,
card_testing_secret_key: card_testing_secret_key
.async_lift(|inner| async {
domain_types::crypto_operation(
&key_manager_state,
common_utils::type_name!(domain::Profile),
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
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while generating card testing secret key")?,
is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled.unwrap_or_default(),
is_debit_routing_enabled: self.is_debit_routing_enabled.unwrap_or_default(),
merchant_business_country: self.merchant_business_country,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: self.is_external_vault_enabled,
external_vault_connector_details: self
.external_vault_connector_details
.map(ForeignInto::foreign_into),
merchant_category_code: self.merchant_category_code,
merchant_country_code: self.merchant_country_code,
split_txns_enabled: self.split_txns_enabled.unwrap_or_default(),
billing_processor_id: self.billing_processor_id,
}))
}
}
#[cfg(feature = "olap")]
pub async fn create_profile(
state: SessionState,
request: api::ProfileCreate,
merchant_context: domain::MerchantContext,
) -> RouterResponse<api_models::admin::ProfileResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
#[cfg(feature = "v1")]
let business_profile = request
.create_domain_model_from_request(&state, &merchant_context)
.await?;
#[cfg(feature = "v2")]
let business_profile = request
.create_domain_model_from_request(
&state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().get_id(),
)
.await?;
let profile_id = business_profile.get_id().to_owned();
let business_profile = db
.insert_business_profile(
key_manager_state,
merchant_context.get_merchant_key_store(),
business_profile,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: format!(
"Business Profile with the profile_id {} already exists",
profile_id.get_string_repr()
),
})
.attach_printable("Failed to insert Business profile because of duplication error")?;
#[cfg(feature = "v1")]
if merchant_context
.get_merchant_account()
.default_profile
.is_some()
{
let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile;
db.update_merchant(
key_manager_state,
merchant_context.get_merchant_account().clone(),
unset_default_profile,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
}
Ok(service_api::ApplicationResponse::Json(
api_models::admin::ProfileResponse::foreign_try_from(business_profile)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse business profile details")?,
))
}
#[cfg(feature = "olap")]
pub async fn list_profile(
state: SessionState,
merchant_id: id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
) -> RouterResponse<Vec<api_models::admin::ProfileResponse>> {
let db = state.store.as_ref();
let key_store = db
.get_merchant_key_store_by_merchant_id(
&(&state).into(),
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let profiles = db
.list_profile_by_merchant_id(&(&state).into(), &key_store, &merchant_id)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?
.clone();
let profiles = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, profiles);
let mut business_profiles = Vec::new();
for profile in profiles {
let business_profile = api_models::admin::ProfileResponse::foreign_try_from(profile)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse business profile details")?;
business_profiles.push(business_profile);
}
Ok(service_api::ApplicationResponse::Json(business_profiles))
}
pub async fn retrieve_profile(
state: SessionState,
profile_id: id_type::ProfileId,
key_store: domain::MerchantKeyStore,
) -> RouterResponse<api_models::admin::ProfileResponse> {
let db = state.store.as_ref();
let business_profile = db
.find_business_profile_by_profile_id(&(&state).into(), &key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(service_api::ApplicationResponse::Json(
api_models::admin::ProfileResponse::foreign_try_from(business_profile)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse business profile details")?,
))
}
pub async fn delete_profile(
state: SessionState,
profile_id: id_type::ProfileId,
merchant_id: &id_type::MerchantId,
) -> RouterResponse<bool> {
let db = state.store.as_ref();
let delete_result = db
.delete_profile_by_profile_id_merchant_id(&profile_id, merchant_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(service_api::ApplicationResponse::Json(delete_result))
}
#[cfg(feature = "olap")]
#[async_trait::async_trait]
trait ProfileUpdateBridge {
async fn get_update_profile_object(
self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
) -> RouterResult<domain::ProfileUpdate>;
}
#[cfg(all(feature = "olap", feature = "v1"))]
#[async_trait::async_trait]
impl ProfileUpdateBridge for api::ProfileUpdate {
async fn get_update_profile_object(
self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
) -> RouterResult<domain::ProfileUpdate> {
if let Some(session_expiry) = &self.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
if let Some(intent_fulfillment_expiry) = self.intent_fulfillment_time {
helpers::validate_intent_fulfillment_expiry(intent_fulfillment_expiry)?;
}
let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);
if let Some(ref routing_algorithm) = self.routing_algorithm {
let _: api_models::routing::StaticRoutingAlgorithm = routing_algorithm
.clone()
.parse_value("RoutingAlgorithm")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "routing_algorithm",
})
.attach_printable("Invalid routing algorithm given")?;
}
let payment_link_config = self
.payment_link_config
.map(|payment_link_conf| match payment_link_conf.validate() {
Ok(_) => Ok(payment_link_conf.foreign_into()),
Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string()
})),
})
.transpose()?;
let extended_card_info_config = self
.extended_card_info_config
.as_ref()
.map(|config| {
config.encode_to_value().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "extended_card_info_config",
},
)
})
.transpose()?
.map(Secret::new);
let key_manager_state = state.into();
let outgoing_webhook_custom_http_headers = self
.outgoing_webhook_custom_http_headers
.async_map(|headers| {
cards::create_encrypted_data(&key_manager_state, key_store, headers)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?;
let payout_link_config = self
.payout_link_config
.map(|payout_conf| match payout_conf.config.validate() {
Ok(_) => Ok(payout_conf.foreign_into()),
Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string()
})),
})
.transpose()?;
let key = key_store.key.clone().into_inner();
let key_manager_state = state.into();
let card_testing_secret_key = match business_profile.card_testing_secret_key {
Some(_) => None,
None => {
let card_testing_secret_key = Some(Secret::new(utils::generate_id(
consts::FINGERPRINT_SECRET_LENGTH,
"fs",
)));
card_testing_secret_key
.async_lift(|inner| async {
domain_types::crypto_operation(
&key_manager_state,
common_utils::type_name!(domain::Profile),
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
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while generating card testing secret key")?
}
};
let dynamic_routing_algo_ref = if self.is_debit_routing_enabled == Some(true) {
let mut dynamic_routing_algo_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();
routing::helpers::create_merchant_in_decision_engine_if_not_exists(
state,
business_profile.get_id(),
&mut dynamic_routing_algo_ref,
)
.await;
let dynamic_routing_algo_ref_value = serde_json::to_value(dynamic_routing_algo_ref)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"error serializing dynamic_routing_algorithm_ref to JSON Value",
)?;
Some(dynamic_routing_algo_ref_value)
} else {
self.dynamic_routing_algorithm
};
self.merchant_country_code
.as_ref()
.map(|country_code| country_code.validate_and_get_country_from_merchant_country_code())
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid merchant country code".to_string(),
})?;
Ok(domain::ProfileUpdate::Update(Box::new(
domain::ProfileGeneralUpdate {
profile_name: self.profile_name,
return_url: self.return_url.map(|return_url| return_url.to_string()),
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
webhook_details,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
intent_fulfillment_time: self.intent_fulfillment_time.map(i64::from),
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,
applepay_verified_domains: self.applepay_verified_domains,
payment_link_config,
session_expiry: self.session_expiry.map(i64::from),
authentication_connector_details: self
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config,
extended_card_info_config,
use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: self
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: self
.collect_billing_details_from_wallet_connector,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector: self
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
always_request_extended_authorization: self.always_request_extended_authorization,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: self.is_tax_connector_enabled,
dynamic_routing_algorithm: dynamic_routing_algo_ref,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: self.is_auto_retries_enabled,
max_auto_retries_enabled: self.max_auto_retries_enabled.map(i16::from),
is_click_to_pay_enabled: self.is_click_to_pay_enabled,
authentication_product_ids: self.authentication_product_ids,
card_testing_guard_config: self
.card_testing_guard_config
.map(ForeignInto::foreign_into),
card_testing_secret_key,
is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled,
force_3ds_challenge: self.force_3ds_challenge,
is_debit_routing_enabled: self.is_debit_routing_enabled,
merchant_business_country: self.merchant_business_country,
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled: self.is_pre_network_tokenization_enabled,
merchant_category_code: self.merchant_category_code,
merchant_country_code: self.merchant_country_code,
dispute_polling_interval: self.dispute_polling_interval,
is_manual_retry_enabled: self.is_manual_retry_enabled,
always_enable_overcapture: self.always_enable_overcapture,
is_external_vault_enabled: self.is_external_vault_enabled,
external_vault_connector_details: self
.external_vault_connector_details
.map(ForeignInto::foreign_into),
billing_processor_id: self.billing_processor_id,
is_l2_l3_enabled: self.is_l2_l3_enabled,
},
)))
}
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[async_trait::async_trait]
impl ProfileUpdateBridge for api::ProfileUpdate {
async fn get_update_profile_object(
self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
) -> RouterResult<domain::ProfileUpdate> {
if let Some(session_expiry) = &self.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
let webhook_details = self.webhook_details.map(ForeignInto::foreign_into);
let payment_link_config = self
.payment_link_config
.map(|payment_link_conf| match payment_link_conf.validate() {
Ok(_) => Ok(payment_link_conf.foreign_into()),
Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string()
})),
})
.transpose()?;
let extended_card_info_config = self
.extended_card_info_config
.as_ref()
.map(|config| {
config.encode_to_value().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "extended_card_info_config",
},
)
})
.transpose()?
.map(Secret::new);
let key_manager_state = state.into();
let outgoing_webhook_custom_http_headers = self
.outgoing_webhook_custom_http_headers
.async_map(|headers| {
cards::create_encrypted_data(&key_manager_state, key_store, headers)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt outgoing webhook custom HTTP headers")?;
let payout_link_config = self
.payout_link_config
.map(|payout_conf| match payout_conf.config.validate() {
Ok(_) => Ok(payout_conf.foreign_into()),
Err(e) => Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: e.to_string()
})),
})
.transpose()?;
let key = key_store.key.clone().into_inner();
let key_manager_state = state.into();
let card_testing_secret_key = match business_profile.card_testing_secret_key {
Some(_) => None,
None => {
let card_testing_secret_key = Some(Secret::new(utils::generate_id(
consts::FINGERPRINT_SECRET_LENGTH,
"fs",
)));
card_testing_secret_key
.async_lift(|inner| async {
domain_types::crypto_operation(
&key_manager_state,
common_utils::type_name!(domain::Profile),
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
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error while generating card testing secret key")?
}
};
let revenue_recovery_retry_algorithm_type = self.revenue_recovery_retry_algorithm_type;
Ok(domain::ProfileUpdate::Update(Box::new(
domain::ProfileGeneralUpdate {
profile_name: self.profile_name,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
webhook_details,
metadata: self.metadata,
applepay_verified_domains: self.applepay_verified_domains,
payment_link_config,
session_expiry: self.session_expiry.map(i64::from),
authentication_connector_details: self
.authentication_connector_details
.map(ForeignInto::foreign_into),
payout_link_config,
extended_card_info_config,
use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: self
.collect_shipping_details_from_wallet_connector_if_required,
collect_billing_details_from_wallet_connector: self
.collect_billing_details_from_wallet_connector_if_required,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
order_fulfillment_time: self
.order_fulfillment_time
.map(|order_fulfillment_time| order_fulfillment_time.into_inner()),
order_fulfillment_time_origin: self.order_fulfillment_time_origin,
always_collect_billing_details_from_wallet_connector: self
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_click_to_pay_enabled: self.is_click_to_pay_enabled,
authentication_product_ids: self.authentication_product_ids,
three_ds_decision_manager_config: None,
card_testing_guard_config: self
.card_testing_guard_config
.map(ForeignInto::foreign_into),
card_testing_secret_key,
is_debit_routing_enabled: self.is_debit_routing_enabled,
merchant_business_country: self.merchant_business_country,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: self.is_external_vault_enabled,
external_vault_connector_details: self
.external_vault_connector_details
.map(ForeignInto::foreign_into),
merchant_category_code: self.merchant_category_code,
merchant_country_code: self.merchant_country_code,
revenue_recovery_retry_algorithm_type,
split_txns_enabled: self.split_txns_enabled,
billing_processor_id: self.billing_processor_id,
},
)))
}
}
#[cfg(feature = "olap")]
pub async fn update_profile(
state: SessionState,
profile_id: &id_type::ProfileId,
key_store: domain::MerchantKeyStore,
request: api::ProfileUpdate,
) -> RouterResponse<api::ProfileResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile = db
.find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let profile_update = request
.get_update_profile_object(&state, &key_store, &business_profile)
.await?;
let updated_business_profile = db
.update_profile_by_profile_id(
key_manager_state,
&key_store,
business_profile,
profile_update,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok(service_api::ApplicationResponse::Json(
api_models::admin::ProfileResponse::foreign_try_from(updated_business_profile)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse business profile details")?,
))
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct ProfileWrapper {
pub profile: domain::Profile,
}
#[cfg(feature = "v2")]
impl ProfileWrapper {
pub fn new(profile: domain::Profile) -> Self {
Self { profile }
}
fn get_routing_config_cache_key(self) -> storage_impl::redis::cache::CacheKind<'static> {
let merchant_id = self.profile.merchant_id.clone();
let profile_id = self.profile.get_id().to_owned();
storage_impl::redis::cache::CacheKind::Routing(
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
.into(),
)
}
pub async fn update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
self,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
algorithm_id: id_type::RoutingId,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()> {
let routing_cache_key = self.clone().get_routing_config_cache_key();
let (routing_algorithm_id, payout_routing_algorithm_id) = match transaction_type {
storage::enums::TransactionType::Payment => (Some(algorithm_id), None),
#[cfg(feature = "payouts")]
storage::enums::TransactionType::Payout => (None, Some(algorithm_id)),
//TODO: Handle ThreeDsAuthentication Transaction Type for Three DS Decision Rule Algorithm configuration
storage::enums::TransactionType::ThreeDsAuthentication => todo!(),
};
let profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate {
routing_algorithm_id,
payout_routing_algorithm_id,
};
let profile = self.profile;
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
profile,
profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in business profile")?;
storage_impl::redis::cache::redact_from_redis_and_publish(
db.get_cache_store().as_ref(),
[routing_cache_key],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate routing cache")?;
Ok(())
}
pub fn get_routing_algorithm_id<'a>(
&'a self,
transaction_data: &'a routing::TransactionData<'_>,
) -> Option<id_type::RoutingId> {
match transaction_data {
routing::TransactionData::Payment(_) => self.profile.routing_algorithm_id.clone(),
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(_) => self.profile.payout_routing_algorithm_id.clone(),
}
}
pub fn get_default_fallback_list_of_connector_under_profile(
&self,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
let fallback_connectors =
if let Some(default_fallback_routing) = self.profile.default_fallback_routing.clone() {
default_fallback_routing
.expose()
.parse_value::<Vec<routing_types::RoutableConnectorChoice>>(
"Vec<RoutableConnectorChoice>",
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Business Profile default config has invalid structure")?
} else {
Vec::new()
};
Ok(fallback_connectors)
}
pub fn get_default_routing_configs_from_profile(
&self,
) -> RouterResult<routing_types::ProfileDefaultRoutingConfig> {
let profile_id = self.profile.get_id().to_owned();
let connectors = self.get_default_fallback_list_of_connector_under_profile()?;
Ok(routing_types::ProfileDefaultRoutingConfig {
profile_id,
connectors,
})
}
pub async fn update_default_fallback_routing_of_connectors_under_profile(
self,
db: &dyn StorageInterface,
updated_config: &Vec<routing_types::RoutableConnectorChoice>,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
let default_fallback_routing = Secret::from(
updated_config
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert routing ref to value")?,
);
let profile_update = domain::ProfileUpdate::DefaultRoutingFallbackUpdate {
default_fallback_routing: Some(default_fallback_routing),
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
self.profile,
profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in business profile")?;
Ok(())
}
pub async fn update_revenue_recovery_algorithm_under_profile(
self,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
revenue_recovery_retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType,
) -> RouterResult<()> {
let recovery_algorithm_data =
diesel_models::business_profile::RevenueRecoveryAlgorithmData {
monitoring_configured_timestamp: date_time::now(),
};
let profile_update = domain::ProfileUpdate::RevenueRecoveryAlgorithmUpdate {
revenue_recovery_retry_algorithm_type,
revenue_recovery_retry_algorithm_data: Some(recovery_algorithm_data),
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
self.profile,
profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to update revenue recovery retry algorithm in business profile",
)?;
Ok(())
}
}
pub async fn extended_card_info_toggle(
state: SessionState,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
ext_card_info_choice: admin_types::ExtendedCardInfoChoice,
) -> RouterResponse<admin_types::ExtendedCardInfoChoice> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the key store by merchant_id")?;
let business_profile = db
.find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
if business_profile.is_extended_card_info_enabled.is_none()
|| business_profile
.is_extended_card_info_enabled
.is_some_and(|existing_config| existing_config != ext_card_info_choice.enabled)
{
let profile_update = domain::ProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled: ext_card_info_choice.enabled,
};
db.update_profile_by_profile_id(
key_manager_state,
&key_store,
business_profile,
profile_update,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
}
Ok(service_api::ApplicationResponse::Json(ext_card_info_choice))
}
pub async fn connector_agnostic_mit_toggle(
state: SessionState,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
connector_agnostic_mit_choice: admin_types::ConnectorAgnosticMitChoice,
) -> RouterResponse<admin_types::ConnectorAgnosticMitChoice> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the key store by merchant_id")?;
let business_profile = db
.find_business_profile_by_profile_id(key_manager_state, &key_store, profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
if business_profile.merchant_id != *merchant_id {
Err(errors::ApiErrorResponse::AccessForbidden {
resource: profile_id.get_string_repr().to_owned(),
})?
}
if business_profile.is_connector_agnostic_mit_enabled
!= Some(connector_agnostic_mit_choice.enabled)
{
let profile_update = domain::ProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled: connector_agnostic_mit_choice.enabled,
};
db.update_profile_by_profile_id(
key_manager_state,
&key_store,
business_profile,
profile_update,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
}
Ok(service_api::ApplicationResponse::Json(
connector_agnostic_mit_choice,
))
}
pub async fn transfer_key_store_to_key_manager(
state: SessionState,
req: admin_types::MerchantKeyTransferRequest,
) -> RouterResponse<admin_types::TransferKeyResponse> {
let resp = transfer_encryption_key(&state, req).await?;
Ok(service_api::ApplicationResponse::Json(
admin_types::TransferKeyResponse {
total_transferred: resp,
},
))
}
async fn process_open_banking_connectors(
state: &SessionState,
merchant_id: &id_type::MerchantId,
auth: &types::ConnectorAuthType,
connector_type: &api_enums::ConnectorType,
connector: &api_enums::Connector,
additional_merchant_data: types::AdditionalMerchantData,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<types::MerchantRecipientData> {
let new_merchant_data = match additional_merchant_data {
types::AdditionalMerchantData::OpenBankingRecipientData(merchant_data) => {
if connector_type != &api_enums::ConnectorType::PaymentProcessor {
return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config:
"OpenBanking connector for Payment Initiation should be a payment processor"
.to_string(),
}
.into());
}
match &merchant_data {
types::MerchantRecipientData::AccountData(acc_data) => {
core_utils::validate_bank_account_data(acc_data)?;
let connector_name = api_enums::Connector::to_string(connector);
let recipient_creation_not_supported = state
.conf
.locker_based_open_banking_connectors
.connector_list
.contains(connector_name.as_str());
let recipient_id = if recipient_creation_not_supported {
locker_recipient_create_call(state, merchant_id, acc_data, key_store).await
} else {
connector_recipient_create_call(
state,
merchant_id,
connector_name,
auth,
acc_data,
)
.await
}
.attach_printable("failed to get recipient_id")?;
let conn_recipient_id = if recipient_creation_not_supported {
Some(types::RecipientIdType::LockerId(Secret::new(recipient_id)))
} else {
Some(types::RecipientIdType::ConnectorId(Secret::new(
recipient_id,
)))
};
let account_data = match &acc_data {
types::MerchantAccountData::Iban { iban, name, .. } => {
types::MerchantAccountData::Iban {
iban: iban.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
}
}
types::MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
} => types::MerchantAccountData::Bacs {
account_number: account_number.clone(),
sort_code: sort_code.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
},
types::MerchantAccountData::FasterPayments {
account_number,
sort_code,
name,
..
} => types::MerchantAccountData::FasterPayments {
account_number: account_number.clone(),
sort_code: sort_code.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
},
types::MerchantAccountData::Sepa { iban, name, .. } => {
types::MerchantAccountData::Sepa {
iban: iban.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
}
}
types::MerchantAccountData::SepaInstant { iban, name, .. } => {
types::MerchantAccountData::SepaInstant {
iban: iban.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
}
}
types::MerchantAccountData::Elixir {
account_number,
iban,
name,
..
} => types::MerchantAccountData::Elixir {
account_number: account_number.clone(),
iban: iban.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
},
types::MerchantAccountData::Bankgiro { number, name, .. } => {
types::MerchantAccountData::Bankgiro {
number: number.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
}
}
types::MerchantAccountData::Plusgiro { number, name, .. } => {
types::MerchantAccountData::Plusgiro {
number: number.clone(),
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
}
}
};
types::MerchantRecipientData::AccountData(account_data)
}
_ => merchant_data.clone(),
}
}
};
Ok(new_merchant_data)
}
async fn connector_recipient_create_call(
state: &SessionState,
merchant_id: &id_type::MerchantId,
connector_name: String,
auth: &types::ConnectorAuthType,
data: &types::MerchantAccountData,
) -> RouterResult<String> {
let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(
connector_name.as_str(),
)?;
let auth = pm_auth_types::ConnectorAuthType::foreign_try_from(auth.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while converting ConnectorAuthType")?;
let connector_integration: pm_auth_types::api::BoxedConnectorIntegration<
'_,
pm_auth_types::api::auth_service::RecipientCreate,
pm_auth_types::RecipientCreateRequest,
pm_auth_types::RecipientCreateResponse,
> = connector.connector.get_connector_integration();
let req = pm_auth_types::RecipientCreateRequest::from(data);
let router_data = pm_auth_types::RecipientCreateRouterData {
flow: std::marker::PhantomData,
merchant_id: Some(merchant_id.to_owned()),
connector: Some(connector_name),
request: req,
response: Err(pm_auth_types::ErrorResponse {
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
code: consts::NO_ERROR_CODE.to_string(),
message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(),
reason: None,
}),
connector_http_status_code: None,
connector_auth_type: auth,
};
let resp = payment_initiation_service::execute_connector_processing_step(
state,
connector_integration,
&router_data,
&connector.connector_name,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while calling recipient create connector api")?;
let recipient_create_resp =
resp.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
let recipient_id = recipient_create_resp.recipient_id;
Ok(recipient_id)
}
async fn locker_recipient_create_call(
state: &SessionState,
merchant_id: &id_type::MerchantId,
data: &types::MerchantAccountData,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
let key_manager_state = &state.into();
let key = key_store.key.get_inner().peek();
let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone());
let data_json = serde_json::to_string(data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize MerchantAccountData to JSON")?;
let encrypted_data = domain_types::crypto_operation(
key_manager_state,
type_name!(payment_method::PaymentMethod),
domain_types::CryptoOperation::Encrypt(Secret::<String, masking::WithType>::new(data_json)),
identifier,
key,
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt merchant account data")?;
let enc_data = hex::encode(encrypted_data.into_encrypted().expose());
let merchant_id_string = merchant_id.get_string_repr().to_owned();
let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from(merchant_id_string))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert to CustomerId")?;
let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq {
merchant_id: merchant_id.to_owned(),
merchant_customer_id: cust_id.clone(),
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
});
let store_resp = cards::add_card_to_hs_locker(
state,
&payload,
&cust_id,
api_enums::LockerChoice::HyperswitchCardVault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt merchant bank account data")?;
Ok(store_resp.card_reference)
}
pub async fn enable_platform_account(
state: SessionState,
merchant_id: id_type::MerchantId,
) -> RouterResponse<()> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = db
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
db.update_merchant(
key_manager_state,
merchant_account,
storage::MerchantAccountUpdate::ToPlatformAccount,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while enabling platform merchant account")
.map(|_| services::ApplicationResponse::StatusOk)
}
impl From<&types::MerchantAccountData> for pm_auth_types::RecipientCreateRequest {
fn from(data: &types::MerchantAccountData) -> Self {
let (name, account_data) = match data {
types::MerchantAccountData::Iban { iban, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::Iban(iban.clone()),
),
types::MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
} => (
name.clone(),
pm_auth_types::RecipientAccountData::Bacs {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
},
),
types::MerchantAccountData::FasterPayments {
account_number,
sort_code,
name,
..
} => (
name.clone(),
pm_auth_types::RecipientAccountData::FasterPayments {
sort_code: sort_code.clone(),
account_number: account_number.clone(),
},
),
types::MerchantAccountData::Sepa { iban, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::Sepa(iban.clone()),
),
types::MerchantAccountData::SepaInstant { iban, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::SepaInstant(iban.clone()),
),
types::MerchantAccountData::Elixir {
account_number,
iban,
name,
..
} => (
name.clone(),
pm_auth_types::RecipientAccountData::Elixir {
account_number: account_number.clone(),
iban: iban.clone(),
},
),
types::MerchantAccountData::Bankgiro { number, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::Bankgiro(number.clone()),
),
types::MerchantAccountData::Plusgiro { number, name, .. } => (
name.clone(),
pm_auth_types::RecipientAccountData::Plusgiro(number.clone()),
),
};
Self {
name,
account_data,
address: None,
}
}
}
| crates/router/src/core/admin.rs | router::src::core::admin | 36,837 | true |
// File: crates/router/src/core/connector_onboarding.rs
// Module: router::src::core::connector_onboarding
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)
}
| crates/router/src/core/connector_onboarding.rs | router::src::core::connector_onboarding | 960 | true |
// File: crates/router/src/core/api_locking.rs
// Module: router::src::core::api_locking
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_aqcuired = 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_aqcuired {
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>;
}
| crates/router/src/core/api_locking.rs | router::src::core::api_locking | 2,107 | true |
// File: crates/router/src/core/chat.rs
// Module: router::src::core::chat
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,
}));
}
| crates/router/src/core/chat.rs | router::src::core::chat | 1,629 | true |
// File: crates/router/src/core/pm_auth.rs
// Module: router::src::core::pm_auth
use std::{collections::HashMap, str::FromStr};
use api_models::{
enums,
payment_methods::{self, BankAccountAccessCreds},
};
use common_enums::{enums::MerchantStorageScheme, PaymentMethodType};
use hex;
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,
merchant_context: domain::MerchantContext,
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,
&merchant_context,
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(),
merchant_context.get_merchant_key_store(),
&pi.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_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(
&(&state).into(),
merchant_context.get_merchant_account().get_id(),
&selected_config.mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_context
.get_merchant_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(merchant_context.get_merchant_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,
_merchant_context: domain::MerchantContext,
_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,
merchant_context: domain::MerchantContext,
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(
&(&state).into(),
merchant_context.get_merchant_account().get_id(),
&config.mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_context
.get_merchant_account()
.get_id()
.get_string_repr()
.to_owned(),
})?;
#[cfg(feature = "v2")]
let merchant_connector_account: domain::MerchantConnectorAccount = {
let _ = merchant_context.get_merchant_account();
let _ = connector;
let _ = merchant_context.get_merchant_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,
&merchant_context,
connector_name,
&access_token,
auth_type,
&state,
None,
)
.await?;
Box::pin(store_bank_details_in_payment_methods(
payload,
merchant_context,
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,
merchant_context: domain::MerchantContext,
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(
&(&state).into(),
&payload.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(
&((&state).into()),
merchant_context.get_merchant_key_store(),
&customer_id,
merchant_context.get_merchant_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,
merchant_context.get_merchant_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()),
};
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,
merchant_context.get_merchant_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: merchant_context.get_merchant_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(),
};
new_entries.push(pm_new);
};
}
store_in_db(
&state,
merchant_context.get_merchant_key_store(),
update_entries,
new_entries,
db,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
Ok(())
}
#[cfg(feature = "v2")]
async fn store_bank_details_in_payment_methods(
_payload: api_models::pm_auth::ExchangeTokenCreateRequest,
_merchant_context: domain::MerchantContext,
_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(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
update_entries: Vec<(domain::PaymentMethod, storage::PaymentMethodUpdate)>,
new_entries: Vec<domain::PaymentMethod>,
db: &dyn StorageInterface,
storage_scheme: MerchantStorageScheme,
) -> RouterResult<()> {
let key_manager_state = &(state.into());
let update_entries_futures = update_entries
.into_iter()
.map(|(pm, pm_update)| {
db.update_payment_method(key_manager_state, 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_manager_state, 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,
merchant_context: &domain::MerchantContext,
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(merchant_context.get_merchant_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 key_manager_state = &state.into();
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&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(
key_manager_state,
&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 merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
merchant_account.clone(),
key_store.clone(),
)));
let bank_account_creds = get_bank_account_creds(
connector,
&merchant_context,
&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)))
}
| crates/router/src/core/pm_auth.rs | router::src::core::pm_auth | 6,556 | true |
// File: crates/router/src/core/payments/tokenization.rs
// Module: router::src::core::payments::tokenization
use std::collections::HashMap;
use ::payment_methods::controller::PaymentMethodsController;
#[cfg(feature = "v1")]
use api_models::payment_methods::PaymentMethodsData;
use api_models::{
payment_methods::PaymentMethodDataWalletInfo, 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};
#[cfg(feature = "v1")]
use hyperswitch_domain_models::{
callback_mapper::CallbackMapper,
mandates::{CommonMandateReference, PaymentsMandateReference, PaymentsMandateReferenceRecord},
payment_method_data,
};
use masking::{ExposeInterface, Secret};
use router_env::{instrument, tracing};
use super::helpers;
#[cfg(feature = "v1")]
use crate::core::payment_methods::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,
},
logger,
routes::{metrics, SessionState},
services,
types::{
self,
api::{self, CardDetailFromLocker, CardDetailsPaymentMethod, 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,
merchant_context: &domain::MerchantContext,
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,
merchant_context,
payment_method_request,
card_detail,
external_vault_details,
))
.await
}
domain::ExternalVaultDetails::Skip => {
// Use internal vault (locker)
save_in_locker_internal(state, merchant_context, 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>,
merchant_context: &domain::MerchantContext,
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>,
) -> RouterResult<SavePaymentMethodDataResponse>
where
FData: mandate::MandateBehaviour + Clone,
{
let mut pm_status = None;
let cards = PmCards {
state,
merchant_context,
};
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 = merchant_context.get_merchant_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(
merchant_context,
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,
merchant_context,
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(PaymentMethodsData::Card(
CardDetailsPaymentMethod::from((card.clone(), co_badged_card_data)),
)),
(
_,
domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(applepay)),
) => Some(PaymentMethodsData::WalletDetails(
PaymentMethodDataWalletInfo::from(applepay),
)),
(
_,
domain::PaymentMethodData::Wallet(domain::WalletData::GooglePay(googlepay)),
) => Some(PaymentMethodsData::WalletDetails(
PaymentMethodDataWalletInfo::from(googlepay),
)),
_ => 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,
merchant_context.get_merchant_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| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((
card.clone(),
None,
)))
});
pm_token_details
.async_map(|pm_card| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_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,
merchant_context.get_merchant_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(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_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(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context
.get_merchant_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(
state,
merchant_context.get_merchant_key_store(),
db,
pm.clone(),
pm_metadata,
merchant_context.get_merchant_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(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_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(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context
.get_merchant_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(
state,
merchant_context.get_merchant_key_store(),
db,
pm.clone(),
connector_mandate_details,
merchant_context.get_merchant_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,
api::enums::LockerChoice::HyperswitchCardVault,
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(
&(state.into()),
merchant_context.get_merchant_key_store(),
merchant_id,
&resp.payment_method_id,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::PaymentMethodNotFound,
)?;
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed while updating card metadata changes",
))?
};
let existing_pm_data = cards
.get_card_details_without_locker_fallback(&existing_pm)
.await?;
// scheme should be updated in case of co-badged cards
let card_scheme = card
.card_network
.clone()
.map(|card_network| card_network.to_string())
.or(existing_pm_data.scheme.clone());
let updated_card = Some(CardDetailFromLocker {
scheme: card_scheme.clone(),
last4_digits: Some(card.card_number.get_last4()),
issuer_country: card
.card_issuing_country
.or(existing_pm_data.issuer_country),
card_isin: Some(card.card_number.get_card_isin()),
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_fingerprint: None,
card_holder_name: card
.card_holder_name
.or(existing_pm_data.card_holder_name),
nick_name: card.nick_name.or(existing_pm_data.nick_name),
card_network: card
.card_network
.or(existing_pm_data.card_network),
card_issuer: card.card_issuer.or(existing_pm_data.card_issuer),
card_type: card.card_type.or(existing_pm_data.card_type),
saved_to_locker: true,
});
let updated_pmd = updated_card.as_ref().map(|card| {
PaymentMethodsData::Card(CardDetailsPaymentMethod::from((
card.clone(),
co_badged_card_data,
)))
});
let pm_data_encrypted: Option<
Encryptable<Secret<serde_json::Value>>,
> = updated_pmd
.async_map(|pmd| {
create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pmd,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
payment_methods::cards::update_payment_method_and_last_used(
state,
merchant_context.get_merchant_key_store(),
db,
existing_pm,
pm_data_encrypted.map(Into::into),
merchant_context.get_merchant_account().storage_scheme,
card_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let customer_saved_pm_option = if payment_method_type
.map(|payment_method_type_value| {
payment_method_type_value
.should_check_for_customer_saved_payment_method_type()
})
.unwrap_or(false)
{
match state
.store
.find_payment_method_by_customer_id_merchant_id_list(
&(state.into()),
merchant_context.get_merchant_key_store(),
&customer_id,
merchant_id,
None,
)
.await
{
Ok(customer_payment_methods) => Ok(customer_payment_methods
.iter()
.find(|payment_method| {
payment_method.get_payment_method_subtype()
== 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",
)
}
}
}
} else {
Ok(None)
}?;
if let Some(customer_saved_pm) = customer_saved_pm_option {
payment_methods::cards::update_last_used_at(
&customer_saved_pm,
state,
merchant_context.get_merchant_account().storage_scheme,
merchant_context.get_merchant_key_store(),
)
.await
.map_err(|e| {
logger::error!("Failed to update last used at: {:?}", e);
})
.ok();
resp.payment_method_id = customer_saved_pm.payment_method_id;
} else {
let pm_metadata =
create_payment_method_metadata(None, connector_token)?;
locker_id = resp.payment_method.and_then(|pm| {
if pm == PaymentMethod::Card {
Some(resp.payment_method_id)
} else {
None
}
});
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
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.clone(),
network_token_locker_id,
pm_network_token_data_encrypted,
Some(vault_source_details),
)
.await?;
match network_token_requestor_ref_id {
Some(network_token_requestor_ref_id) => {
//Insert the network token reference ID along with merchant id, customer id in CallbackMapper table for its respective webooks
let callback_mapper_data =
CallbackMapperData::NetworkTokenWebhook {
merchant_id: merchant_context
.get_merchant_account()
.get_id()
.clone(),
customer_id,
payment_method_id: resp.payment_method_id.clone(),
};
let callback_mapper = CallbackMapper::new(
network_token_requestor_ref_id,
common_enums::CallbackMapperIdType::NetworkTokenRequestorReferenceID,
callback_mapper_data,
common_utils::date_time::now(),
common_utils::date_time::now(),
);
db.insert_call_back_mapper(callback_mapper)
.await
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"Failed to insert in Callback Mapper table",
)?;
}
None => {
logger::info!("Network token requestor reference ID is not available, skipping callback mapper insertion");
}
};
};
}
}
Some(resp.payment_method_id)
} else {
None
};
// check if there needs to be a config if yes then remove it to a different place
let connector_mandate_reference_id = if connector_mandate_id.is_some() {
if let Some(ref mut record) = original_connector_mandate_reference_id {
record.update(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
);
Some(record.clone())
} else {
Some(ConnectorMandateReferenceId::new(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
))
}
} else {
None
};
Ok(SavePaymentMethodDataResponse {
payment_method_id: pm_id,
payment_method_status: pm_status,
connector_mandate_reference_id,
})
}
Err(_) => Ok(SavePaymentMethodDataResponse {
payment_method_id: None,
payment_method_status: None,
connector_mandate_reference_id: None,
}),
}
}
#[cfg(feature = "v2")]
#[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>,
_merchant_context: &domain::MerchantContext,
_payment_method_type: Option<storage_enums::PaymentMethodType>,
_billing_name: Option<Secret<String>>,
_payment_method_billing_address: Option<&api::Address>,
_business_profile: &domain::Profile,
_connector_mandate_request_reference_id: Option<String>,
) -> RouterResult<SavePaymentMethodDataResponse>
where
FData: mandate::MandateBehaviour + Clone,
{
todo!()
}
#[cfg(feature = "v1")]
pub async fn pre_payment_tokenization(
state: &SessionState,
customer_id: id_type::CustomerId,
card: &payment_method_data::Card,
) -> RouterResult<(Option<pm_types::TokenResponse>, Option<String>)> {
let network_tokenization_supported_card_networks = &state
.conf
.network_tokenization_supported_card_networks
.card_networks;
if card
.card_network
.as_ref()
.filter(|cn| network_tokenization_supported_card_networks.contains(cn))
.is_some()
{
let optional_card_cvc = Some(card.card_cvc.clone());
let card_detail = payment_method_data::CardDetail::from(card);
match network_tokenization::make_card_network_tokenization_request(
state,
&card_detail,
optional_card_cvc,
&customer_id,
)
.await
{
Ok((_token_response, network_token_requestor_ref_id)) => {
let network_tokenization_service = &state.conf.network_tokenization_service;
match (
network_token_requestor_ref_id.clone(),
network_tokenization_service,
) {
(Some(token_ref), Some(network_tokenization_service)) => {
let network_token = record_operation_time(
async {
network_tokenization::get_network_token(
state,
customer_id,
token_ref,
network_tokenization_service.get_inner(),
)
.await
},
&metrics::FETCH_NETWORK_TOKEN_TIME,
&[],
)
.await;
match network_token {
Ok(token_response) => {
Ok((Some(token_response), network_token_requestor_ref_id.clone()))
}
_ => {
logger::error!(
"Error while fetching token from tokenization service"
);
Ok((None, network_token_requestor_ref_id.clone()))
}
}
}
(Some(token_ref), _) => Ok((None, Some(token_ref))),
_ => Ok((None, None)),
}
}
Err(err) => {
logger::error!("Failed to tokenize card: {:?}", err);
Ok((None, None)) //None will be returned in case of error when calling network tokenization service
}
}
} else {
Ok((None, None)) //None will be returned in case of unsupported card network.
}
}
#[cfg(feature = "v1")]
async fn skip_saving_card_in_locker(
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = payment_method_request
.clone()
.customer_id
.clone()
.get_required_value("customer_id")?;
let payment_method_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let last4_digits = payment_method_request
.card
.clone()
.map(|c| c.card_number.get_last4());
let card_isin = payment_method_request
.card
.clone()
.map(|c| c.card_number.get_card_isin());
match payment_method_request.card.clone() {
Some(card) => {
let card_detail = CardDetailFromLocker {
scheme: None,
issuer_country: card.card_issuing_country.clone(),
last4_digits: last4_digits.clone(),
card_number: None,
expiry_month: Some(card.card_exp_month.clone()),
expiry_year: Some(card.card_exp_year),
card_token: None,
card_holder_name: card.card_holder_name.clone(),
card_fingerprint: None,
nick_name: None,
card_isin: card_isin.clone(),
card_issuer: card.card_issuer.clone(),
card_network: card.card_network.clone(),
card_type: card.card_type.clone(),
saved_to_locker: false,
};
let pm_resp = api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id),
payment_method_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
card: Some(card_detail),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
metadata: None,
created: Some(common_utils::date_time::now()),
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((pm_resp, None))
}
None => {
let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id),
payment_method_id: pm_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
card: None,
metadata: None,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((payment_method_response, None))
}
}
}
#[cfg(feature = "v2")]
async fn skip_saving_card_in_locker(
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn save_in_locker_internal(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
card_detail: Option<api::CardDetail>,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
payment_method_request.validate()?;
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = payment_method_request
.customer_id
.clone()
.get_required_value("customer_id")?;
match (payment_method_request.card.clone(), card_detail) {
(_, Some(card)) | (Some(card), _) => Box::pin(
PmCards {
state,
merchant_context,
}
.add_card_to_locker(payment_method_request, &card, &customer_id, None),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card Failed"),
_ => {
let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_id.clone(),
customer_id: Some(customer_id),
payment_method_id: pm_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: None,
metadata: None,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((payment_method_response, None))
}
}
}
#[cfg(feature = "v1")]
pub async fn save_in_locker_external(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_method_request: api::PaymentMethodCreate,
card_detail: Option<api::CardDetail>,
external_vault_connector_details: &ExternalVaultConnectorDetails,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
let customer_id = payment_method_request
.customer_id
.clone()
.get_required_value("customer_id")?;
// For external vault, we need to convert the card data to PaymentMethodVaultingData
if let Some(card) = card_detail {
let payment_method_vaulting_data =
hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card.clone());
let external_vault_mca_id = external_vault_connector_details.vault_connector_id.clone();
let key_manager_state = &state.into();
let merchant_connector_account_details = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
&external_vault_mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: external_vault_mca_id.get_string_repr().to_string(),
})?;
// Call vault_payment_method_external_v1
let vault_response = vault_payment_method_external_v1(
state,
&payment_method_vaulting_data,
merchant_context.get_merchant_account(),
merchant_connector_account_details,
)
.await?;
let payment_method_id = vault_response.vault_id.to_string().to_owned();
let card_detail = CardDetailFromLocker::from(card);
let pm_resp = api::PaymentMethodResponse {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
customer_id: Some(customer_id),
payment_method_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
card: Some(card_detail),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
metadata: None,
created: Some(common_utils::date_time::now()),
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((pm_resp, None))
} else {
//Similar implementation is done for save in locker internal
let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
customer_id: Some(customer_id),
payment_method_id: pm_id,
payment_method: payment_method_request.payment_method,
payment_method_type: payment_method_request.payment_method_type,
#[cfg(feature = "payouts")]
bank_transfer: None,
card: None,
metadata: None,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false),
installment_payment_enabled: Some(false),
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
};
Ok((payment_method_response, None))
}
}
#[cfg(feature = "v2")]
pub async fn save_in_locker_internal(
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_method_request: api::PaymentMethodCreate,
) -> RouterResult<(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
todo!()
}
#[cfg(feature = "v2")]
pub async fn save_network_token_in_locker(
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_card_data: &domain::Card,
_payment_method_request: api::PaymentMethodCreate,
) -> RouterResult<(
Option<api_models::payment_methods::PaymentMethodResponse>,
Option<payment_methods::transformers::DataDuplicationCheck>,
Option<String>,
)> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn save_network_token_in_locker(
state: &SessionState,
merchant_context: &domain::MerchantContext,
card_data: &payment_method_data::Card,
network_token_data: Option<api::CardDetail>,
payment_method_request: api::PaymentMethodCreate,
) -> RouterResult<(
Option<api_models::payment_methods::PaymentMethodResponse>,
Option<payment_methods::transformers::DataDuplicationCheck>,
Option<String>,
)> {
let customer_id = payment_method_request
.customer_id
.clone()
.get_required_value("customer_id")?;
let network_tokenization_supported_card_networks = &state
.conf
.network_tokenization_supported_card_networks
.card_networks;
match network_token_data {
Some(nt_data) => {
let (res, dc) = Box::pin(
PmCards {
state,
merchant_context,
}
.add_card_to_locker(
payment_method_request,
&nt_data,
&customer_id,
None,
),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Network Token Failed")?;
Ok((Some(res), dc, None))
}
None => {
if card_data
.card_network
.as_ref()
.filter(|cn| network_tokenization_supported_card_networks.contains(cn))
.is_some()
{
let optional_card_cvc = Some(card_data.card_cvc.clone());
match network_tokenization::make_card_network_tokenization_request(
state,
&domain::CardDetail::from(card_data),
optional_card_cvc,
&customer_id,
)
.await
{
Ok((token_response, network_token_requestor_ref_id)) => {
// Only proceed if the tokenization was successful
let network_token_data = api::CardDetail {
card_number: token_response.token.clone(),
card_exp_month: token_response.token_expiry_month.clone(),
card_exp_year: token_response.token_expiry_year.clone(),
card_holder_name: None,
nick_name: None,
card_issuing_country: None,
card_network: Some(token_response.card_brand.clone()),
card_issuer: None,
card_type: None,
};
let (res, dc) = Box::pin(
PmCards {
state,
merchant_context,
}
.add_card_to_locker(
payment_method_request,
&network_token_data,
&customer_id,
None,
),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Network Token Failed")?;
Ok((Some(res), dc, network_token_requestor_ref_id))
}
Err(err) => {
logger::error!("Failed to tokenize card: {:?}", err);
Ok((None, None, None)) //None will be returned in case of error when calling network tokenization service
}
}
} else {
Ok((None, None, None)) //None will be returned in case of unsupported card network.
}
}
}
}
pub fn handle_tokenization_response<F, Req>(
resp: &mut types::RouterData<F, Req, types::PaymentsResponseData>,
) {
let response = resp.response.clone();
if let Err(err) = response {
if let Some(secret_metadata) = &err.connector_metadata {
let metadata = secret_metadata.clone().expose();
if let Some(token) = metadata
.get("payment_method_token")
.and_then(|t| t.as_str())
{
resp.response = Ok(types::PaymentsResponseData::TokenizationResponse {
token: token.to_string(),
});
}
}
}
}
pub fn create_payment_method_metadata(
metadata: Option<&pii::SecretSerdeValue>,
connector_token: Option<(String, String)>,
) -> RouterResult<Option<serde_json::Value>> {
let mut meta = match metadata {
None => serde_json::Map::new(),
Some(meta) => {
let metadata = meta.clone().expose();
let existing_metadata: serde_json::Map<String, serde_json::Value> = metadata
.parse_value("Map<String, Value>")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse the metadata")?;
existing_metadata
}
};
Ok(connector_token.and_then(|connector_and_token| {
meta.insert(
connector_and_token.0,
serde_json::Value::String(connector_and_token.1),
)
}))
}
pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>(
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>,
pm_token_request_data: types::PaymentMethodTokenizationData,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
if should_continue_payment {
match tokenization_action {
payments::TokenizationAction::TokenizeInConnector => {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PaymentMethodToken,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let pm_token_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let pm_token_router_data =
helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>(
router_data.clone(),
pm_token_request_data,
pm_token_response_data,
);
router_data
.request
.set_session_token(pm_token_router_data.session_token.clone());
let mut resp = services::execute_connector_processing_step(
state,
connector_integration,
&pm_token_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
// checks for metadata in the ErrorResponse, if present bypasses it and constructs an Ok response
handle_tokenization_response(&mut resp);
metrics::CONNECTOR_PAYMENT_METHOD_TOKENIZATION.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
),
);
let payment_token_resp = resp.response.map(|res| {
if let types::PaymentsResponseData::TokenizationResponse { token } = res {
Some(token)
} else {
None
}
});
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: payment_token_resp,
is_payment_method_tokenization_performed: true,
connector_response: resp.connector_response.clone(),
})
}
_ => Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
}),
}
} else {
logger::debug!("Skipping connector tokenization based on should_continue_payment flag");
Ok(types::PaymentMethodTokenResult {
payment_method_token_result: Ok(None),
is_payment_method_tokenization_performed: false,
connector_response: None,
})
}
}
pub fn update_router_data_with_payment_method_token_result<F: Clone, T>(
payment_method_token_result: types::PaymentMethodTokenResult,
router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>,
is_retry_payment: bool,
should_continue_further: bool,
) -> bool {
if payment_method_token_result.is_payment_method_tokenization_performed {
match payment_method_token_result.payment_method_token_result {
Ok(pm_token_result) => {
router_data.payment_method_token = pm_token_result.map(|pm_token| {
hyperswitch_domain_models::router_data::PaymentMethodToken::Token(Secret::new(
pm_token,
))
});
if router_data.connector_response.is_none() {
router_data.connector_response =
payment_method_token_result.connector_response.clone();
}
true
}
Err(err) => {
if is_retry_payment {
router_data.response = Err(err);
false
} else {
logger::debug!(payment_method_tokenization_error=?err);
true
}
}
}
} else {
should_continue_further
}
}
#[cfg(feature = "v1")]
pub fn add_connector_mandate_details_in_payment_method(
payment_method_type: Option<storage_enums::PaymentMethodType>,
authorized_amount: Option<i64>,
authorized_currency: Option<storage_enums::Currency>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
connector_mandate_id: Option<String>,
mandate_metadata: Option<Secret<serde_json::Value>>,
connector_mandate_request_reference_id: Option<String>,
) -> Option<CommonMandateReference> {
let mut mandate_details = HashMap::new();
if let Some((mca_id, connector_mandate_id)) =
merchant_connector_id.clone().zip(connector_mandate_id)
{
mandate_details.insert(
mca_id,
PaymentsMandateReferenceRecord {
connector_mandate_id,
payment_method_type,
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
mandate_metadata,
connector_mandate_status: Some(ConnectorMandateStatus::Active),
connector_mandate_request_reference_id,
},
);
Some(CommonMandateReference {
payments: Some(PaymentsMandateReference(mandate_details)),
payouts: None,
})
} else {
None
}
}
#[allow(clippy::too_many_arguments)]
#[cfg(feature = "v1")]
pub fn update_connector_mandate_details(
mandate_details: Option<CommonMandateReference>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
authorized_amount: Option<i64>,
authorized_currency: Option<storage_enums::Currency>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
connector_mandate_id: Option<String>,
mandate_metadata: Option<Secret<serde_json::Value>>,
connector_mandate_request_reference_id: Option<String>,
) -> RouterResult<Option<CommonMandateReference>> {
let mandate_reference = match mandate_details
.as_ref()
.and_then(|common_mandate| common_mandate.payments.clone())
{
Some(mut payment_mandate_reference) => {
if let Some((mca_id, connector_mandate_id)) =
merchant_connector_id.clone().zip(connector_mandate_id)
{
let updated_record = PaymentsMandateReferenceRecord {
connector_mandate_id: connector_mandate_id.clone(),
payment_method_type,
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
mandate_metadata: mandate_metadata.clone(),
connector_mandate_status: Some(ConnectorMandateStatus::Active),
connector_mandate_request_reference_id: connector_mandate_request_reference_id
.clone(),
};
payment_mandate_reference
.entry(mca_id)
.and_modify(|pm| *pm = updated_record)
.or_insert(PaymentsMandateReferenceRecord {
connector_mandate_id,
payment_method_type,
original_payment_authorized_amount: authorized_amount,
original_payment_authorized_currency: authorized_currency,
mandate_metadata: mandate_metadata.clone(),
connector_mandate_status: Some(ConnectorMandateStatus::Active),
connector_mandate_request_reference_id,
});
let payout_data = mandate_details.and_then(|common_mandate| common_mandate.payouts);
Some(CommonMandateReference {
payments: Some(payment_mandate_reference),
payouts: payout_data,
})
} else {
None
}
}
None => add_connector_mandate_details_in_payment_method(
payment_method_type,
authorized_amount,
authorized_currency,
merchant_connector_id,
connector_mandate_id,
mandate_metadata,
connector_mandate_request_reference_id,
),
};
Ok(mandate_reference)
}
#[cfg(feature = "v1")]
pub fn update_connector_mandate_details_status(
merchant_connector_id: id_type::MerchantConnectorAccountId,
mut payment_mandate_reference: PaymentsMandateReference,
status: ConnectorMandateStatus,
) -> RouterResult<Option<CommonMandateReference>> {
let mandate_reference = {
payment_mandate_reference
.entry(merchant_connector_id)
.and_modify(|pm| {
let update_rec = PaymentsMandateReferenceRecord {
connector_mandate_id: pm.connector_mandate_id.clone(),
payment_method_type: pm.payment_method_type,
original_payment_authorized_amount: pm.original_payment_authorized_amount,
original_payment_authorized_currency: pm.original_payment_authorized_currency,
mandate_metadata: pm.mandate_metadata.clone(),
connector_mandate_status: Some(status),
connector_mandate_request_reference_id: pm
.connector_mandate_request_reference_id
.clone(),
};
*pm = update_rec
});
Some(payment_mandate_reference)
};
Ok(Some(CommonMandateReference {
payments: mandate_reference,
payouts: None,
}))
}
#[cfg(feature = "v2")]
pub async fn add_token_for_payment_method(
router_data: &mut types::RouterData<
api::PaymentMethodToken,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
>,
payment_method_data_request: types::PaymentMethodTokenizationData,
state: SessionState,
merchant_connector_account_details: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
) -> RouterResult<types::PspTokenResult> {
let connector_id = merchant_connector_account_details.id.clone();
let connector_data = api::ConnectorData::get_connector_by_name(
&(state.conf.connectors),
&merchant_connector_account_details
.connector_name
.to_string(),
api::GetToken::Connector,
Some(connector_id.clone()),
)?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PaymentMethodToken,
types::PaymentMethodTokenizationData,
types::PaymentsResponseData,
> = connector_data.connector.get_connector_integration();
let payment_method_token_response_data_type: Result<
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let payment_method_token_router_data =
helpers::router_data_type_conversion::<_, api::PaymentMethodToken, _, _, _, _>(
router_data.clone(),
payment_method_data_request.clone(),
payment_method_token_response_data_type,
);
let connector_integration_response = services::execute_connector_processing_step(
&state,
connector_integration,
&payment_method_token_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let payment_token_response = connector_integration_response.response.map(|res| {
if let types::PaymentsResponseData::TokenizationResponse { token } = res {
Ok(token)
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get token from connector")
}
});
match payment_token_response {
Ok(token) => Ok(types::PspTokenResult { token: Ok(token?) }),
Err(error_response) => Ok(types::PspTokenResult {
token: Err(error_response),
}),
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn save_card_and_network_token_in_locker(
state: &SessionState,
customer_id: id_type::CustomerId,
payment_method_status: common_enums::PaymentMethodStatus,
payment_method_data: domain::PaymentMethodData,
vault_operation: Option<hyperswitch_domain_models::payments::VaultOperation>,
payment_method_info: Option<domain::PaymentMethod>,
merchant_context: &domain::MerchantContext,
payment_method_create_request: api::PaymentMethodCreate,
is_network_tokenization_enabled: bool,
business_profile: &domain::Profile,
) -> RouterResult<(
(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
Option<String>,
),
Option<api_models::payment_methods::PaymentMethodResponse>,
)> {
let network_token_requestor_reference_id = payment_method_info
.and_then(|pm_info| pm_info.network_token_requestor_reference_id.clone());
match vault_operation {
Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardData(card)) => {
let card_data = api::CardDetail::from(card.card_data.clone());
if let (Some(nt_ref_id), Some(tokenization_service)) = (
card.network_token_req_ref_id.clone(),
&state.conf.network_tokenization_service,
) {
let _ = record_operation_time(
async {
network_tokenization::delete_network_token_from_tokenization_service(
state,
nt_ref_id.clone(),
&customer_id,
tokenization_service.get_inner(),
)
.await
},
&metrics::DELETE_NETWORK_TOKEN_TIME,
&[],
)
.await;
}
let (res, dc) = Box::pin(save_in_locker(
state,
merchant_context,
payment_method_create_request.to_owned(),
Some(card_data),
business_profile,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card In Locker Failed")?;
Ok(((res, dc, None), None))
}
Some(hyperswitch_domain_models::payments::VaultOperation::SaveCardAndNetworkTokenData(
save_card_and_network_token_data,
)) => {
let card_data =
api::CardDetail::from(save_card_and_network_token_data.card_data.clone());
let network_token_data = api::CardDetail::from(
save_card_and_network_token_data
.network_token
.network_token_data
.clone(),
);
if payment_method_status == common_enums::PaymentMethodStatus::Active {
let (res, dc) = Box::pin(save_in_locker_internal(
state,
merchant_context,
payment_method_create_request.to_owned(),
Some(card_data),
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card In Locker Failed")?;
let (network_token_resp, _dc, _) = Box::pin(save_network_token_in_locker(
state,
merchant_context,
&save_card_and_network_token_data.card_data,
Some(network_token_data),
payment_method_create_request.clone(),
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Network Token In Locker Failed")?;
Ok((
(res, dc, network_token_requestor_reference_id),
network_token_resp,
))
} else {
if let (Some(nt_ref_id), Some(tokenization_service)) = (
network_token_requestor_reference_id.clone(),
&state.conf.network_tokenization_service,
) {
let _ = record_operation_time(
async {
network_tokenization::delete_network_token_from_tokenization_service(
state,
nt_ref_id.clone(),
&customer_id,
tokenization_service.get_inner(),
)
.await
},
&metrics::DELETE_NETWORK_TOKEN_TIME,
&[],
)
.await;
}
let (res, dc) = Box::pin(save_in_locker_internal(
state,
merchant_context,
payment_method_create_request.to_owned(),
Some(card_data),
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card In Locker Failed")?;
Ok(((res, dc, None), None))
}
}
_ => {
let card_data = payment_method_create_request.card.clone();
let (res, dc) = Box::pin(save_in_locker(
state,
merchant_context,
payment_method_create_request.to_owned(),
card_data,
business_profile,
))
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Add Card In Locker Failed")?;
if is_network_tokenization_enabled {
match &payment_method_data {
domain::PaymentMethodData::Card(card) => {
let (
network_token_resp,
_network_token_duplication_check, //the duplication check is discarded, since each card has only one token, handling card duplication check will be suffice
network_token_requestor_ref_id,
) = Box::pin(save_network_token_in_locker(
state,
merchant_context,
card,
None,
payment_method_create_request.clone(),
))
.await?;
Ok((
(res, dc, network_token_requestor_ref_id),
network_token_resp,
))
}
_ => Ok(((res, dc, None), None)), //network_token_resp is None in case of other payment methods
}
} else {
Ok(((res, dc, None), None))
}
}
}
}
| crates/router/src/core/payments/tokenization.rs | router::src::core::payments::tokenization | 13,512 | true |
// File: crates/router/src/core/payments/payment_methods.rs
// Module: router::src::core::payments::payment_methods
//! 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,
merchant_context: domain::MerchantContext,
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 key_manager_state = &(&state).into();
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
&payment_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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(
key_manager_state,
profile.get_id(),
merchant_context.get_merchant_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,
&merchant_context,
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,
&merchant_context,
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 => 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,
merchant_context: &domain::MerchantContext,
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
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: "list_payment_methods".to_string(),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: ["requires_payment_method".to_string()].join(", "),
})
}
}
}
| crates/router/src/core/payments/payment_methods.rs | router::src::core::payments::payment_methods | 6,355 | true |
// File: crates/router/src/core/payments/types.rs
// Module: router::src::core::payments::types
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::{
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<
&hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore,
> for AuthenticationData
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
authentication_store: &hyperswitch_domain_models::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(),
})
} else {
Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into())
}
}
}
| crates/router/src/core/payments/types.rs | router::src::core::payments::types | 3,339 | true |
// File: crates/router/src/core/payments/transformers.rs
// Module: router::src::core::payments::transformers
use std::{fmt::Debug, marker::PhantomData, str::FromStr};
#[cfg(feature = "v2")]
use api_models::enums as api_enums;
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,
merchant_context: &domain::MerchantContext,
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,
merchant_context: &domain::MerchantContext,
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: merchant_context.get_merchant_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,
merchant_context.get_merchant_account().get_id(),
&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,
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,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::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,
merchant_context
.get_merchant_account()
.publishable_key
.as_ref(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to construct finish redirection url")?
.to_string();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("connector_request_reference_id not found in payment_attempt")?;
let email = customer
.as_ref()
.and_then(|customer| customer.email.clone())
.map(pii::Email::from);
let browser_info = payment_data
.payment_attempt
.browser_info
.clone()
.map(types::BrowserInformation::from);
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,
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,
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,
payment_channel: None,
enable_partial_authorization: payment_data.payment_intent.enable_partial_authorization,
enable_overcapture: None,
is_stored_credential: None,
};
let connector_mandate_request_reference_id = payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|detail| detail.get_connector_token_request_reference_id());
// TODO: evaluate the fields in router data, if they are required or not
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
// TODO: evaluate why we need customer id at the connector level. We already have connector customer id.
customer_id,
connector: connector_id.to_owned(),
// TODO: evaluate why we need payment id at the connector level. We already have connector reference id
payment_id: payment_data
.payment_attempt
.payment_id
.get_string_repr()
.to_owned(),
// TODO: evaluate why we need attempt id at the connector level. We already have connector reference id
attempt_id: payment_data
.payment_attempt
.get_id()
.get_string_repr()
.to_owned(),
status: payment_data.payment_attempt.status,
payment_method,
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,
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,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::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,
merchant_context
.get_merchant_account()
.publishable_key
.as_ref(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to construct finish redirection url")?
.to_string();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("connector_request_reference_id not found in payment_attempt")?;
let email = customer
.as_ref()
.and_then(|customer| customer.email.clone())
.map(pii::Email::from);
let browser_info = payment_data
.payment_attempt
.browser_info
.clone()
.map(types::BrowserInformation::from);
// TODO: few fields are repeated in both routerdata and request
let request = types::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,
merchant_context.get_merchant_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,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::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: merchant_context.get_merchant_account().get_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(),
tenant_id: state.tenant.tenant_id.clone(),
// 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: hyperswitch_domain_models::payment_address::PaymentAddress::default(),
auth_type: payment_data.payment_attempt.authentication_type,
connector_meta_data: None,
connector_wallets_details: None,
request,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_status: None,
payment_method_token: None,
connector_customer: None,
recurring_mandate_payment_data: None,
// TODO: This has to be generated as the reference id based on the connector configuration
// Some connectros might not accept accept the global id. This has to be done when generating the reference id
connector_request_reference_id,
preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
// TODO: take this based on the env
test_mode: Some(true),
payment_method_balance: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id,
psd2_sca_exemption_type: None,
authentication_id: 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_router_data_for_psync<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentStatusData<api::PSync>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsSyncRouterData> {
use masking::ExposeOptionInterface;
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
})?;
// TODO: Take Globalid / CustomerReferenceId and convert to connector reference id
let customer_id = None;
let payment_intent = payment_data.payment_intent;
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let attempt = &payment_data.payment_attempt;
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 request = types::PaymentsSyncData {
amount: attempt.amount_details.get_net_amount(),
integrity_object: None,
mandate_id: None,
connector_transaction_id: match attempt.get_connector_payment_id() {
Some(connector_txn_id) => {
types::ResponseId::ConnectorTransactionId(connector_txn_id.to_owned())
}
None => types::ResponseId::NoResponseId,
},
encoded_data: attempt.encoded_data.clone().expose_option(),
capture_method: Some(payment_intent.capture_method),
connector_meta: attempt.connector_metadata.clone().expose_option(),
sync_type: types::SyncRequestType::SinglePaymentSync,
payment_method_type: Some(attempt.payment_method_subtype),
currency: payment_intent.amount_details.currency,
// TODO: Get the charges object from feature metadata
split_payments: None,
payment_experience: None,
connector_reference_id: attempt.connector_response_reference_id.clone(),
setup_future_usage: Some(payment_intent.setup_future_usage),
};
// TODO: evaluate the fields in router data, if they are required or not
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
// TODO: evaluate why we need customer id at the connector level. We already have connector customer id.
customer_id,
tenant_id: state.tenant.tenant_id.clone(),
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_intent.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: attempt.get_id().get_string_repr().to_owned(),
status: attempt.status,
payment_method: attempt.payment_method_type,
payment_method_type: Some(attempt.payment_method_subtype),
connector_auth_type: auth_type,
description: payment_intent
.description
.as_ref()
.map(|description| description.get_string_repr())
.map(ToOwned::to_owned),
// TODO: Create unified address
address: hyperswitch_domain_models::payment_address::PaymentAddress::default(),
auth_type: attempt.authentication_type,
connector_meta_data: None,
connector_wallets_details: None,
request,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_status: None,
payment_method_token: None,
connector_customer: None,
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: attempt.preprocessing_step_id.clone(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
// TODO: take this based on the env
test_mode: Some(true),
payment_method_balance: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id: 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_cancel_router_data_v2<'a>(
state: &'a SessionState,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
payment_data: &hyperswitch_domain_models::payments::PaymentCancelData<api::Void>,
request: types::PaymentsCancelData,
connector_request_reference_id: String,
customer_id: Option<common_utils::id_type::CustomerId>,
connector_id: &str,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
RouterDataV2<
api::Void,
flow_common_types::PaymentFlowData,
types::PaymentsCancelData,
types::PaymentsResponseData,
>,
> {
let auth_type: types::ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
let payment_cancel_data = flow_common_types::PaymentFlowData {
merchant_id: merchant_account.get_id().clone(),
customer_id,
connector_customer: None,
connector: connector_id.to_owned(),
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: hyperswitch_domain_models::payment_address::PaymentAddress::default(),
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: payment_cancel_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_router_data_for_cancel<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentCancelData<
hyperswitch_domain_models::router_flow_types::Void,
>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsCancelRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
})?;
// 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 payment_intent = payment_data.get_payment_intent();
let attempt = payment_data.get_payment_attempt();
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 request = types::PaymentsCancelData {
amount: Some(attempt.amount_details.get_net_amount().get_amount_as_i64()),
currency: Some(payment_intent.amount_details.currency),
connector_transaction_id: attempt
.get_connector_payment_id()
.unwrap_or_default()
.to_string(),
cancellation_reason: attempt.cancellation_reason.clone(),
connector_meta: attempt.connector_metadata.clone().expose_option(),
browser_info: None,
metadata: None,
minor_amount: Some(attempt.amount_details.get_net_amount()),
webhook_url: None,
capture_method: Some(payment_intent.capture_method),
};
// Construct RouterDataV2 for cancel operation
let router_data_v2 = construct_cancel_router_data_v2(
state,
merchant_context.get_merchant_account(),
merchant_connector_account,
&payment_data,
request,
connector_request_reference_id.clone(),
customer_id.clone(),
connector_id,
header_payload.clone(),
)
.await?;
// Convert RouterDataV2 to old RouterData (v1) using the existing RouterDataConversion trait
let router_data = flow_common_types::PaymentFlowData::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_sdk_session<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentIntentData<api::Session>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsSessionRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
})?;
let auth_type: types::ConnectorAuthType = 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 billing_address = payment_data
.payment_intent
.billing_address
.as_ref()
.map(|billing_address| billing_address.clone().into_inner());
// fetch email from customer or billing address (fallback)
let email = customer
.as_ref()
.and_then(|customer| customer.email.clone())
.map(pii::Email::from)
.or(billing_address
.as_ref()
.and_then(|address| address.email.clone()));
// fetch customer name from customer or billing address (fallback)
let customer_name = customer
.as_ref()
.and_then(|customer| customer.name.clone())
.map(|name| name.into_inner())
.or(billing_address.and_then(|address| {
address
.address
.as_ref()
.and_then(|address_details| address_details.get_optional_full_name())
}));
let order_details = payment_data
.payment_intent
.order_details
.clone()
.map(|order_details| {
order_details
.into_iter()
.map(|order_detail| order_detail.expose())
.collect()
});
let required_amount_type = StringMajorUnitForConnector;
let apple_pay_amount = required_amount_type
.convert(
payment_data.payment_intent.amount_details.order_amount,
payment_data.payment_intent.amount_details.currency,
)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for applePay".to_string(),
})?;
let apple_pay_recurring_details = payment_data
.payment_intent
.feature_metadata
.clone()
.and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details)
.map(|apple_pay_recurring_details| {
ForeignInto::foreign_into((apple_pay_recurring_details, apple_pay_amount))
});
let order_tax_amount = payment_data
.payment_intent
.amount_details
.tax_details
.clone()
.and_then(|tax| tax.get_default_tax_amount());
let payment_attempt = payment_data.get_payment_attempt();
let payment_method = Some(payment_attempt.payment_method_type);
let payment_method_type = Some(payment_attempt.payment_method_subtype);
// TODO: few fields are repeated in both routerdata and request
let request = types::PaymentsSessionData {
amount: payment_data
.payment_intent
.amount_details
.order_amount
.get_amount_as_i64(),
currency: payment_data.payment_intent.amount_details.currency,
country: payment_data
.payment_intent
.billing_address
.and_then(|billing_address| {
billing_address
.get_inner()
.address
.as_ref()
.and_then(|address| address.country)
}),
// TODO: populate surcharge here
surcharge_details: None,
order_details,
email,
minor_amount: payment_data.payment_intent.amount_details.order_amount,
apple_pay_recurring_details,
customer_name,
metadata: payment_data.payment_intent.metadata,
order_tax_amount,
shipping_cost: payment_data.payment_intent.amount_details.shipping_cost,
payment_method,
payment_method_type,
};
// TODO: evaluate the fields in router data, if they are required or not
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
// TODO: evaluate why we need customer id at the connector level. We already have connector customer id.
customer_id,
connector: connector_id.to_owned(),
tenant_id: state.tenant.tenant_id.clone(),
// TODO: evaluate why we need payment id at the connector level. We already have connector reference id
payment_id: payment_data.payment_intent.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: "".to_string(),
status: enums::AttemptStatus::Started,
payment_method: enums::PaymentMethod::Wallet,
payment_method_type,
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: hyperswitch_domain_models::payment_address::PaymentAddress::default(),
auth_type: payment_data
.payment_intent
.authentication_type
.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: None,
request,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_status: None,
payment_method_token: None,
connector_customer: None,
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: "".to_string(),
preprocessing_id: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
// TODO: take this based on the env
test_mode: Some(true),
payment_method_balance: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id: None,
psd2_sca_exemption_type: None,
authentication_id: 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_payment_router_data_for_setup_mandate<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentConfirmData<api::SetupMandate>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::SetupMandateRouterData> {
fp_utils::when(merchant_connector_account.is_disabled(), || {
Err(errors::ApiErrorResponse::MerchantConnectorAccountDisabled)
})?;
let auth_type = merchant_connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
// TODO: Take Globalid and convert to connector reference id
let customer_id = customer
.to_owned()
.map(|customer| common_utils::id_type::CustomerId::try_from(customer.id.clone()))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Invalid global customer generated, not able to convert to reference id",
)?;
let connector_customer_id = customer.as_ref().and_then(|customer| {
customer
.get_connector_customer_id(merchant_connector_account)
.map(String::from)
});
let payment_method = payment_data.payment_attempt.payment_method_type;
let router_base_url = &state.base_url;
let attempt = &payment_data.payment_attempt;
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_id,
None,
));
let webhook_url = match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(
merchant_connector_account,
) => Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account.get_id().get_string_repr(),
)),
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
payment_data.webhook_url
}
};
let router_return_url = payment_data
.payment_intent
.create_finish_redirection_url(
router_base_url,
merchant_context
.get_merchant_account()
.publishable_key
.as_ref(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to construct finish redirection url")?
.to_string();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("connector_request_reference_id not found in payment_attempt")?;
let email = customer
.as_ref()
.and_then(|customer| customer.email.clone())
.map(pii::Email::from);
let browser_info = payment_data
.payment_attempt
.browser_info
.clone()
.map(types::BrowserInformation::from);
// TODO: few fields are repeated in both routerdata and request
let request = types::SetupMandateRequestData {
currency: payment_data.payment_intent.amount_details.currency,
payment_method_data: payment_data
.payment_method_data
.get_required_value("payment_method_data")?,
amount: Some(
payment_data
.payment_attempt
.amount_details
.get_net_amount()
.get_amount_as_i64(),
),
confirm: true,
statement_descriptor_suffix: None,
customer_acceptance: None,
mandate_id: None,
setup_future_usage: Some(payment_data.payment_intent.setup_future_usage),
off_session: None,
setup_mandate_details: None,
router_return_url: Some(router_return_url.clone()),
webhook_url,
browser_info,
email,
customer_name: None,
return_url: Some(router_return_url),
payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype),
request_incremental_authorization: matches!(
payment_data
.payment_intent
.request_incremental_authorization,
RequestIncrementalAuthorization::True
),
metadata: payment_data.payment_intent.metadata,
minor_amount: Some(payment_data.payment_attempt.amount_details.get_net_amount()),
shipping_cost: payment_data.payment_intent.amount_details.shipping_cost,
capture_method: Some(payment_data.payment_intent.capture_method),
complete_authorize_url,
connector_testing_data: None,
customer_id: None,
enable_partial_authorization: None,
payment_channel: None,
enrolled_for_3ds: true,
related_transaction_id: None,
is_stored_credential: None,
};
let connector_mandate_request_reference_id = payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|detail| detail.get_connector_token_request_reference_id());
// TODO: evaluate the fields in router data, if they are required or not
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
// TODO: evaluate why we need customer id at the connector level. We already have connector customer id.
customer_id,
connector: connector_id.to_owned(),
// TODO: evaluate why we need payment id at the connector level. We already have connector reference id
payment_id: payment_data
.payment_attempt
.payment_id
.get_string_repr()
.to_owned(),
// TODO: evaluate why we need attempt id at the connector level. We already have connector reference id
attempt_id: payment_data
.payment_attempt
.get_id()
.get_string_repr()
.to_owned(),
status: payment_data.payment_attempt.status,
payment_method,
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: None,
connector_wallets_details: None,
request,
response: Err(hyperswitch_domain_models::router_data::ErrorResponse::default()),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_status: None,
payment_method_token: None,
connector_customer: connector_customer_id,
recurring_mandate_payment_data: None,
// TODO: This has to be generated as the reference id based on the connector configuration
// Some connectros might not accept accept the global id. This has to be done when generating the reference id
connector_request_reference_id,
preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
// TODO: take this based on the env
test_mode: Some(true),
payment_method_balance: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn construct_payment_router_data<'a, F, T>(
state: &'a SessionState,
payment_data: PaymentData<F>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a 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<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 payment_method = payment_data
.payment_attempt
.payment_method
.or(payment_method)
.get_required_value("payment_method")?;
let payment_method_type = payment_data
.payment_attempt
.payment_method_type
.or(payment_method_type);
let resource_id = match payment_data
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string)
{
Some(id) => types::ResponseId::ConnectorTransactionId(id),
None => types::ResponseId::NoResponseId,
};
// [#44]: why should response be filled during request
let response = Ok(types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
});
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 customer_id = customer.to_owned().map(|customer| customer.customer_id);
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_enum = api_models::enums::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 apple_pay_flow = payments::decide_apple_pay_flow(
state,
payment_data.payment_attempt.payment_method_type,
Some(merchant_connector_account),
);
let unified_address = if let Some(payment_method_info) =
payment_data.payment_method_info.clone()
{
let payment_method_billing = payment_method_info
.payment_method_billing_address
.map(|decrypted_data| decrypted_data.into_inner().expose())
.map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse payment_method_billing_address")?;
payment_data
.address
.clone()
.unify_with_payment_data_billing(payment_method_billing)
} else {
payment_data.address
};
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 order_details = payment_data
.payment_intent
.order_details
.as_ref()
.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<_>, _>>()
})
.transpose()?;
let l2_l3_data =
(state.conf.l2_l3_data_config.enabled && payment_data.is_l2_l3_enabled).then(|| {
let shipping_address = unified_address.get_shipping();
let billing_address = unified_address.get_payment_billing();
let merchant_tax_registration_id = merchant_context
.get_merchant_account()
.get_merchant_tax_registration_id();
Box::new(types::L2L3Data {
order_date: payment_data.payment_intent.order_date,
tax_status: payment_data.payment_intent.tax_status,
customer_tax_registration_id: customer.as_ref().and_then(|c| {
c.tax_registration_id
.as_ref()
.map(|e| e.clone().into_inner())
}),
order_details: order_details.clone(),
discount_amount: payment_data.payment_intent.discount_amount,
shipping_cost: payment_data.payment_intent.shipping_cost,
shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,
duty_amount: payment_data.payment_intent.duty_amount,
order_tax_amount: payment_data
.payment_attempt
.net_amount
.get_order_tax_amount(),
merchant_order_reference_id: payment_data
.payment_intent
.merchant_order_reference_id
.clone(),
customer_id: payment_data.payment_intent.customer_id.clone(),
billing_address_city: billing_address
.as_ref()
.and_then(|addr| addr.address.as_ref())
.and_then(|details| details.city.clone()),
merchant_tax_registration_id,
customer_name: customer
.as_ref()
.and_then(|c| c.name.as_ref().map(|e| e.clone().into_inner())),
customer_email: payment_data.email,
customer_phone_number: customer
.as_ref()
.and_then(|c| c.phone.as_ref().map(|e| e.clone().into_inner())),
customer_phone_country_code: customer
.as_ref()
.and_then(|c| c.phone_country_code.clone()),
shipping_details: shipping_address
.and_then(|address| address.address.as_ref())
.cloned(),
})
});
crate::logger::debug!("unified address details {:?}", unified_address);
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id,
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_id.to_owned(),
payment_id: payment_data
.payment_attempt
.payment_id
.get_string_repr()
.to_owned(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
status: payment_data.payment_attempt.status,
payment_method,
payment_method_type,
connector_auth_type: auth_type,
description: payment_data.payment_intent.description.clone(),
address: unified_address,
auth_type: payment_data
.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(),
request: T::try_from(additional_data)?,
response,
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: payment_data.payment_method_info.map(|info| info.status),
payment_method_token: payment_data
.pm_token
.map(|token| types::PaymentMethodToken::Token(Secret::new(token))),
connector_customer: payment_data.connector_customer_id,
recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data,
connector_request_reference_id: core_utils::get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
&payment_data.payment_intent,
&payment_data.payment_attempt,
connector_id,
)?,
preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,
#[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,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: merchant_recipient_data.map(|data| {
api_models::admin::AdditionalMerchantData::foreign_from(
types::AdditionalMerchantData::OpenBankingRecipientData(data),
)
}),
header_payload,
connector_mandate_request_reference_id,
authentication_id: None,
psd2_sca_exemption_type: payment_data.payment_intent.psd2_sca_exemption_type,
raw_connector_response: None,
is_payment_id_from_merchant: payment_data.payment_intent.is_payment_id_from_merchant,
l2_l3_data,
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_payment_router_data_for_update_metadata<'a>(
state: &'a SessionState,
payment_data: PaymentData<api::UpdateMetadata>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::UpdateMetadata,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
>,
> {
let (payment_method, router_data);
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")?;
payment_method = payment_data
.payment_attempt
.payment_method
.or(payment_data.payment_attempt.payment_method)
.get_required_value("payment_method_type")?;
// [#44]: why should response be filled during request
let response = Err(hyperswitch_domain_models::router_data::ErrorResponse {
code: "IR_20".to_string(),
message: "Update metadata is not implemented for this connector".to_string(),
reason: None,
status_code: http::StatusCode::BAD_REQUEST.as_u16(),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
});
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 customer_id = customer.to_owned().map(|customer| customer.customer_id);
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_enum = api_models::enums::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 apple_pay_flow = payments::decide_apple_pay_flow(
state,
payment_data.payment_attempt.payment_method_type,
Some(merchant_connector_account),
);
let unified_address = if let Some(payment_method_info) =
payment_data.payment_method_info.clone()
{
let payment_method_billing = payment_method_info
.payment_method_billing_address
.map(|decrypted_data| decrypted_data.into_inner().expose())
.map(|decrypted_value| decrypted_value.parse_value("payment_method_billing_address"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse payment_method_billing_address")?;
payment_data
.address
.clone()
.unify_with_payment_data_billing(payment_method_billing)
} else {
payment_data.address
};
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());
crate::logger::debug!("unified address details {:?}", unified_address);
router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
customer_id,
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_id.to_owned(),
payment_id: payment_data
.payment_attempt
.payment_id
.get_string_repr()
.to_owned(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
status: payment_data.payment_attempt.status,
payment_method,
payment_method_type: payment_data.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: payment_data.payment_intent.description.clone(),
address: unified_address,
auth_type: payment_data
.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(),
request: types::PaymentsUpdateMetadataData::try_from(additional_data)?,
response,
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: payment_data.payment_method_info.map(|info| info.status),
payment_method_token: payment_data
.pm_token
.map(|token| types::PaymentMethodToken::Token(Secret::new(token))),
connector_customer: payment_data.connector_customer_id,
recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data,
connector_request_reference_id: core_utils::get_connector_request_reference_id(
&state.conf,
merchant_context.get_merchant_account().get_id(),
&payment_data.payment_intent,
&payment_data.payment_attempt,
connector_id,
)?,
preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,
#[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,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: merchant_recipient_data.map(|data| {
api_models::admin::AdditionalMerchantData::foreign_from(
types::AdditionalMerchantData::OpenBankingRecipientData(data),
)
}),
header_payload,
connector_mandate_request_reference_id,
authentication_id: None,
psd2_sca_exemption_type: payment_data.payment_intent.psd2_sca_exemption_type,
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)
}
pub trait ToResponse<F, D, Op>
where
Self: Sized,
Op: Debug,
D: OperationSessionGetters<F>,
{
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
fn generate_response(
data: D,
customer: Option<domain::Customer>,
auth_flow: services::AuthFlow,
base_url: &str,
operation: Op,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
) -> RouterResponse<Self>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
fn generate_response(
data: D,
customer: Option<domain::Customer>,
base_url: &str,
operation: Op,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
merchant_context: &domain::MerchantContext,
) -> RouterResponse<Self>;
}
/// Generate a response from the given Data. This should be implemented on a payment data object
pub trait GenerateResponse<Response>
where
Self: Sized,
{
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
fn generate_response(
self,
state: &SessionState,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
connector_response_data: Option<common_types::domain::ConnectorResponseData>,
) -> RouterResponse<Response>;
}
#[cfg(feature = "v2")]
impl<F> GenerateResponse<api_models::payments::PaymentsCaptureResponse>
for hyperswitch_domain_models::payments::PaymentCaptureData<F>
where
F: Clone,
{
fn generate_response(
self,
state: &SessionState,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
_connector_response_data: Option<common_types::domain::ConnectorResponseData>,
) -> RouterResponse<api_models::payments::PaymentsCaptureResponse> {
let payment_intent = &self.payment_intent;
let payment_attempt = &self.payment_attempt;
let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from((
&payment_intent.amount_details,
&payment_attempt.amount_details,
));
let response = api_models::payments::PaymentsCaptureResponse {
id: payment_intent.id.clone(),
amount,
status: payment_intent.status,
};
let headers = connector_http_status_code
.map(|status_code| {
vec![(
X_CONNECTOR_HTTP_STATUS_CODE.to_string(),
Maskable::new_normal(status_code.to_string()),
)]
})
.unwrap_or_default();
Ok(services::ApplicationResponse::JsonWithHeaders((
response, headers,
)))
}
}
#[cfg(feature = "v2")]
impl<F> GenerateResponse<api_models::payments::PaymentsCancelResponse>
for hyperswitch_domain_models::payments::PaymentCancelData<F>
where
F: Clone,
{
fn generate_response(
self,
state: &SessionState,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
_connector_response_data: Option<common_types::domain::ConnectorResponseData>,
) -> RouterResponse<api_models::payments::PaymentsCancelResponse> {
let payment_intent = &self.payment_intent;
let payment_attempt = &self.payment_attempt;
let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from((
&payment_intent.amount_details,
&payment_attempt.amount_details,
));
let connector = payment_attempt
.connector
.as_ref()
.and_then(|conn| api_enums::Connector::from_str(conn).ok());
let error = payment_attempt
.error
.as_ref()
.map(api_models::payments::ErrorDetails::foreign_from);
let response = api_models::payments::PaymentsCancelResponse {
id: payment_intent.id.clone(),
status: payment_intent.status,
cancellation_reason: payment_attempt.cancellation_reason.clone(),
amount,
customer_id: payment_intent.customer_id.clone(),
connector,
created: payment_intent.created_at,
payment_method_type: Some(payment_attempt.payment_method_type),
payment_method_subtype: Some(payment_attempt.payment_method_subtype),
attempts: None,
return_url: payment_intent.return_url.clone(),
error,
};
let headers = connector_http_status_code
.map(|status_code| {
vec![(
X_CONNECTOR_HTTP_STATUS_CODE.to_string(),
Maskable::new_normal(status_code.to_string()),
)]
})
.unwrap_or_default();
Ok(services::ApplicationResponse::JsonWithHeaders((
response, headers,
)))
}
}
#[cfg(feature = "v1")]
impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsResponse
where
F: Clone,
Op: Debug,
D: OperationSessionGetters<F>,
{
#[allow(clippy::too_many_arguments)]
fn generate_response(
payment_data: D,
customer: Option<domain::Customer>,
auth_flow: services::AuthFlow,
base_url: &str,
operation: Op,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
) -> RouterResponse<Self> {
let captures = payment_data
.get_multiple_capture_data()
.and_then(|multiple_capture_data| {
multiple_capture_data
.expand_captures
.and_then(|should_expand| {
should_expand.then_some(
multiple_capture_data
.get_all_captures()
.into_iter()
.cloned()
.collect(),
)
})
});
payments_to_payments_response(
payment_data,
captures,
customer,
auth_flow,
base_url,
&operation,
connector_request_reference_id_config,
connector_http_status_code,
external_latency,
is_latency_header_enabled,
)
}
}
#[cfg(feature = "v1")]
impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsSessionResponse
where
F: Clone,
Op: Debug,
D: OperationSessionGetters<F>,
{
#[allow(clippy::too_many_arguments)]
fn generate_response(
payment_data: D,
_customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
_base_url: &str,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
) -> RouterResponse<Self> {
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
session_token: payment_data.get_sessions_token(),
payment_id: payment_data.get_payment_attempt().payment_id.clone(),
client_secret: payment_data
.get_payment_intent()
.client_secret
.clone()
.get_required_value("client_secret")?
.into(),
},
vec![],
)))
}
}
#[cfg(feature = "v2")]
impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsSessionResponse
where
F: Clone,
Op: Debug,
D: OperationSessionGetters<F>,
{
#[allow(clippy::too_many_arguments)]
fn generate_response(
payment_data: D,
_customer: Option<domain::Customer>,
_base_url: &str,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_merchant_context: &domain::MerchantContext,
) -> RouterResponse<Self> {
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
session_token: payment_data.get_sessions_token(),
payment_id: payment_data.get_payment_intent().id.clone(),
vault_details: payment_data.get_optional_external_vault_session_details(),
},
vec![],
)))
}
}
#[cfg(feature = "v1")]
impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsDynamicTaxCalculationResponse
where
F: Clone,
Op: Debug,
D: OperationSessionGetters<F>,
{
#[allow(clippy::too_many_arguments)]
fn generate_response(
payment_data: D,
_customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
_base_url: &str,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
) -> RouterResponse<Self> {
let mut amount = payment_data.get_payment_intent().amount;
let shipping_cost = payment_data.get_payment_intent().shipping_cost;
if let Some(shipping_cost) = shipping_cost {
amount = amount + shipping_cost;
}
let order_tax_amount = payment_data
.get_payment_intent()
.tax_details
.clone()
.and_then(|tax| {
tax.payment_method_type
.map(|a| a.order_tax_amount)
.or_else(|| tax.default.map(|a| a.order_tax_amount))
});
if let Some(tax_amount) = order_tax_amount {
amount = amount + tax_amount;
}
let currency = payment_data
.get_payment_attempt()
.currency
.get_required_value("currency")?;
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
net_amount: amount,
payment_id: payment_data.get_payment_attempt().payment_id.clone(),
order_tax_amount,
shipping_cost,
display_amount: api_models::payments::DisplayAmountOnSdk::foreign_try_from((
amount,
shipping_cost,
order_tax_amount,
currency,
))?,
},
vec![],
)))
}
}
#[cfg(feature = "v2")]
impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsIntentResponse
where
F: Clone,
Op: Debug,
D: OperationSessionGetters<F>,
{
#[allow(clippy::too_many_arguments)]
fn generate_response(
payment_data: D,
_customer: Option<domain::Customer>,
_base_url: &str,
operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_merchant_context: &domain::MerchantContext,
) -> RouterResponse<Self> {
let payment_intent = payment_data.get_payment_intent();
let client_secret = payment_data.get_client_secret();
let is_cit_transaction = payment_intent.setup_future_usage.is_off_session();
let mandate_type = if payment_intent.customer_present
== common_enums::PresenceOfCustomerDuringPayment::Absent
{
Some(api::MandateTransactionType::RecurringMandateTransaction)
} else if is_cit_transaction {
Some(api::MandateTransactionType::NewMandateTransaction)
} else {
None
};
let payment_type = helpers::infer_payment_type(
payment_intent.amount_details.order_amount.into(),
mandate_type.as_ref(),
);
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
id: payment_intent.id.clone(),
profile_id: payment_intent.profile_id.clone(),
status: payment_intent.status,
amount_details: api_models::payments::AmountDetailsResponse::foreign_from(
payment_intent.amount_details.clone(),
),
client_secret: client_secret.clone(),
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
routing_algorithm_id: payment_intent.routing_algorithm_id.clone(),
capture_method: payment_intent.capture_method,
authentication_type: payment_intent.authentication_type,
billing: payment_intent
.billing_address
.clone()
.map(|billing| billing.into_inner())
.map(From::from),
shipping: payment_intent
.shipping_address
.clone()
.map(|shipping| shipping.into_inner())
.map(From::from),
customer_id: payment_intent.customer_id.clone(),
customer_present: payment_intent.customer_present,
description: payment_intent.description.clone(),
return_url: payment_intent.return_url.clone(),
setup_future_usage: payment_intent.setup_future_usage,
apply_mit_exemption: payment_intent.apply_mit_exemption,
statement_descriptor: payment_intent.statement_descriptor.clone(),
order_details: payment_intent.order_details.clone().map(|order_details| {
order_details
.into_iter()
.map(|order_detail| order_detail.expose().convert_back())
.collect()
}),
allowed_payment_method_types: payment_intent.allowed_payment_method_types.clone(),
metadata: payment_intent.metadata.clone(),
connector_metadata: payment_intent.connector_metadata.clone(),
feature_metadata: payment_intent
.feature_metadata
.clone()
.map(|feature_metadata| feature_metadata.convert_back()),
payment_link_enabled: payment_intent.enable_payment_link,
payment_link_config: payment_intent
.payment_link_config
.clone()
.map(ForeignFrom::foreign_from),
request_incremental_authorization: payment_intent.request_incremental_authorization,
split_txns_enabled: payment_intent.split_txns_enabled,
expires_on: payment_intent.session_expiry,
frm_metadata: payment_intent.frm_metadata.clone(),
request_external_three_ds_authentication: payment_intent
.request_external_three_ds_authentication,
payment_type,
enable_partial_authorization: payment_intent.enable_partial_authorization,
},
vec![],
)))
}
}
#[cfg(feature = "v2")]
impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentAttemptListResponse
where
F: Clone,
Op: Debug,
D: OperationSessionGetters<F>,
{
#[allow(clippy::too_many_arguments)]
fn generate_response(
payment_data: D,
_customer: Option<domain::Customer>,
_base_url: &str,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_merchant_context: &domain::MerchantContext,
) -> RouterResponse<Self> {
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
payment_attempt_list: payment_data
.list_payments_attempts()
.iter()
.map(api_models::payments::PaymentAttemptResponse::foreign_from)
.collect(),
},
vec![],
)))
}
}
#[cfg(feature = "v2")]
impl<F> GenerateResponse<api_models::payments::PaymentsResponse>
for hyperswitch_domain_models::payments::PaymentConfirmData<F>
where
F: Clone,
{
fn generate_response(
self,
state: &SessionState,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
connector_response_data: Option<common_types::domain::ConnectorResponseData>,
) -> RouterResponse<api_models::payments::PaymentsResponse> {
let payment_intent = self.payment_intent;
let payment_attempt = self.payment_attempt;
let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from((
&payment_intent.amount_details,
&payment_attempt.amount_details,
));
let connector = payment_attempt
.connector
.clone()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector is none when constructing response")?;
let merchant_connector_id = payment_attempt.merchant_connector_id.clone();
let error = payment_attempt
.error
.as_ref()
.map(api_models::payments::ErrorDetails::foreign_from);
let payment_address = self.payment_address;
let raw_connector_response =
connector_response_data.and_then(|data| data.raw_connector_response);
let payment_method_data =
Some(api_models::payments::PaymentMethodDataResponseWithBilling {
payment_method_data: None,
billing: payment_address
.get_request_payment_method_billing()
.cloned()
.map(From::from),
});
// TODO: Add support for other next actions, currently only supporting redirect to url
let redirect_to_url = payment_intent.create_start_redirection_url(
&state.base_url,
merchant_context
.get_merchant_account()
.publishable_key
.clone(),
)?;
let next_action = if payment_intent.status.is_in_terminal_state() {
None
} else {
let next_action_containing_wait_screen =
wait_screen_next_steps_check(payment_attempt.clone())?;
let next_action_containing_sdk_upi_intent =
extract_sdk_uri_information(payment_attempt.clone())?;
payment_attempt
.redirection_data
.as_ref()
.map(|_| api_models::payments::NextActionData::RedirectToUrl { redirect_to_url })
.or(next_action_containing_sdk_upi_intent.map(|sdk_uri_data| {
api_models::payments::NextActionData::SdkUpiIntentInformation {
sdk_uri: sdk_uri_data.sdk_uri,
}
}))
.or(next_action_containing_wait_screen.map(|wait_screen_data| {
api_models::payments::NextActionData::WaitScreenInformation {
display_from_timestamp: wait_screen_data.display_from_timestamp,
display_to_timestamp: wait_screen_data.display_to_timestamp,
poll_config: wait_screen_data.poll_config,
}
}))
};
let connector_token_details = payment_attempt
.connector_token_details
.and_then(Option::<api_models::payments::ConnectorTokenDetails>::foreign_from);
let return_url = payment_intent
.return_url
.clone()
.or(profile.return_url.clone());
let headers = connector_http_status_code
.map(|status_code| {
vec![(
X_CONNECTOR_HTTP_STATUS_CODE.to_string(),
Maskable::new_normal(status_code.to_string()),
)]
})
.unwrap_or_default();
let response = api_models::payments::PaymentsResponse {
id: payment_intent.id.clone(),
status: payment_intent.status,
amount,
customer_id: payment_intent.customer_id.clone(),
connector: Some(connector),
created: payment_intent.created_at,
modified_at: payment_intent.modified_at,
payment_method_data,
payment_method_type: Some(payment_attempt.payment_method_type),
payment_method_subtype: Some(payment_attempt.payment_method_subtype),
next_action,
connector_transaction_id: payment_attempt.connector_payment_id.clone(),
connector_reference_id: payment_attempt.connector_response_reference_id.clone(),
connector_token_details,
merchant_connector_id,
browser_info: None,
error,
return_url,
authentication_type: payment_intent.authentication_type,
authentication_type_applied: Some(payment_attempt.authentication_type),
payment_method_id: payment_attempt.payment_method_id,
attempts: None,
billing: None, //TODO: add this
shipping: None, //TODO: add this
is_iframe_redirection_enabled: None,
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
raw_connector_response,
feature_metadata: payment_intent
.feature_metadata
.map(|feature_metadata| feature_metadata.convert_back()),
metadata: payment_intent.metadata,
};
Ok(services::ApplicationResponse::JsonWithHeaders((
response, headers,
)))
}
}
#[cfg(feature = "v2")]
impl<F> GenerateResponse<api_models::payments::PaymentsResponse>
for hyperswitch_domain_models::payments::PaymentStatusData<F>
where
F: Clone,
{
fn generate_response(
self,
state: &SessionState,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
is_latency_header_enabled: Option<bool>,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
connector_response_data: Option<common_types::domain::ConnectorResponseData>,
) -> RouterResponse<api_models::payments::PaymentsResponse> {
let payment_intent = self.payment_intent;
let payment_attempt = &self.payment_attempt;
let amount = api_models::payments::PaymentAmountDetailsResponse::foreign_from((
&payment_intent.amount_details,
&payment_attempt.amount_details,
));
let connector = payment_attempt.connector.clone();
let merchant_connector_id = payment_attempt.merchant_connector_id.clone();
let error = payment_attempt
.error
.as_ref()
.map(api_models::payments::ErrorDetails::foreign_from);
let attempts = self.attempts.as_ref().map(|attempts| {
attempts
.iter()
.map(api_models::payments::PaymentAttemptResponse::foreign_from)
.collect()
});
let payment_method_data =
Some(api_models::payments::PaymentMethodDataResponseWithBilling {
payment_method_data: None,
billing: self
.payment_address
.get_request_payment_method_billing()
.cloned()
.map(From::from),
});
let raw_connector_response =
connector_response_data.and_then(|data| data.raw_connector_response);
let connector_token_details = self
.payment_attempt
.connector_token_details
.clone()
.and_then(Option::<api_models::payments::ConnectorTokenDetails>::foreign_from);
let return_url = payment_intent.return_url.or(profile.return_url.clone());
let headers = connector_http_status_code
.map(|status_code| {
vec![(
X_CONNECTOR_HTTP_STATUS_CODE.to_string(),
Maskable::new_normal(status_code.to_string()),
)]
})
.unwrap_or_default();
let response = api_models::payments::PaymentsResponse {
id: payment_intent.id.clone(),
status: payment_intent.status,
amount,
customer_id: payment_intent.customer_id.clone(),
connector,
billing: self
.payment_address
.get_payment_billing()
.cloned()
.map(From::from),
shipping: self.payment_address.get_shipping().cloned().map(From::from),
created: payment_intent.created_at,
modified_at: payment_intent.modified_at,
payment_method_data,
payment_method_type: Some(payment_attempt.payment_method_type),
payment_method_subtype: Some(payment_attempt.payment_method_subtype),
connector_transaction_id: payment_attempt.connector_payment_id.clone(),
connector_reference_id: payment_attempt.connector_response_reference_id.clone(),
merchant_connector_id,
browser_info: None,
connector_token_details,
payment_method_id: payment_attempt.payment_method_id.clone(),
error,
authentication_type_applied: payment_attempt.authentication_applied,
authentication_type: payment_intent.authentication_type,
next_action: None,
attempts,
return_url,
is_iframe_redirection_enabled: payment_intent.is_iframe_redirection_enabled,
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
raw_connector_response,
feature_metadata: payment_intent
.feature_metadata
.map(|feature_metadata| feature_metadata.convert_back()),
metadata: payment_intent.metadata,
};
Ok(services::ApplicationResponse::JsonWithHeaders((
response, headers,
)))
}
}
#[cfg(feature = "v2")]
impl<F> GenerateResponse<api_models::payments::PaymentAttemptResponse>
for hyperswitch_domain_models::payments::PaymentAttemptRecordData<F>
where
F: Clone,
{
fn generate_response(
self,
_state: &SessionState,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
_connector_response_data: Option<common_types::domain::ConnectorResponseData>,
) -> RouterResponse<api_models::payments::PaymentAttemptResponse> {
let payment_attempt = self.payment_attempt;
let response = api_models::payments::PaymentAttemptResponse::foreign_from(&payment_attempt);
Ok(services::ApplicationResponse::JsonWithHeaders((
response,
vec![],
)))
}
}
#[cfg(feature = "v2")]
impl<F> GenerateResponse<api_models::payments::PaymentAttemptRecordResponse>
for hyperswitch_domain_models::payments::PaymentAttemptRecordData<F>
where
F: Clone,
{
fn generate_response(
self,
_state: &SessionState,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
_merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
_connector_response_data: Option<common_types::domain::ConnectorResponseData>,
) -> RouterResponse<api_models::payments::PaymentAttemptRecordResponse> {
let payment_attempt = self.payment_attempt;
let payment_intent = self.payment_intent;
let response = api_models::payments::PaymentAttemptRecordResponse {
id: payment_attempt.id.clone(),
status: payment_attempt.status,
amount: payment_attempt.amount_details.get_net_amount(),
payment_intent_feature_metadata: payment_intent
.feature_metadata
.as_ref()
.map(api_models::payments::FeatureMetadata::foreign_from),
payment_attempt_feature_metadata: payment_attempt
.feature_metadata
.as_ref()
.map(api_models::payments::PaymentAttemptFeatureMetadata::foreign_from),
error_details: payment_attempt
.error
.map(api_models::payments::RecordAttemptErrorDetails::from),
created_at: payment_attempt.created_at,
};
Ok(services::ApplicationResponse::JsonWithHeaders((
response,
vec![],
)))
}
}
#[cfg(feature = "v1")]
impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsPostSessionTokensResponse
where
F: Clone,
Op: Debug,
D: OperationSessionGetters<F>,
{
fn generate_response(
payment_data: D,
_customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
_base_url: &str,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
) -> RouterResponse<Self> {
let papal_sdk_next_action =
paypal_sdk_next_steps_check(payment_data.get_payment_attempt().clone())?;
let next_action = papal_sdk_next_action.map(|paypal_next_action_data| {
api_models::payments::NextActionData::InvokeSdkClient {
next_action_data: paypal_next_action_data,
}
});
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
payment_id: payment_data.get_payment_intent().payment_id.clone(),
next_action,
status: payment_data.get_payment_intent().status,
},
vec![],
)))
}
}
#[cfg(feature = "v1")]
impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsUpdateMetadataResponse
where
F: Clone,
Op: Debug,
D: OperationSessionGetters<F>,
{
fn generate_response(
payment_data: D,
_customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
_base_url: &str,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
) -> RouterResponse<Self> {
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
payment_id: payment_data.get_payment_intent().payment_id.clone(),
metadata: payment_data
.get_payment_intent()
.metadata
.clone()
.map(Secret::new),
},
vec![],
)))
}
}
impl ForeignTryFrom<(MinorUnit, Option<MinorUnit>, Option<MinorUnit>, Currency)>
for api_models::payments::DisplayAmountOnSdk
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
(net_amount, shipping_cost, order_tax_amount, currency): (
MinorUnit,
Option<MinorUnit>,
Option<MinorUnit>,
Currency,
),
) -> Result<Self, Self::Error> {
let major_unit_convertor = StringMajorUnitForConnector;
let sdk_net_amount = major_unit_convertor
.convert(net_amount, currency)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert net_amount to base unit".to_string(),
})
.attach_printable("Failed to convert net_amount to string major unit")?;
let sdk_shipping_cost = shipping_cost
.map(|cost| {
major_unit_convertor
.convert(cost, currency)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert shipping_cost to base unit".to_string(),
})
.attach_printable("Failed to convert shipping_cost to string major unit")
})
.transpose()?;
let sdk_order_tax_amount = order_tax_amount
.map(|cost| {
major_unit_convertor
.convert(cost, currency)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert order_tax_amount to base unit".to_string(),
})
.attach_printable("Failed to convert order_tax_amount to string major unit")
})
.transpose()?;
Ok(Self {
net_amount: sdk_net_amount,
shipping_cost: sdk_shipping_cost,
order_tax_amount: sdk_order_tax_amount,
})
}
}
#[cfg(feature = "v1")]
impl<F, Op, D> ToResponse<F, D, Op> for api::VerifyResponse
where
F: Clone,
Op: Debug,
D: OperationSessionGetters<F>,
{
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
fn generate_response(
_data: D,
_customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
_base_url: &str,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
) -> RouterResponse<Self> {
todo!()
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
fn generate_response(
payment_data: D,
customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
_base_url: &str,
_operation: Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
) -> RouterResponse<Self> {
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_data
.get_payment_attempt()
.payment_method_data
.clone()
.map(|data| data.parse_value("payment_method_data"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_method_data",
})?;
let payment_method_data_response =
additional_payment_method_data.map(api::PaymentMethodDataResponse::from);
Ok(services::ApplicationResponse::JsonWithHeaders((
Self {
verify_id: Some(payment_data.get_payment_intent().payment_id.clone()),
merchant_id: Some(payment_data.get_payment_intent().merchant_id.clone()),
client_secret: payment_data
.get_payment_intent()
.client_secret
.clone()
.map(Secret::new),
customer_id: customer.as_ref().map(|x| x.customer_id.clone()),
email: customer
.as_ref()
.and_then(|cus| cus.email.as_ref().map(|s| s.to_owned())),
name: customer
.as_ref()
.and_then(|cus| cus.name.as_ref().map(|s| s.to_owned())),
phone: customer
.as_ref()
.and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())),
mandate_id: payment_data
.get_mandate_id()
.and_then(|mandate_ids| mandate_ids.mandate_id.clone()),
payment_method: payment_data.get_payment_attempt().payment_method,
payment_method_data: payment_method_data_response,
payment_token: payment_data.get_token().map(ToString::to_string),
error_code: payment_data.get_payment_attempt().clone().error_code,
error_message: payment_data.get_payment_attempt().clone().error_message,
},
vec![],
)))
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
// try to use router data here so that already validated things , we don't want to repeat the validations.
// Add internal value not found and external value not found so that we can give 500 / Internal server error for internal value not found
#[allow(clippy::too_many_arguments)]
pub fn payments_to_payments_response<Op, F: Clone, D>(
_payment_data: D,
_captures: Option<Vec<storage::Capture>>,
_customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
_base_url: &str,
_operation: &Op,
_connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
_connector_http_status_code: Option<u16>,
_external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
) -> RouterResponse<api_models::payments::PaymentsResponse>
where
Op: Debug,
D: OperationSessionGetters<F>,
{
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
// try to use router data here so that already validated things , we don't want to repeat the validations.
// Add internal value not found and external value not found so that we can give 500 / Internal server error for internal value not found
#[allow(clippy::too_many_arguments)]
pub fn payments_to_payments_response<Op, F: Clone, D>(
payment_data: D,
captures: Option<Vec<storage::Capture>>,
customer: Option<domain::Customer>,
_auth_flow: services::AuthFlow,
base_url: &str,
operation: &Op,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
connector_http_status_code: Option<u16>,
external_latency: Option<u128>,
_is_latency_header_enabled: Option<bool>,
) -> RouterResponse<api::PaymentsResponse>
where
Op: Debug,
D: OperationSessionGetters<F>,
{
use std::ops::Not;
use hyperswitch_interfaces::consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE};
let payment_attempt = payment_data.get_payment_attempt().clone();
let payment_intent = payment_data.get_payment_intent().clone();
let payment_link_data = payment_data.get_payment_link_data();
let currency = payment_attempt
.currency
.as_ref()
.get_required_value("currency")?;
let amount = currency
.to_currency_base_unit(
payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "amount",
})?;
let mandate_id = payment_attempt.mandate_id.clone();
let refunds_response = payment_data.get_refunds().is_empty().not().then(|| {
payment_data
.get_refunds()
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let disputes_response = payment_data.get_disputes().is_empty().not().then(|| {
payment_data
.get_disputes()
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let incremental_authorizations_response =
payment_data.get_authorizations().is_empty().not().then(|| {
payment_data
.get_authorizations()
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let external_authentication_details = payment_data
.get_authentication()
.map(ForeignInto::foreign_into);
let attempts_response = payment_data.get_attempts().map(|attempts| {
attempts
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let captures_response = captures.map(|captures| {
captures
.into_iter()
.map(ForeignInto::foreign_into)
.collect()
});
let merchant_id = payment_attempt.merchant_id.to_owned();
let payment_method_type = payment_attempt
.payment_method_type
.as_ref()
.map(ToString::to_string)
.unwrap_or("".to_owned());
let payment_method = payment_attempt
.payment_method
.as_ref()
.map(ToString::to_string)
.unwrap_or("".to_owned());
let additional_payment_method_data: Option<api_models::payments::AdditionalPaymentData> =
payment_attempt
.payment_method_data
.clone()
.and_then(|data| match data {
serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null
_ => Some(data.parse_value("AdditionalPaymentData")),
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse the AdditionalPaymentData from payment_attempt.payment_method_data")?;
let surcharge_details =
payment_attempt
.net_amount
.get_surcharge_amount()
.map(|surcharge_amount| RequestSurchargeDetails {
surcharge_amount,
tax_amount: payment_attempt.net_amount.get_tax_on_surcharge(),
});
let merchant_decision = payment_intent.merchant_decision.to_owned();
let frm_message = payment_data.get_frm_message().map(FrmMessage::foreign_from);
let payment_method_data =
additional_payment_method_data.map(api::PaymentMethodDataResponse::from);
let payment_method_data_response = (payment_method_data.is_some()
|| payment_data
.get_address()
.get_request_payment_method_billing()
.is_some())
.then_some(api_models::payments::PaymentMethodDataResponseWithBilling {
payment_method_data,
billing: payment_data
.get_address()
.get_request_payment_method_billing()
.cloned()
.map(From::from),
});
let mut headers = connector_http_status_code
.map(|status_code| {
vec![(
X_CONNECTOR_HTTP_STATUS_CODE.to_string(),
Maskable::new_normal(status_code.to_string()),
)]
})
.unwrap_or_default();
if let Some(payment_confirm_source) = payment_intent.payment_confirm_source {
headers.push((
X_PAYMENT_CONFIRM_SOURCE.to_string(),
Maskable::new_normal(payment_confirm_source.to_string()),
))
}
// For the case when we don't have Customer data directly stored in Payment intent
let customer_table_response: Option<CustomerDetailsResponse> =
customer.as_ref().map(ForeignInto::foreign_into);
// If we have customer data in Payment Intent and if the customer is not deleted, We are populating the Retrieve response from the
// same. If the customer is deleted then we use the customer table to populate customer details
let customer_details_response =
if let Some(customer_details_raw) = payment_intent.customer_details.clone() {
let customer_details_encrypted =
serde_json::from_value::<CustomerData>(customer_details_raw.into_inner().expose());
if let Ok(customer_details_encrypted_data) = customer_details_encrypted {
Some(CustomerDetailsResponse {
id: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.id.clone()),
name: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.name.clone())
.or(customer_details_encrypted_data
.name
.or(customer.as_ref().and_then(|customer| {
customer.name.as_ref().map(|name| name.clone().into_inner())
}))),
email: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.email.clone())
.or(customer_details_encrypted_data.email.or(customer
.as_ref()
.and_then(|customer| customer.email.clone().map(pii::Email::from)))),
phone: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.phone.clone())
.or(customer_details_encrypted_data
.phone
.or(customer.as_ref().and_then(|customer| {
customer
.phone
.as_ref()
.map(|phone| phone.clone().into_inner())
}))),
phone_country_code: customer_table_response
.as_ref()
.and_then(|customer_data| customer_data.phone_country_code.clone())
.or(customer_details_encrypted_data
.phone_country_code
.or(customer
.as_ref()
.and_then(|customer| customer.phone_country_code.clone()))),
})
} else {
customer_table_response
}
} else {
customer_table_response
};
headers.extend(
external_latency
.map(|latency| {
vec![(
X_HS_LATENCY.to_string(),
Maskable::new_normal(latency.to_string()),
)]
})
.unwrap_or_default(),
);
let connector_name = payment_attempt.connector.as_deref().unwrap_or_default();
let router_return_url = helpers::create_redirect_url(
&base_url.to_string(),
&payment_attempt,
connector_name,
payment_data.get_creds_identifier(),
);
let output = if payments::is_start_pay(&operation)
&& payment_attempt.authentication_data.is_some()
{
let redirection_data = payment_attempt
.authentication_data
.clone()
.get_required_value("redirection_data")?;
let form: RedirectForm = serde_json::from_value(redirection_data)
.map_err(|_| errors::ApiErrorResponse::InternalServerError)?;
services::ApplicationResponse::Form(Box::new(services::RedirectionFormData {
redirect_form: form,
payment_method_data: payment_data.get_payment_method_data().cloned(),
amount,
currency: currency.to_string(),
}))
} else {
let mut next_action_response = None;
// Early exit for terminal payment statuses - don't evaluate next_action at all
if payment_intent.status.is_in_terminal_state() {
next_action_response = None;
} else {
let bank_transfer_next_steps = bank_transfer_next_steps_check(payment_attempt.clone())?;
let next_action_voucher = voucher_next_steps_check(payment_attempt.clone())?;
let next_action_mobile_payment = mobile_payment_next_steps_check(&payment_attempt)?;
let next_action_containing_qr_code_url =
qr_code_next_steps_check(payment_attempt.clone())?;
let papal_sdk_next_action = paypal_sdk_next_steps_check(payment_attempt.clone())?;
let next_action_containing_fetch_qr_code_url =
fetch_qr_code_url_next_steps_check(payment_attempt.clone())?;
let next_action_containing_wait_screen =
wait_screen_next_steps_check(payment_attempt.clone())?;
let next_action_containing_sdk_upi_intent =
extract_sdk_uri_information(payment_attempt.clone())?;
let next_action_invoke_hidden_frame =
next_action_invoke_hidden_frame(&payment_attempt)?;
if payment_intent.status == enums::IntentStatus::RequiresCustomerAction
|| bank_transfer_next_steps.is_some()
|| next_action_voucher.is_some()
|| next_action_containing_qr_code_url.is_some()
|| next_action_containing_wait_screen.is_some()
|| next_action_containing_sdk_upi_intent.is_some()
|| papal_sdk_next_action.is_some()
|| next_action_containing_fetch_qr_code_url.is_some()
|| payment_data.get_authentication().is_some()
{
next_action_response = bank_transfer_next_steps
.map(|bank_transfer| {
api_models::payments::NextActionData::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details: bank_transfer,
}
})
.or(next_action_voucher.map(|voucher_data| {
api_models::payments::NextActionData::DisplayVoucherInformation {
voucher_details: voucher_data,
}
}))
.or(next_action_mobile_payment.map(|mobile_payment_data| {
api_models::payments::NextActionData::CollectOtp {
consent_data_required: mobile_payment_data.consent_data_required,
}
}))
.or(next_action_containing_qr_code_url.map(|qr_code_data| {
api_models::payments::NextActionData::foreign_from(qr_code_data)
}))
.or(next_action_containing_fetch_qr_code_url.map(|fetch_qr_code_data| {
api_models::payments::NextActionData::FetchQrCodeInformation {
qr_code_fetch_url: fetch_qr_code_data.qr_code_fetch_url
}
}))
.or(papal_sdk_next_action.map(|paypal_next_action_data| {
api_models::payments::NextActionData::InvokeSdkClient{
next_action_data: paypal_next_action_data
}
}))
.or(next_action_containing_sdk_upi_intent.map(|sdk_uri_data| {
api_models::payments::NextActionData::SdkUpiIntentInformation {
sdk_uri: sdk_uri_data.sdk_uri,
}
}))
.or(next_action_containing_wait_screen.map(|wait_screen_data| {
api_models::payments::NextActionData::WaitScreenInformation {
display_from_timestamp: wait_screen_data.display_from_timestamp,
display_to_timestamp: wait_screen_data.display_to_timestamp,
poll_config: wait_screen_data.poll_config,
}
}))
.or(payment_attempt.authentication_data.as_ref().map(|_| {
// Check if iframe redirection is enabled in the business profile
let redirect_url = helpers::create_startpay_url(
base_url,
&payment_attempt,
&payment_intent,
);
// Check if redirection inside popup is enabled in the payment intent
if payment_intent.is_iframe_redirection_enabled.unwrap_or(false) {
api_models::payments::NextActionData::RedirectInsidePopup {
popup_url: redirect_url,
redirect_response_url:router_return_url
}
} else {
api_models::payments::NextActionData::RedirectToUrl {
redirect_to_url: redirect_url,
}
}
}))
.or(match payment_data.get_authentication(){
Some(authentication_store) => {
let authentication = &authentication_store.authentication;
if payment_intent.status == common_enums::IntentStatus::RequiresCustomerAction && authentication_store.cavv.is_none() && authentication.is_separate_authn_required(){
// if preAuthn and separate authentication needed.
let poll_config = payment_data.get_poll_config().unwrap_or_default();
let request_poll_id = core_utils::get_external_authentication_request_poll_id(&payment_intent.payment_id);
let payment_connector_name = payment_attempt.connector
.as_ref()
.get_required_value("connector")?;
let is_jwt_flow = authentication.is_jwt_flow()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to determine if the authentication is JWT flow")?;
Some(api_models::payments::NextActionData::ThreeDsInvoke {
three_ds_data: api_models::payments::ThreeDsData {
three_ds_authentication_url: helpers::create_authentication_url(base_url, &payment_attempt),
three_ds_authorize_url: helpers::create_authorize_url(
base_url,
&payment_attempt,
payment_connector_name,
),
three_ds_method_details: authentication.three_ds_method_url.as_ref().zip(authentication.three_ds_method_data.as_ref()).map(|(three_ds_method_url,three_ds_method_data )|{
api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData {
three_ds_method_data_submission: true,
three_ds_method_data: Some(three_ds_method_data.clone()),
three_ds_method_url: Some(three_ds_method_url.to_owned()),
three_ds_method_key: if is_jwt_flow {
Some(api_models::payments::ThreeDsMethodKey::JWT)
} else {
Some(api_models::payments::ThreeDsMethodKey::ThreeDsMethodData)
},
// In JWT flow, we need to wait for post message to get the result
consume_post_message_for_three_ds_method_completion: is_jwt_flow,
}
}).unwrap_or(api_models::payments::ThreeDsMethodData::AcsThreeDsMethodData {
three_ds_method_data_submission: false,
three_ds_method_data: None,
three_ds_method_url: None,
three_ds_method_key: None,
consume_post_message_for_three_ds_method_completion: false,
}),
poll_config: api_models::payments::PollConfigResponse {poll_id: request_poll_id, delay_in_secs: poll_config.delay_in_secs, frequency: poll_config.frequency},
message_version: authentication.message_version.as_ref()
.map(|version| version.to_string()),
directory_server_id: authentication.directory_server_id.clone(),
},
})
}else{
None
}
},
None => None
})
.or(match next_action_invoke_hidden_frame{
Some(threeds_invoke_data) => Some(construct_connector_invoke_hidden_frame(
threeds_invoke_data,
)?),
None => None
});
}
};
// next action check for third party sdk session (for ex: Apple pay through trustpay has third party sdk session response)
if third_party_sdk_session_next_action(&payment_attempt, operation) {
next_action_response = Some(
api_models::payments::NextActionData::ThirdPartySdkSessionToken {
session_token: payment_data.get_sessions_token().first().cloned(),
},
)
}
let routed_through = payment_attempt.connector.clone();
let connector_label = routed_through.as_ref().and_then(|connector_name| {
core_utils::get_connector_label(
payment_intent.business_country,
payment_intent.business_label.as_ref(),
payment_attempt.business_sub_label.as_ref(),
connector_name,
)
});
let mandate_data = payment_data.get_setup_mandate().map(|d| api::MandateData {
customer_acceptance: d.customer_acceptance.clone(),
mandate_type: d.mandate_type.clone().map(|d| match d {
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(Some(i)) => {
api::MandateType::MultiUse(Some(api::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
}))
}
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(i) => {
api::MandateType::SingleUse(api::payments::MandateAmountData {
amount: i.amount,
currency: i.currency,
start_date: i.start_date,
end_date: i.end_date,
metadata: i.metadata,
})
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(None) => {
api::MandateType::MultiUse(None)
}
}),
update_mandate_id: d.update_mandate_id.clone(),
});
let order_tax_amount = payment_data
.get_payment_attempt()
.net_amount
.get_order_tax_amount()
.or_else(|| {
payment_data
.get_payment_intent()
.tax_details
.clone()
.and_then(|tax| {
tax.payment_method_type
.map(|a| a.order_tax_amount)
.or_else(|| tax.default.map(|a| a.order_tax_amount))
})
});
let connector_mandate_id = payment_data.get_mandate_id().and_then(|mandate| {
mandate
.mandate_reference_id
.as_ref()
.and_then(|mandate_ref| match mandate_ref {
api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_reference_id,
) => connector_mandate_reference_id.get_connector_mandate_id(),
_ => None,
})
});
let connector_transaction_id = payment_attempt
.get_connector_payment_id()
.map(ToString::to_string);
let manual_retry_allowed = match payment_data.get_is_manual_retry_enabled() {
Some(true) => helpers::is_manual_retry_allowed(
&payment_intent.status,
&payment_attempt.status,
connector_request_reference_id_config,
&merchant_id,
),
Some(false) | None => None,
};
let payments_response = api::PaymentsResponse {
payment_id: payment_intent.payment_id,
merchant_id: payment_intent.merchant_id,
status: payment_intent.status,
amount: payment_attempt.net_amount.get_order_amount(),
net_amount: payment_attempt.get_total_amount(),
amount_capturable: payment_attempt.amount_capturable,
amount_received: payment_intent.amount_captured,
connector: routed_through,
client_secret: payment_intent.client_secret.map(Secret::new),
created: Some(payment_intent.created_at),
currency: currency.to_string(),
customer_id: customer.as_ref().map(|cus| cus.clone().customer_id),
customer: customer_details_response,
description: payment_intent.description,
refunds: refunds_response,
disputes: disputes_response,
attempts: attempts_response,
captures: captures_response,
mandate_id,
mandate_data,
setup_future_usage: payment_attempt.setup_future_usage_applied,
off_session: payment_intent.off_session,
capture_on: None,
capture_method: payment_attempt.capture_method,
payment_method: payment_attempt.payment_method,
payment_method_data: payment_method_data_response,
payment_token: payment_attempt.payment_token,
shipping: payment_data
.get_address()
.get_shipping()
.cloned()
.map(From::from),
billing: payment_data
.get_address()
.get_payment_billing()
.cloned()
.map(From::from),
order_details: payment_intent.order_details,
email: customer
.as_ref()
.and_then(|cus| cus.email.as_ref().map(|s| s.to_owned())),
name: customer
.as_ref()
.and_then(|cus| cus.name.as_ref().map(|s| s.to_owned())),
phone: customer
.as_ref()
.and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())),
return_url: payment_intent.return_url,
authentication_type: payment_attempt.authentication_type,
statement_descriptor_name: payment_intent.statement_descriptor_name,
statement_descriptor_suffix: payment_intent.statement_descriptor_suffix,
next_action: next_action_response,
cancellation_reason: payment_attempt.cancellation_reason,
error_code: payment_attempt
.error_code
.filter(|code| code != NO_ERROR_CODE),
error_message: payment_attempt
.error_reason
.or(payment_attempt.error_message)
.filter(|message| message != NO_ERROR_MESSAGE),
unified_code: payment_attempt.unified_code,
unified_message: payment_attempt.unified_message,
payment_experience: payment_attempt.payment_experience,
payment_method_type: payment_attempt.payment_method_type,
connector_label,
business_country: payment_intent.business_country,
business_label: payment_intent.business_label,
business_sub_label: payment_attempt.business_sub_label,
allowed_payment_method_types: payment_intent.allowed_payment_method_types,
ephemeral_key: payment_data
.get_ephemeral_key()
.map(ForeignFrom::foreign_from),
manual_retry_allowed,
connector_transaction_id,
frm_message,
metadata: payment_intent.metadata,
connector_metadata: payment_intent.connector_metadata,
feature_metadata: payment_intent.feature_metadata,
reference_id: payment_attempt.connector_response_reference_id,
payment_link: payment_link_data,
profile_id: payment_intent.profile_id,
surcharge_details,
attempt_count: payment_intent.attempt_count,
merchant_decision,
merchant_connector_id: payment_attempt.merchant_connector_id,
incremental_authorization_allowed: payment_intent.incremental_authorization_allowed,
authorization_count: payment_intent.authorization_count,
incremental_authorizations: incremental_authorizations_response,
external_authentication_details,
external_3ds_authentication_attempted: payment_attempt
.external_three_ds_authentication_attempted,
expires_on: payment_intent.session_expiry,
fingerprint: payment_intent.fingerprint_id,
browser_info: payment_attempt.browser_info,
payment_method_id: payment_attempt.payment_method_id,
network_transaction_id: payment_attempt.network_transaction_id,
payment_method_status: payment_data
.get_payment_method_info()
.map(|info| info.status),
updated: Some(payment_intent.modified_at),
split_payments: payment_attempt.charges,
frm_metadata: payment_intent.frm_metadata,
merchant_order_reference_id: payment_intent.merchant_order_reference_id,
order_tax_amount,
connector_mandate_id,
mit_category: payment_intent.mit_category,
shipping_cost: payment_intent.shipping_cost,
capture_before: payment_attempt.capture_before,
extended_authorization_applied: payment_attempt.extended_authorization_applied,
card_discovery: payment_attempt.card_discovery,
force_3ds_challenge: payment_intent.force_3ds_challenge,
force_3ds_challenge_trigger: payment_intent.force_3ds_challenge_trigger,
issuer_error_code: payment_attempt.issuer_error_code,
issuer_error_message: payment_attempt.issuer_error_message,
is_iframe_redirection_enabled: payment_intent.is_iframe_redirection_enabled,
whole_connector_response: payment_data.get_whole_connector_response(),
payment_channel: payment_intent.payment_channel,
enable_partial_authorization: payment_intent.enable_partial_authorization,
enable_overcapture: payment_intent.enable_overcapture,
is_overcapture_enabled: payment_attempt.is_overcapture_enabled,
network_details: payment_attempt
.network_details
.map(NetworkDetails::foreign_from),
is_stored_credential: payment_attempt.is_stored_credential,
request_extended_authorization: payment_attempt.request_extended_authorization,
};
services::ApplicationResponse::JsonWithHeaders((payments_response, headers))
};
metrics::PAYMENT_OPS_COUNT.add(
1,
router_env::metric_attributes!(
("operation", format!("{:?}", operation)),
("merchant", merchant_id.clone()),
("payment_method_type", payment_method_type),
("payment_method", payment_method),
),
);
Ok(output)
}
#[cfg(feature = "v1")]
pub fn third_party_sdk_session_next_action<Op>(
payment_attempt: &storage::PaymentAttempt,
operation: &Op,
) -> bool
where
Op: Debug,
{
// If the operation is confirm, we will send session token response in next action
if format!("{operation:?}").eq("PaymentConfirm") {
let condition1 = payment_attempt
.connector
.as_ref()
.map(|connector| {
matches!(connector.as_str(), "trustpay") || matches!(connector.as_str(), "payme")
})
.and_then(|is_connector_supports_third_party_sdk| {
if is_connector_supports_third_party_sdk {
payment_attempt
.payment_method
.map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::Wallet))
} else {
Some(false)
}
})
.unwrap_or(false);
// This condition to be triggered for open banking connectors, third party SDK session token will be provided
let condition2 = payment_attempt
.connector
.as_ref()
.map(|connector| matches!(connector.as_str(), "plaid"))
.and_then(|is_connector_supports_third_party_sdk| {
if is_connector_supports_third_party_sdk {
payment_attempt
.payment_method
.map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::OpenBanking))
.and_then(|first_match| {
payment_attempt
.payment_method_type
.map(|pmt| {
matches!(
pmt,
diesel_models::enums::PaymentMethodType::OpenBankingPIS
)
})
.map(|second_match| first_match && second_match)
})
} else {
Some(false)
}
})
.unwrap_or(false);
condition1 || condition2
} else {
false
}
}
pub fn qr_code_next_steps_check(
payment_attempt: storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::QrCodeInformation>> {
let qr_code_steps: Option<Result<api_models::payments::QrCodeInformation, _>> = payment_attempt
.connector_metadata
.map(|metadata| metadata.parse_value("QrCodeInformation"));
let qr_code_instructions = qr_code_steps.transpose().ok().flatten();
Ok(qr_code_instructions)
}
pub fn paypal_sdk_next_steps_check(
payment_attempt: storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::SdkNextActionData>> {
let paypal_connector_metadata: Option<Result<api_models::payments::SdkNextActionData, _>> =
payment_attempt.connector_metadata.map(|metadata| {
metadata.parse_value("SdkNextActionData").map_err(|_| {
crate::logger::warn!(
"SdkNextActionData parsing failed for paypal_connector_metadata"
)
})
});
let paypal_next_steps = paypal_connector_metadata.transpose().ok().flatten();
Ok(paypal_next_steps)
}
pub fn fetch_qr_code_url_next_steps_check(
payment_attempt: storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::FetchQrCodeInformation>> {
let qr_code_steps: Option<Result<api_models::payments::FetchQrCodeInformation, _>> =
payment_attempt
.connector_metadata
.map(|metadata| metadata.parse_value("FetchQrCodeInformation"));
let qr_code_fetch_url = qr_code_steps.transpose().ok().flatten();
Ok(qr_code_fetch_url)
}
pub fn extract_sdk_uri_information(
payment_attempt: storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::SdkUpiIntentInformation>> {
let sdk_uri_steps: Option<Result<api_models::payments::SdkUpiIntentInformation, _>> =
payment_attempt
.connector_metadata
.map(|metadata| metadata.parse_value("SdkUpiIntentInformation"));
let sdk_uri_information = sdk_uri_steps.transpose().ok().flatten();
Ok(sdk_uri_information)
}
pub fn wait_screen_next_steps_check(
payment_attempt: storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::WaitScreenInstructions>> {
let display_info_with_timer_steps: Option<
Result<api_models::payments::WaitScreenInstructions, _>,
> = payment_attempt
.connector_metadata
.map(|metadata| metadata.parse_value("WaitScreenInstructions"));
let display_info_with_timer_instructions =
display_info_with_timer_steps.transpose().ok().flatten();
Ok(display_info_with_timer_instructions)
}
pub fn next_action_invoke_hidden_frame(
payment_attempt: &storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::PaymentsConnectorThreeDsInvokeData>> {
let connector_three_ds_invoke_data: Option<
Result<api_models::payments::PaymentsConnectorThreeDsInvokeData, _>,
> = payment_attempt
.connector_metadata
.clone()
.map(|metadata| metadata.parse_value("PaymentsConnectorThreeDsInvokeData"));
let three_ds_invoke_data = connector_three_ds_invoke_data.transpose().ok().flatten();
Ok(three_ds_invoke_data)
}
pub fn construct_connector_invoke_hidden_frame(
connector_three_ds_invoke_data: api_models::payments::PaymentsConnectorThreeDsInvokeData,
) -> RouterResult<api_models::payments::NextActionData> {
let iframe_data = api_models::payments::IframeData::ThreedsInvokeAndCompleteAutorize {
three_ds_method_data_submission: connector_three_ds_invoke_data
.three_ds_method_data_submission,
three_ds_method_data: Some(connector_three_ds_invoke_data.three_ds_method_data),
three_ds_method_url: connector_three_ds_invoke_data.three_ds_method_url,
directory_server_id: connector_three_ds_invoke_data.directory_server_id,
message_version: connector_three_ds_invoke_data.message_version,
};
Ok(api_models::payments::NextActionData::InvokeHiddenIframe { iframe_data })
}
#[cfg(feature = "v1")]
impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::PaymentsResponse {
fn foreign_from((pi, pa): (storage::PaymentIntent, storage::PaymentAttempt)) -> Self {
let connector_transaction_id = pa.get_connector_payment_id().map(ToString::to_string);
Self {
payment_id: pi.payment_id,
merchant_id: pi.merchant_id,
status: pi.status,
amount: pi.amount,
amount_capturable: pa.amount_capturable,
client_secret: pi.client_secret.map(|s| s.into()),
created: Some(pi.created_at),
currency: pi.currency.map(|c| c.to_string()).unwrap_or_default(),
description: pi.description,
metadata: pi.metadata,
order_details: pi.order_details,
customer_id: pi.customer_id.clone(),
connector: pa.connector,
payment_method: pa.payment_method,
payment_method_type: pa.payment_method_type,
business_label: pi.business_label,
business_country: pi.business_country,
business_sub_label: pa.business_sub_label,
setup_future_usage: pi.setup_future_usage,
capture_method: pa.capture_method,
authentication_type: pa.authentication_type,
connector_transaction_id,
attempt_count: pi.attempt_count,
profile_id: pi.profile_id,
merchant_connector_id: pa.merchant_connector_id,
payment_method_data: pa.payment_method_data.and_then(|data| {
match data.parse_value("PaymentMethodDataResponseWithBilling") {
Ok(parsed_data) => Some(parsed_data),
Err(e) => {
router_env::logger::error!("Failed to parse 'PaymentMethodDataResponseWithBilling' from payment method data. Error: {e:?}");
None
}
}
}),
merchant_order_reference_id: pi.merchant_order_reference_id,
customer: pi.customer_details.and_then(|customer_details|
match customer_details.into_inner().expose().parse_value::<CustomerData>("CustomerData"){
Ok(parsed_data) => Some(
CustomerDetailsResponse {
id: pi.customer_id,
name: parsed_data.name,
phone: parsed_data.phone,
email: parsed_data.email,
phone_country_code:parsed_data.phone_country_code
}),
Err(e) => {
router_env::logger::error!("Failed to parse 'CustomerDetailsResponse' from payment method data. Error: {e:?}");
None
}
}
),
billing: pi.billing_details.and_then(|billing_details|
match billing_details.into_inner().expose().parse_value::<Address>("Address") {
Ok(parsed_data) => Some(parsed_data),
Err(e) => {
router_env::logger::error!("Failed to parse 'BillingAddress' from payment method data. Error: {e:?}");
None
}
}
),
shipping: pi.shipping_details.and_then(|shipping_details|
match shipping_details.into_inner().expose().parse_value::<Address>("Address") {
Ok(parsed_data) => Some(parsed_data),
Err(e) => {
router_env::logger::error!("Failed to parse 'ShippingAddress' from payment method data. Error: {e:?}");
None
}
}
),
// TODO: fill in details based on requirement
net_amount: pa.net_amount.get_total_amount(),
amount_received: None,
refunds: None,
disputes: None,
attempts: None,
captures: None,
mandate_id: None,
mandate_data: None,
off_session: None,
capture_on: None,
payment_token: None,
email: None,
name: None,
phone: None,
return_url: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
next_action: None,
cancellation_reason: None,
error_code: None,
error_message: None,
unified_code: None,
unified_message: None,
payment_experience: None,
connector_label: None,
allowed_payment_method_types: None,
ephemeral_key: None,
manual_retry_allowed: None,
frm_message: None,
connector_metadata: None,
feature_metadata: None,
reference_id: None,
payment_link: None,
surcharge_details: None,
merchant_decision: None,
incremental_authorization_allowed: None,
authorization_count: None,
incremental_authorizations: None,
external_authentication_details: None,
external_3ds_authentication_attempted: None,
expires_on: None,
fingerprint: None,
browser_info: None,
payment_method_id: None,
payment_method_status: None,
updated: None,
split_payments: None,
frm_metadata: None,
capture_before: pa.capture_before,
extended_authorization_applied: pa.extended_authorization_applied,
order_tax_amount: None,
connector_mandate_id:None,
shipping_cost: None,
card_discovery: pa.card_discovery,
mit_category: pi.mit_category,
force_3ds_challenge: pi.force_3ds_challenge,
force_3ds_challenge_trigger: pi.force_3ds_challenge_trigger,
whole_connector_response: None,
issuer_error_code: pa.issuer_error_code,
issuer_error_message: pa.issuer_error_message,
is_iframe_redirection_enabled:pi.is_iframe_redirection_enabled,
payment_channel: pi.payment_channel,
network_transaction_id: None,
enable_partial_authorization: pi.enable_partial_authorization,
enable_overcapture: pi.enable_overcapture,
is_overcapture_enabled: pa.is_overcapture_enabled,
network_details: pa.network_details.map(NetworkDetails::foreign_from),
is_stored_credential:pa.is_stored_credential,
request_extended_authorization: pa.request_extended_authorization,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<(storage::PaymentIntent, Option<storage::PaymentAttempt>)>
for api_models::payments::PaymentsListResponseItem
{
fn foreign_from((pi, pa): (storage::PaymentIntent, Option<storage::PaymentAttempt>)) -> Self {
Self {
id: pi.id,
merchant_id: pi.merchant_id,
profile_id: pi.profile_id,
customer_id: pi.customer_id,
payment_method_id: pa.as_ref().and_then(|p| p.payment_method_id.clone()),
status: pi.status,
amount: api_models::payments::PaymentAmountDetailsResponse::foreign_from((
&pi.amount_details,
pa.as_ref().map(|p| &p.amount_details),
)),
created: pi.created_at,
payment_method_type: pa.as_ref().and_then(|p| p.payment_method_type.into()),
payment_method_subtype: pa.as_ref().and_then(|p| p.payment_method_subtype.into()),
connector: pa.as_ref().and_then(|p| p.connector.clone()),
merchant_connector_id: pa.as_ref().and_then(|p| p.merchant_connector_id.clone()),
customer: None,
merchant_reference_id: pi.merchant_reference_id,
connector_payment_id: pa.as_ref().and_then(|p| p.connector_payment_id.clone()),
connector_response_reference_id: pa
.as_ref()
.and_then(|p| p.connector_response_reference_id.clone()),
metadata: pi.metadata,
description: pi.description.map(|val| val.get_string_repr().to_string()),
authentication_type: pi.authentication_type,
capture_method: Some(pi.capture_method),
setup_future_usage: Some(pi.setup_future_usage),
attempt_count: pi.attempt_count,
error: pa
.as_ref()
.and_then(|p| p.error.as_ref())
.map(api_models::payments::ErrorDetails::foreign_from),
cancellation_reason: pa.as_ref().and_then(|p| p.cancellation_reason.clone()),
order_details: None,
return_url: pi.return_url,
statement_descriptor: pi.statement_descriptor,
allowed_payment_method_types: pi.allowed_payment_method_types,
authorization_count: pi.authorization_count,
modified_at: pa.as_ref().map(|p| p.modified_at),
}
}
}
#[cfg(feature = "v1")]
impl ForeignFrom<ephemeral_key::EphemeralKey> for api::ephemeral_key::EphemeralKeyCreateResponse {
fn foreign_from(from: ephemeral_key::EphemeralKey) -> Self {
Self {
customer_id: from.customer_id,
created_at: from.created_at,
expires: from.expires,
secret: from.secret,
}
}
}
#[cfg(feature = "v1")]
pub fn bank_transfer_next_steps_check(
payment_attempt: storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::BankTransferNextStepsData>> {
let bank_transfer_next_step = if let Some(diesel_models::enums::PaymentMethod::BankTransfer) =
payment_attempt.payment_method
{
if payment_attempt.payment_method_type != Some(diesel_models::enums::PaymentMethodType::Pix)
{
let bank_transfer_next_steps: Option<api_models::payments::BankTransferNextStepsData> =
payment_attempt
.connector_metadata
.map(|metadata| {
metadata
.parse_value("NextStepsRequirements")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to parse the Value to NextRequirements struct",
)
})
.transpose()?;
bank_transfer_next_steps
} else {
None
}
} else {
None
};
Ok(bank_transfer_next_step)
}
#[cfg(feature = "v1")]
pub fn voucher_next_steps_check(
payment_attempt: storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::VoucherNextStepData>> {
let voucher_next_step = if let Some(diesel_models::enums::PaymentMethod::Voucher) =
payment_attempt.payment_method
{
let voucher_next_steps: Option<api_models::payments::VoucherNextStepData> = payment_attempt
.connector_metadata
.map(|metadata| {
metadata
.parse_value("NextStepsRequirements")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse the Value to NextRequirements struct")
})
.transpose()?;
voucher_next_steps
} else {
None
};
Ok(voucher_next_step)
}
#[cfg(feature = "v1")]
pub fn mobile_payment_next_steps_check(
payment_attempt: &storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::MobilePaymentNextStepData>> {
let mobile_payment_next_step = if let Some(diesel_models::enums::PaymentMethod::MobilePayment) =
payment_attempt.payment_method
{
let mobile_paymebnt_next_steps: Option<api_models::payments::MobilePaymentNextStepData> =
payment_attempt
.connector_metadata
.clone()
.map(|metadata| {
metadata
.parse_value("MobilePaymentNextStepData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse the Value to NextRequirements struct")
})
.transpose()?;
mobile_paymebnt_next_steps
} else {
None
};
Ok(mobile_payment_next_step)
}
impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::payments::NextActionData {
fn foreign_from(qr_info: api_models::payments::QrCodeInformation) -> Self {
match qr_info {
api_models::payments::QrCodeInformation::QrCodeUrl {
image_data_url,
qr_code_url,
display_to_timestamp,
} => Self::QrCodeInformation {
image_data_url: Some(image_data_url),
qr_code_url: Some(qr_code_url),
display_to_timestamp,
border_color: None,
display_text: None,
},
api_models::payments::QrCodeInformation::QrDataUrl {
image_data_url,
display_to_timestamp,
} => Self::QrCodeInformation {
image_data_url: Some(image_data_url),
display_to_timestamp,
qr_code_url: None,
border_color: None,
display_text: None,
},
api_models::payments::QrCodeInformation::QrCodeImageUrl {
qr_code_url,
display_to_timestamp,
} => Self::QrCodeInformation {
qr_code_url: Some(qr_code_url),
image_data_url: None,
display_to_timestamp,
border_color: None,
display_text: None,
},
api_models::payments::QrCodeInformation::QrColorDataUrl {
color_image_data_url,
display_to_timestamp,
border_color,
display_text,
} => Self::QrCodeInformation {
qr_code_url: None,
image_data_url: Some(color_image_data_url),
display_to_timestamp,
border_color,
display_text,
},
}
}
}
#[derive(Clone)]
pub struct PaymentAdditionalData<'a, F>
where
F: Clone,
{
router_base_url: String,
connector_name: String,
payment_data: PaymentData<F>,
state: &'a SessionState,
customer_data: &'a Option<domain::Customer>,
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizeData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data.clone();
let router_base_url = &additional_data.router_base_url;
let connector_name = &additional_data.connector_name;
let attempt = &payment_data.payment_attempt;
let browser_info: Option<types::BrowserInformation> = attempt
.browser_info
.clone()
.map(types::BrowserInformation::from);
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let merchant_connector_account_id_or_connector_name = payment_data
.payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(connector_name);
let webhook_url = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account_id_or_connector_name,
));
let router_return_url = Some(helpers::create_redirect_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let payment_method_data = payment_data.payment_method_data.or_else(|| {
if payment_data.mandate_id.is_some() {
Some(domain::PaymentMethodData::MandatePayment)
} else {
None
}
});
let amount = payment_data
.payment_attempt
.get_total_amount()
.get_amount_as_i64();
let customer_name = additional_data
.customer_data
.as_ref()
.and_then(|customer_data| {
customer_data
.name
.as_ref()
.map(|customer| customer.clone().into_inner())
});
let customer_id = additional_data
.customer_data
.as_ref()
.and_then(|data| data.get_id().clone().try_into().ok());
let merchant_order_reference_id = payment_data
.payment_intent
.merchant_reference_id
.map(|s| s.get_string_repr().to_string());
let shipping_cost = payment_data.payment_intent.amount_details.shipping_cost;
Ok(Self {
payment_method_data: payment_method_data
.unwrap_or(domain::PaymentMethodData::Card(domain::Card::default())),
amount,
order_tax_amount: None, // V2 doesn't currently support order tax amount
email: None, // V2 doesn't store email directly in payment_intent
customer_name,
currency: payment_data.currency,
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
capture_method: Some(payment_data.payment_intent.capture_method),
router_return_url,
webhook_url,
complete_authorize_url,
setup_future_usage: Some(payment_data.payment_intent.setup_future_usage),
mandate_id: payment_data.mandate_id.clone(),
off_session: get_off_session(payment_data.mandate_id.as_ref(), None),
customer_acceptance: None,
setup_mandate_details: None,
browser_info,
order_details: None,
order_category: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype),
surcharge_details: None,
customer_id,
request_incremental_authorization: false,
metadata: payment_data
.payment_intent
.metadata
.clone()
.map(|m| m.expose()),
authentication_data: None,
request_extended_authorization: None,
split_payments: None,
minor_amount: payment_data.payment_attempt.get_total_amount(),
merchant_order_reference_id,
integrity_object: None,
shipping_cost,
additional_payment_method_data: None,
merchant_account_id: None,
merchant_config_currency: None,
connector_testing_data: None,
order_id: None,
mit_category: None,
locale: None,
payment_channel: None,
enable_partial_authorization: None,
enable_overcapture: None,
is_stored_credential: None,
})
}
}
fn get_off_session(
mandate_id: Option<&MandateIds>,
off_session_flag: Option<bool>,
) -> Option<bool> {
match (mandate_id, off_session_flag) {
(_, Some(false)) => Some(false),
(Some(_), _) | (_, Some(true)) => Some(true),
(None, None) => None,
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthorizeData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data.clone();
let router_base_url = &additional_data.router_base_url;
let connector_name = &additional_data.connector_name;
let attempt = &payment_data.payment_attempt;
let browser_info: Option<types::BrowserInformation> = attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let connector_metadata = additional_data
.payment_data
.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()?;
let order_category = connector_metadata.as_ref().and_then(|cm| {
cm.noon
.as_ref()
.and_then(|noon| noon.order_category.clone())
});
let braintree_metadata = 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 order_details = additional_data
.payment_data
.payment_intent
.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<_>, _>>()
})
.transpose()?;
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let merchant_connector_account_id_or_connector_name = payment_data
.payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(connector_name);
let webhook_url = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account_id_or_connector_name,
));
let router_return_url = Some(helpers::create_redirect_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
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 payment_method_data = payment_data.payment_method_data.or_else(|| {
if payment_data.mandate_id.is_some() {
Some(domain::PaymentMethodData::MandatePayment)
} else {
None
}
});
let amount = payment_data.payment_attempt.get_total_amount();
let customer_name = additional_data
.customer_data
.as_ref()
.and_then(|customer_data| {
customer_data
.name
.as_ref()
.map(|customer| customer.clone().into_inner())
});
let customer_id = additional_data
.customer_data
.as_ref()
.map(|data| data.customer_id.clone());
let split_payments = payment_data.payment_intent.split_payments.clone();
let merchant_order_reference_id = payment_data
.payment_intent
.merchant_order_reference_id
.clone();
let shipping_cost = payment_data.payment_intent.shipping_cost;
let connector = api_models::enums::Connector::from_str(connector_name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector_name:?}")
})?;
let connector_testing_data = connector_metadata
.and_then(|cm| match connector {
api_models::enums::Connector::Adyen => cm
.adyen
.map(|adyen_cm| adyen_cm.testing)
.map(|testing_data| {
serde_json::to_value(testing_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse Adyen testing data")
}),
_ => None,
})
.transpose()?
.map(pii::SecretSerdeValue::new);
let is_off_session = get_off_session(
payment_data.mandate_id.as_ref(),
payment_data.payment_intent.off_session,
);
Ok(Self {
payment_method_data: (payment_method_data.get_required_value("payment_method_data")?),
setup_future_usage: payment_data.payment_attempt.setup_future_usage_applied,
mandate_id: payment_data.mandate_id.clone(),
off_session: is_off_session,
setup_mandate_details: payment_data.setup_mandate.clone(),
confirm: payment_data.payment_attempt.confirm,
statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix,
statement_descriptor: payment_data.payment_intent.statement_descriptor_name,
capture_method: payment_data.payment_attempt.capture_method,
amount: amount.get_amount_as_i64(),
order_tax_amount: payment_data
.payment_attempt
.net_amount
.get_order_tax_amount(),
minor_amount: amount,
currency: payment_data.currency,
browser_info,
email: payment_data.email,
customer_name,
payment_experience: payment_data.payment_attempt.payment_experience,
order_details,
order_category,
session_token: None,
enrolled_for_3ds: true,
related_transaction_id: None,
payment_method_type: payment_data.payment_attempt.payment_method_type,
router_return_url,
webhook_url,
complete_authorize_url,
customer_id,
surcharge_details: payment_data.surcharge_details,
request_incremental_authorization: matches!(
payment_data
.payment_intent
.request_incremental_authorization,
Some(RequestIncrementalAuthorization::True)
),
metadata: additional_data.payment_data.payment_intent.metadata,
authentication_data: payment_data
.authentication
.as_ref()
.map(AuthenticationData::foreign_try_from)
.transpose()?,
customer_acceptance: payment_data.customer_acceptance,
request_extended_authorization: attempt.request_extended_authorization,
split_payments,
merchant_order_reference_id,
integrity_object: None,
additional_payment_method_data,
shipping_cost,
merchant_account_id,
merchant_config_currency,
connector_testing_data,
mit_category: payment_data.payment_intent.mit_category,
order_id: None,
locale: Some(additional_data.state.locale.clone()),
payment_channel: payment_data.payment_intent.payment_channel,
enable_partial_authorization: payment_data.payment_intent.enable_partial_authorization,
enable_overcapture: payment_data.payment_intent.enable_overcapture,
is_stored_credential: payment_data.payment_attempt.is_stored_credential,
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsExtendAuthorizationData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsExtendAuthorizationData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let connector = api::ConnectorData::get_connector_by_name(
&additional_data.state.conf.connectors,
&additional_data.connector_name,
api::GetToken::Connector,
payment_data.payment_attempt.merchant_connector_id.clone(),
)?;
let amount = payment_data.payment_attempt.get_total_amount();
Ok(Self {
minor_amount: amount,
currency: payment_data.currency,
connector_transaction_id: connector
.connector
.connector_transaction_id(&payment_data.payment_attempt)?
.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,
connector_meta: payment_data.payment_attempt.connector_metadata,
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let capture_method = payment_data.get_capture_method();
let amount = payment_data.payment_attempt.get_total_amount();
let payment_method_type = payment_data
.payment_attempt
.get_payment_method_type()
.to_owned();
Ok(Self {
amount,
integrity_object: None,
mandate_id: payment_data.mandate_id.clone(),
connector_transaction_id: match payment_data.payment_attempt.get_connector_payment_id()
{
Some(connector_txn_id) => {
types::ResponseId::ConnectorTransactionId(connector_txn_id.to_owned())
}
None => types::ResponseId::NoResponseId,
},
encoded_data: payment_data.payment_attempt.encoded_data,
capture_method,
connector_meta: payment_data.payment_attempt.connector_metadata,
sync_type: match payment_data.multiple_capture_data {
Some(multiple_capture_data) => types::SyncRequestType::MultipleCaptureSync(
multiple_capture_data.get_pending_connector_capture_ids(),
),
None => types::SyncRequestType::SinglePaymentSync,
},
payment_method_type,
currency: payment_data.currency,
split_payments: payment_data.payment_intent.split_payments,
payment_experience: payment_data.payment_attempt.payment_experience,
connector_reference_id: payment_data
.payment_attempt
.connector_response_reference_id
.clone(),
setup_future_usage: payment_data.payment_intent.setup_future_usage,
})
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>>
for types::PaymentsIncrementalAuthorizationData
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let payment_attempt = &payment_data.payment_attempt;
let connector = api::ConnectorData::get_connector_by_name(
&additional_data.state.conf.connectors,
&additional_data.connector_name,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)?;
let incremental_details = payment_data
.incremental_authorization_details
.as_ref()
.ok_or(
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing incremental_authorization_details in payment_data"),
)?;
Ok(Self {
total_amount: incremental_details.total_amount.get_amount_as_i64(),
additional_amount: incremental_details.additional_amount.get_amount_as_i64(),
reason: incremental_details.reason.clone(),
currency: payment_data.currency,
connector_transaction_id: connector
.connector
.connector_transaction_id(payment_attempt)?
.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,
connector_meta: payment_attempt.connector_metadata.clone(),
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>>
for types::PaymentsIncrementalAuthorizationData
{
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let connector = api::ConnectorData::get_connector_by_name(
&additional_data.state.conf.connectors,
&additional_data.connector_name,
api::GetToken::Connector,
payment_data.payment_attempt.merchant_connector_id.clone(),
)?;
let incremental_details = payment_data
.incremental_authorization_details
.as_ref()
.ok_or(
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing incremental_authorization_details in payment_data"),
)?;
Ok(Self {
total_amount: incremental_details.total_amount.get_amount_as_i64(),
additional_amount: incremental_details.additional_amount.get_amount_as_i64(),
reason: incremental_details.reason.clone(),
currency: payment_data.currency,
connector_transaction_id: connector
.connector
.connector_transaction_id(&payment_data.payment_attempt)?
.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,
connector_meta: payment_data
.payment_attempt
.connector_metadata
.map(|secret| secret.expose()),
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
use masking::ExposeOptionInterface;
let payment_data = additional_data.payment_data;
let connector = api::ConnectorData::get_connector_by_name(
&additional_data.state.conf.connectors,
&additional_data.connector_name,
api::GetToken::Connector,
payment_data.payment_attempt.merchant_connector_id.clone(),
)?;
let amount_to_capture = payment_data
.payment_attempt
.amount_details
.get_amount_to_capture()
.unwrap_or(payment_data.payment_attempt.get_total_amount());
let amount = payment_data.payment_attempt.get_total_amount();
Ok(Self {
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.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
.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,
})
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCaptureData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let connector = api::ConnectorData::get_connector_by_name(
&additional_data.state.conf.connectors,
&additional_data.connector_name,
api::GetToken::Connector,
payment_data.payment_attempt.merchant_connector_id.clone(),
)?;
let amount_to_capture = payment_data
.payment_attempt
.amount_to_capture
.unwrap_or(payment_data.payment_attempt.get_total_amount());
let browser_info: Option<types::BrowserInformation> = payment_data
.payment_attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let amount = payment_data.payment_attempt.get_total_amount();
let router_base_url = &additional_data.router_base_url;
let attempt = &payment_data.payment_attempt;
let merchant_connector_account_id = payment_data
.payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.ok_or(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let webhook_url: Option<_> = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account_id,
));
Ok(Self {
capture_method: payment_data.get_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.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,
multiple_capture_data: match payment_data.multiple_capture_data {
Some(multiple_capture_data) => Some(MultipleCaptureRequestData {
capture_sequence: multiple_capture_data.get_captures_count()?,
capture_reference: multiple_capture_data
.get_latest_capture()
.capture_id
.clone(),
}),
None => None,
},
browser_info,
metadata: payment_data.payment_intent.metadata,
integrity_object: None,
split_payments: payment_data.payment_intent.split_payments,
webhook_url,
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let connector = api::ConnectorData::get_connector_by_name(
&additional_data.state.conf.connectors,
&additional_data.connector_name,
api::GetToken::Connector,
payment_data.payment_attempt.merchant_connector_id.clone(),
)?;
let browser_info: Option<types::BrowserInformation> = payment_data
.payment_attempt
.browser_info
.clone()
.map(types::BrowserInformation::from);
let amount = payment_data.payment_attempt.amount_details.get_net_amount();
let router_base_url = &additional_data.router_base_url;
let attempt = &payment_data.payment_attempt;
let merchant_connector_account_id = payment_data
.payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.ok_or(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let webhook_url: Option<_> = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account_id,
));
let capture_method = payment_data.payment_intent.capture_method;
Ok(Self {
amount: Some(amount.get_amount_as_i64()), // This should be removed once we start moving to connector module
minor_amount: Some(amount),
currency: Some(payment_data.payment_intent.amount_details.currency),
connector_transaction_id: connector
.connector
.connector_transaction_id(&payment_data.payment_attempt)?
.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,
cancellation_reason: payment_data.payment_attempt.cancellation_reason,
connector_meta: payment_data
.payment_attempt
.connector_metadata
.clone()
.expose_option(),
browser_info,
metadata: payment_data.payment_intent.metadata.expose_option(),
webhook_url,
capture_method: Some(capture_method),
})
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let connector = api::ConnectorData::get_connector_by_name(
&additional_data.state.conf.connectors,
&additional_data.connector_name,
api::GetToken::Connector,
payment_data.payment_attempt.merchant_connector_id.clone(),
)?;
let browser_info: Option<types::BrowserInformation> = payment_data
.payment_attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let amount = payment_data.payment_attempt.get_total_amount();
let router_base_url = &additional_data.router_base_url;
let attempt = &payment_data.payment_attempt;
let merchant_connector_account_id = payment_data
.payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.ok_or(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let webhook_url: Option<_> = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account_id,
));
let capture_method = payment_data.payment_attempt.capture_method;
Ok(Self {
amount: Some(amount.get_amount_as_i64()), // This should be removed once we start moving to connector module
minor_amount: Some(amount),
currency: Some(payment_data.currency),
connector_transaction_id: connector
.connector
.connector_transaction_id(&payment_data.payment_attempt)?
.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,
cancellation_reason: payment_data.payment_attempt.cancellation_reason,
connector_meta: payment_data.payment_attempt.connector_metadata,
browser_info,
metadata: payment_data.payment_intent.metadata,
webhook_url,
capture_method,
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelPostCaptureData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsCancelPostCaptureData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let connector = api::ConnectorData::get_connector_by_name(
&additional_data.state.conf.connectors,
&additional_data.connector_name,
api::GetToken::Connector,
payment_data.payment_attempt.merchant_connector_id.clone(),
)?;
let amount = payment_data.payment_attempt.get_total_amount();
Ok(Self {
minor_amount: Some(amount),
currency: Some(payment_data.currency),
connector_transaction_id: connector
.connector
.connector_transaction_id(&payment_data.payment_attempt)?
.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,
cancellation_reason: payment_data.payment_attempt.cancellation_reason,
connector_meta: payment_data.payment_attempt.connector_metadata,
})
}
}
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsApproveData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let amount = payment_data.payment_attempt.get_total_amount();
Ok(Self {
amount: Some(amount.get_amount_as_i64()), //need to change after we move to connector module
currency: Some(payment_data.currency),
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessionUpdateData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessionUpdateData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let order_tax_amount = payment_data
.payment_intent
.tax_details
.clone()
.and_then(|tax| tax.payment_method_type.map(|pmt| pmt.order_tax_amount))
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "order_tax_amount",
})?;
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.get_total_surcharge_amount())
.unwrap_or_default();
let shipping_cost = payment_data
.payment_intent
.shipping_cost
.unwrap_or_default();
// net_amount here would include amount, order_tax_amount, surcharge_amount and shipping_cost
let net_amount = payment_data.payment_intent.amount
+ order_tax_amount
+ shipping_cost
+ surcharge_amount;
Ok(Self {
amount: net_amount,
order_tax_amount,
currency: payment_data.currency,
order_amount: payment_data.payment_intent.amount,
session_id: payment_data.session_id,
shipping_cost: payment_data.payment_intent.shipping_cost,
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessionTokensData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessionTokensData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data.clone();
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.get_total_surcharge_amount())
.unwrap_or_default();
let shipping_cost = payment_data
.payment_intent
.shipping_cost
.unwrap_or_default();
// amount here would include amount, surcharge_amount and shipping_cost
let amount = payment_data.payment_intent.amount + shipping_cost + surcharge_amount;
let merchant_order_reference_id = payment_data
.payment_intent
.merchant_order_reference_id
.clone();
let router_base_url = &additional_data.router_base_url;
let connector_name = &additional_data.connector_name;
let attempt = &payment_data.payment_attempt;
let router_return_url = Some(helpers::create_redirect_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
Ok(Self {
amount, //need to change after we move to connector module
order_amount: payment_data.payment_intent.amount,
currency: payment_data.currency,
merchant_order_reference_id,
capture_method: payment_data.payment_attempt.capture_method,
shipping_cost: payment_data.payment_intent.shipping_cost,
setup_future_usage: payment_data.payment_attempt.setup_future_usage_applied,
router_return_url,
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsUpdateMetadataData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsUpdateMetadataData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data.clone();
let connector = api::ConnectorData::get_connector_by_name(
&additional_data.state.conf.connectors,
&additional_data.connector_name,
api::GetToken::Connector,
payment_data.payment_attempt.merchant_connector_id.clone(),
)?;
Ok(Self {
metadata: payment_data
.payment_intent
.metadata
.map(Secret::new)
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("payment_intent.metadata not found")?,
connector_transaction_id: connector
.connector
.connector_transaction_id(&payment_data.payment_attempt)?
.ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?,
})
}
}
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsRejectData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let amount = payment_data.payment_attempt.get_total_amount();
Ok(Self {
amount: Some(amount.get_amount_as_i64()), //need to change after we move to connector module
currency: Some(payment_data.currency),
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data.clone();
let order_details = additional_data
.payment_data
.payment_intent
.order_details
.map(|order_details| {
order_details
.iter()
.map(|data| data.to_owned().expose())
.collect()
});
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.get_total_surcharge_amount())
.unwrap_or_default();
let amount = payment_data.payment_intent.amount_details.order_amount;
let shipping_cost = payment_data
.payment_intent
.amount_details
.shipping_cost
.unwrap_or_default();
// net_amount here would include amount, surcharge_amount and shipping_cost
let net_amount = amount + surcharge_amount + shipping_cost;
let required_amount_type = StringMajorUnitForConnector;
let apple_pay_amount = required_amount_type
.convert(net_amount, payment_data.currency)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for applePay".to_string(),
})?;
let apple_pay_recurring_details = payment_data
.payment_intent
.feature_metadata
.and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details)
.map(|apple_pay_recurring_details| {
ForeignInto::foreign_into((apple_pay_recurring_details, apple_pay_amount))
});
let order_tax_amount = payment_data
.payment_intent
.amount_details
.tax_details
.clone()
.and_then(|tax| tax.get_default_tax_amount());
Ok(Self {
amount: amount.get_amount_as_i64(), //need to change once we move to connector module
minor_amount: amount,
currency: payment_data.currency,
country: payment_data.address.get_payment_method_billing().and_then(
|billing_address| {
billing_address
.address
.as_ref()
.and_then(|address| address.country)
},
),
order_details,
surcharge_details: payment_data.surcharge_details,
email: payment_data.email,
apple_pay_recurring_details,
customer_name: None,
metadata: payment_data.payment_intent.metadata,
order_tax_amount,
shipping_cost: payment_data.payment_intent.amount_details.shipping_cost,
payment_method: Some(payment_data.payment_attempt.payment_method_type),
payment_method_type: Some(payment_data.payment_attempt.payment_method_subtype),
})
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data.clone();
let order_details = additional_data
.payment_data
.payment_intent
.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<_>, _>>()
})
.transpose()?;
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.get_total_surcharge_amount())
.unwrap_or_default();
let amount = payment_data.payment_intent.amount;
let shipping_cost = payment_data
.payment_intent
.shipping_cost
.unwrap_or_default();
// net_amount here would include amount, surcharge_amount and shipping_cost
let net_amount = amount + surcharge_amount + shipping_cost;
let required_amount_type = StringMajorUnitForConnector;
let apple_pay_amount = required_amount_type
.convert(net_amount, payment_data.currency)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: "Failed to convert amount to string major unit for applePay".to_string(),
})?;
let apple_pay_recurring_details = payment_data
.payment_intent
.feature_metadata
.map(|feature_metadata| {
feature_metadata
.parse_value::<diesel_models::types::FeatureMetadata>("FeatureMetadata")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed parsing FeatureMetadata")
})
.transpose()?
.and_then(|feature_metadata| feature_metadata.apple_pay_recurring_details)
.map(|apple_pay_recurring_details| {
ForeignFrom::foreign_from((apple_pay_recurring_details, apple_pay_amount))
});
let order_tax_amount = payment_data
.payment_intent
.tax_details
.clone()
.and_then(|tax| tax.get_default_tax_amount());
let shipping_cost = payment_data.payment_intent.shipping_cost;
let metadata = payment_data
.payment_intent
.metadata
.clone()
.map(Secret::new);
Ok(Self {
amount: net_amount.get_amount_as_i64(), //need to change once we move to connector module
minor_amount: amount,
currency: payment_data.currency,
country: payment_data.address.get_payment_method_billing().and_then(
|billing_address| {
billing_address
.address
.as_ref()
.and_then(|address| address.country)
},
),
order_details,
email: payment_data.email,
surcharge_details: payment_data.surcharge_details,
apple_pay_recurring_details,
customer_name: None,
order_tax_amount,
shipping_cost,
metadata,
payment_method: payment_data.payment_attempt.payment_method,
payment_method_type: payment_data.payment_attempt.payment_method_type,
})
}
}
impl
ForeignFrom<(
diesel_models::types::ApplePayRecurringDetails,
StringMajorUnit,
)> for api_models::payments::ApplePayRecurringPaymentRequest
{
fn foreign_from(
(apple_pay_recurring_details, net_amount): (
diesel_models::types::ApplePayRecurringDetails,
StringMajorUnit,
),
) -> Self {
Self {
payment_description: apple_pay_recurring_details.payment_description,
regular_billing: api_models::payments::ApplePayRegularBillingRequest {
amount: net_amount,
label: apple_pay_recurring_details.regular_billing.label,
payment_timing: api_models::payments::ApplePayPaymentTiming::Recurring,
recurring_payment_start_date: apple_pay_recurring_details
.regular_billing
.recurring_payment_start_date,
recurring_payment_end_date: apple_pay_recurring_details
.regular_billing
.recurring_payment_end_date,
recurring_payment_interval_unit: apple_pay_recurring_details
.regular_billing
.recurring_payment_interval_unit
.map(ForeignFrom::foreign_from),
recurring_payment_interval_count: apple_pay_recurring_details
.regular_billing
.recurring_payment_interval_count,
},
billing_agreement: apple_pay_recurring_details.billing_agreement,
management_u_r_l: apple_pay_recurring_details.management_url,
}
}
}
impl ForeignFrom<diesel_models::types::ApplePayRecurringDetails>
for api_models::payments::ApplePayRecurringDetails
{
fn foreign_from(
apple_pay_recurring_details: diesel_models::types::ApplePayRecurringDetails,
) -> Self {
Self {
payment_description: apple_pay_recurring_details.payment_description,
regular_billing: ForeignFrom::foreign_from(apple_pay_recurring_details.regular_billing),
billing_agreement: apple_pay_recurring_details.billing_agreement,
management_url: apple_pay_recurring_details.management_url,
}
}
}
impl ForeignFrom<diesel_models::types::ApplePayRegularBillingDetails>
for api_models::payments::ApplePayRegularBillingDetails
{
fn foreign_from(
apple_pay_regular_billing: diesel_models::types::ApplePayRegularBillingDetails,
) -> Self {
Self {
label: apple_pay_regular_billing.label,
recurring_payment_start_date: apple_pay_regular_billing.recurring_payment_start_date,
recurring_payment_end_date: apple_pay_regular_billing.recurring_payment_end_date,
recurring_payment_interval_unit: apple_pay_regular_billing
.recurring_payment_interval_unit
.map(ForeignFrom::foreign_from),
recurring_payment_interval_count: apple_pay_regular_billing
.recurring_payment_interval_count,
}
}
}
impl ForeignFrom<diesel_models::types::RecurringPaymentIntervalUnit>
for api_models::payments::RecurringPaymentIntervalUnit
{
fn foreign_from(
apple_pay_recurring_payment_interval_unit: diesel_models::types::RecurringPaymentIntervalUnit,
) -> Self {
match apple_pay_recurring_payment_interval_unit {
diesel_models::types::RecurringPaymentIntervalUnit::Day => Self::Day,
diesel_models::types::RecurringPaymentIntervalUnit::Month => Self::Month,
diesel_models::types::RecurringPaymentIntervalUnit::Year => Self::Year,
diesel_models::types::RecurringPaymentIntervalUnit::Hour => Self::Hour,
diesel_models::types::RecurringPaymentIntervalUnit::Minute => Self::Minute,
}
}
}
impl ForeignFrom<diesel_models::types::RedirectResponse>
for api_models::payments::RedirectResponse
{
fn foreign_from(redirect_res: diesel_models::types::RedirectResponse) -> Self {
Self {
param: redirect_res.param,
json_payload: redirect_res.json_payload,
}
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequestData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let router_base_url = &additional_data.router_base_url;
let connector_name = &additional_data.connector_name;
let attempt = &payment_data.payment_attempt;
let router_return_url = Some(helpers::create_redirect_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let browser_info: Option<types::BrowserInformation> = attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let customer_name = additional_data
.customer_data
.as_ref()
.and_then(|customer_data| {
customer_data
.name
.as_ref()
.map(|customer| customer.clone().into_inner())
});
let amount = payment_data.payment_attempt.get_total_amount();
let merchant_connector_account_id_or_connector_name = payment_data
.payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(connector_name);
let webhook_url = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account_id_or_connector_name,
));
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let connector = api_models::enums::Connector::from_str(connector_name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector_name:?}")
})?;
let connector_testing_data = payment_data
.payment_intent
.connector_metadata
.as_ref()
.map(|cm| {
cm.clone()
.parse_value::<api_models::payments::ConnectorMetadata>("ConnectorMetadata")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed parsing ConnectorMetadata")
})
.transpose()?
.and_then(|cm| match connector {
api_models::enums::Connector::Adyen => cm
.adyen
.map(|adyen_cm| adyen_cm.testing)
.map(|testing_data| {
serde_json::to_value(testing_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse Adyen testing data")
}),
_ => None,
})
.transpose()?
.map(pii::SecretSerdeValue::new);
let is_off_session = get_off_session(
payment_data.mandate_id.as_ref(),
payment_data.payment_intent.off_session,
);
Ok(Self {
currency: payment_data.currency,
confirm: true,
amount: Some(amount.get_amount_as_i64()), //need to change once we move to connector module
minor_amount: Some(amount),
payment_method_data: (payment_data
.payment_method_data
.get_required_value("payment_method_data")?),
statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix,
setup_future_usage: payment_data.payment_attempt.setup_future_usage_applied,
off_session: is_off_session,
mandate_id: payment_data.mandate_id.clone(),
setup_mandate_details: payment_data.setup_mandate,
customer_acceptance: payment_data.customer_acceptance,
router_return_url,
email: payment_data.email,
customer_name,
return_url: payment_data.payment_intent.return_url,
browser_info,
payment_method_type: attempt.payment_method_type,
request_incremental_authorization: matches!(
payment_data
.payment_intent
.request_incremental_authorization,
Some(RequestIncrementalAuthorization::True)
),
metadata: payment_data.payment_intent.metadata.clone().map(Into::into),
shipping_cost: payment_data.payment_intent.shipping_cost,
webhook_url,
complete_authorize_url,
capture_method: payment_data.payment_attempt.capture_method,
connector_testing_data,
customer_id: payment_data.payment_intent.customer_id,
enable_partial_authorization: payment_data.payment_intent.enable_partial_authorization,
payment_channel: payment_data.payment_intent.payment_channel,
related_transaction_id: None,
enrolled_for_3ds: true,
is_stored_credential: payment_data.payment_attempt.is_stored_credential,
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SetupMandateRequestData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
}
impl ForeignTryFrom<types::CaptureSyncResponse> for storage::CaptureUpdate {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
capture_sync_response: types::CaptureSyncResponse,
) -> Result<Self, Self::Error> {
match capture_sync_response {
types::CaptureSyncResponse::Success {
resource_id,
status,
connector_response_reference_id,
..
} => {
let (connector_capture_id, processor_capture_data) = match resource_id {
types::ResponseId::EncodedData(_) | types::ResponseId::NoResponseId => {
(None, None)
}
types::ResponseId::ConnectorTransactionId(id) => {
let (txn_id, txn_data) =
common_utils_type::ConnectorTransactionId::form_id_and_data(id);
(Some(txn_id), txn_data)
}
};
Ok(Self::ResponseUpdate {
status: enums::CaptureStatus::foreign_try_from(status)?,
connector_capture_id,
connector_response_reference_id,
processor_capture_data,
})
}
types::CaptureSyncResponse::Error {
code,
message,
reason,
status_code,
..
} => Ok(Self::ErrorUpdate {
status: match status_code {
500..=511 => enums::CaptureStatus::Pending,
_ => enums::CaptureStatus::Failed,
},
error_code: Some(code),
error_message: Some(message),
error_reason: reason,
}),
}
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthorizeData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let router_base_url = &additional_data.router_base_url;
let connector_name = &additional_data.connector_name;
let attempt = &payment_data.payment_attempt;
let browser_info: Option<types::BrowserInformation> = payment_data
.payment_attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let redirect_response = payment_data.redirect_response.map(|redirect| {
types::CompleteAuthorizeRedirectResponse {
params: redirect.param,
payload: redirect.json_payload,
}
});
let amount = payment_data.payment_attempt.get_total_amount();
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let braintree_metadata = payment_data
.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 is_off_session = get_off_session(
payment_data.mandate_id.as_ref(),
payment_data.payment_intent.off_session,
);
Ok(Self {
setup_future_usage: payment_data.payment_intent.setup_future_usage,
mandate_id: payment_data.mandate_id.clone(),
off_session: is_off_session,
setup_mandate_details: payment_data.setup_mandate.clone(),
confirm: payment_data.payment_attempt.confirm,
statement_descriptor_suffix: payment_data.payment_intent.statement_descriptor_suffix,
capture_method: payment_data.payment_attempt.capture_method,
amount: amount.get_amount_as_i64(), // need to change once we move to connector module
minor_amount: amount,
currency: payment_data.currency,
browser_info,
email: payment_data.email,
payment_method_data: payment_data.payment_method_data,
connector_transaction_id: payment_data
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
redirect_response,
connector_meta: payment_data.payment_attempt.connector_metadata,
complete_authorize_url,
metadata: payment_data.payment_intent.metadata,
customer_acceptance: payment_data.customer_acceptance,
merchant_account_id,
merchant_config_currency,
threeds_method_comp_ind: payment_data.threeds_method_comp_ind,
is_stored_credential: payment_data.payment_attempt.is_stored_credential,
})
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::CompleteAuthorizeData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
}
#[cfg(feature = "v2")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProcessingData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
todo!()
}
}
#[cfg(feature = "v1")]
impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPreProcessingData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
let payment_method_data = payment_data.payment_method_data;
let router_base_url = &additional_data.router_base_url;
let attempt = &payment_data.payment_attempt;
let connector_name = &additional_data.connector_name;
let order_details = payment_data
.payment_intent
.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<_>, _>>()
})
.transpose()?;
let merchant_connector_account_id_or_connector_name = payment_data
.payment_attempt
.merchant_connector_id
.as_ref()
.map(|mca_id| mca_id.get_string_repr())
.unwrap_or(connector_name);
let webhook_url = Some(helpers::create_webhook_url(
router_base_url,
&attempt.merchant_id,
merchant_connector_account_id_or_connector_name,
));
let router_return_url = Some(helpers::create_redirect_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let complete_authorize_url = Some(helpers::create_complete_authorize_url(
router_base_url,
attempt,
connector_name,
payment_data.creds_identifier.as_deref(),
));
let browser_info: Option<types::BrowserInformation> = payment_data
.payment_attempt
.browser_info
.clone()
.map(|b| b.parse_value("BrowserInformation"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let amount = payment_data.payment_attempt.get_total_amount();
Ok(Self {
payment_method_data,
email: payment_data.email,
currency: Some(payment_data.currency),
amount: Some(amount.get_amount_as_i64()), // need to change this once we move to connector module
minor_amount: Some(amount),
payment_method_type: payment_data.payment_attempt.payment_method_type,
setup_mandate_details: payment_data.setup_mandate,
capture_method: payment_data.payment_attempt.capture_method,
order_details,
router_return_url,
webhook_url,
complete_authorize_url,
browser_info,
surcharge_details: payment_data.surcharge_details,
connector_transaction_id: payment_data
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
redirect_response: None,
mandate_id: payment_data.mandate_id,
related_transaction_id: None,
enrolled_for_3ds: true,
split_payments: payment_data.payment_intent.split_payments,
metadata: payment_data.payment_intent.metadata.map(Secret::new),
customer_acceptance: payment_data.customer_acceptance,
setup_future_usage: payment_data.payment_intent.setup_future_usage,
is_stored_credential: payment_data.payment_attempt.is_stored_credential,
})
}
}
impl ForeignFrom<payments::FraudCheck> for FrmMessage {
fn foreign_from(fraud_check: payments::FraudCheck) -> Self {
Self {
frm_name: fraud_check.frm_name,
frm_transaction_id: fraud_check.frm_transaction_id,
frm_transaction_type: Some(fraud_check.frm_transaction_type.to_string()),
frm_status: Some(fraud_check.frm_status.to_string()),
frm_score: fraud_check.frm_score,
frm_reason: fraud_check.frm_reason,
frm_error: fraud_check.frm_error,
}
}
}
impl ForeignFrom<CustomerDetails> for router_request_types::CustomerDetails {
fn foreign_from(customer: CustomerDetails) -> Self {
Self {
customer_id: Some(customer.id),
name: customer.name,
email: customer.email,
phone: customer.phone,
phone_country_code: customer.phone_country_code,
tax_registration_id: customer.tax_registration_id,
}
}
}
/// The response amount details in the confirm intent response will have the combined fields from
/// intent amount details and attempt amount details.
#[cfg(feature = "v2")]
impl
ForeignFrom<(
&hyperswitch_domain_models::payments::AmountDetails,
&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails,
)> for api_models::payments::PaymentAmountDetailsResponse
{
fn foreign_from(
(intent_amount_details, attempt_amount_details): (
&hyperswitch_domain_models::payments::AmountDetails,
&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails,
),
) -> Self {
Self {
order_amount: intent_amount_details.order_amount,
currency: intent_amount_details.currency,
shipping_cost: attempt_amount_details.get_shipping_cost(),
order_tax_amount: attempt_amount_details.get_order_tax_amount(),
external_tax_calculation: intent_amount_details.skip_external_tax_calculation,
surcharge_calculation: intent_amount_details.skip_surcharge_calculation,
surcharge_amount: attempt_amount_details.get_surcharge_amount(),
tax_on_surcharge: attempt_amount_details.get_tax_on_surcharge(),
net_amount: attempt_amount_details.get_net_amount(),
amount_to_capture: attempt_amount_details.get_amount_to_capture(),
amount_capturable: attempt_amount_details.get_amount_capturable(),
amount_captured: intent_amount_details.amount_captured,
}
}
}
/// The response amount details in the confirm intent response will have the combined fields from
/// intent amount details and attempt amount details.
#[cfg(feature = "v2")]
impl
ForeignFrom<(
&hyperswitch_domain_models::payments::AmountDetails,
Option<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails>,
)> for api_models::payments::PaymentAmountDetailsResponse
{
fn foreign_from(
(intent_amount_details, attempt_amount_details): (
&hyperswitch_domain_models::payments::AmountDetails,
Option<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails>,
),
) -> Self {
Self {
order_amount: intent_amount_details.order_amount,
currency: intent_amount_details.currency,
shipping_cost: attempt_amount_details
.and_then(|attempt_amount| attempt_amount.get_shipping_cost())
.or(intent_amount_details.shipping_cost),
order_tax_amount: attempt_amount_details
.and_then(|attempt_amount| attempt_amount.get_order_tax_amount())
.or(intent_amount_details
.tax_details
.as_ref()
.and_then(|tax_details| tax_details.get_default_tax_amount())),
external_tax_calculation: intent_amount_details.skip_external_tax_calculation,
surcharge_calculation: intent_amount_details.skip_surcharge_calculation,
surcharge_amount: attempt_amount_details
.and_then(|attempt| attempt.get_surcharge_amount())
.or(intent_amount_details.surcharge_amount),
tax_on_surcharge: attempt_amount_details
.and_then(|attempt| attempt.get_tax_on_surcharge())
.or(intent_amount_details.tax_on_surcharge),
net_amount: attempt_amount_details
.map(|attempt| attempt.get_net_amount())
.unwrap_or(intent_amount_details.calculate_net_amount()),
amount_to_capture: attempt_amount_details
.and_then(|attempt| attempt.get_amount_to_capture()),
amount_capturable: attempt_amount_details
.map(|attempt| attempt.get_amount_capturable())
.unwrap_or(MinorUnit::zero()),
amount_captured: intent_amount_details.amount_captured,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>
for api_models::payments::PaymentAttemptResponse
{
fn foreign_from(
attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> Self {
let payment_method_data: Option<
api_models::payments::PaymentMethodDataResponseWithBilling,
> = attempt
.payment_method_data
.clone()
.and_then(|data| serde_json::from_value(data.expose().clone()).ok());
Self {
id: attempt.get_id().to_owned(),
status: attempt.status,
amount: api_models::payments::PaymentAttemptAmountDetails::foreign_from(
&attempt.amount_details,
),
connector: attempt.connector.clone(),
error: attempt
.error
.as_ref()
.map(api_models::payments::ErrorDetails::foreign_from),
authentication_type: attempt.authentication_type,
created_at: attempt.created_at,
modified_at: attempt.modified_at,
cancellation_reason: attempt.cancellation_reason.clone(),
payment_token: attempt
.connector_token_details
.as_ref()
.and_then(|details| details.connector_mandate_id.clone()),
connector_metadata: attempt.connector_metadata.clone(),
payment_experience: attempt.payment_experience,
payment_method_type: attempt.payment_method_type,
connector_reference_id: attempt.connector_response_reference_id.clone(),
payment_method_subtype: attempt.get_payment_method_type(),
connector_payment_id: attempt
.get_connector_payment_id()
.map(|str| common_utils::types::ConnectorTransactionId::from(str.to_owned())),
payment_method_id: attempt.payment_method_id.clone(),
client_source: attempt.client_source.clone(),
client_version: attempt.client_version.clone(),
feature_metadata: attempt
.feature_metadata
.as_ref()
.map(api_models::payments::PaymentAttemptFeatureMetadata::foreign_from),
payment_method_data,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails>
for api_models::payments::PaymentAttemptAmountDetails
{
fn foreign_from(
amount: &hyperswitch_domain_models::payments::payment_attempt::AttemptAmountDetails,
) -> Self {
Self {
net_amount: amount.get_net_amount(),
amount_to_capture: amount.get_amount_to_capture(),
surcharge_amount: amount.get_surcharge_amount(),
tax_on_surcharge: amount.get_tax_on_surcharge(),
amount_capturable: amount.get_amount_capturable(),
shipping_cost: amount.get_shipping_cost(),
order_tax_amount: amount.get_order_tax_amount(),
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&diesel_models::types::BillingConnectorPaymentDetails>
for api_models::payments::BillingConnectorPaymentDetails
{
fn foreign_from(metadata: &diesel_models::types::BillingConnectorPaymentDetails) -> Self {
Self {
payment_processor_token: metadata.payment_processor_token.clone(),
connector_customer_id: metadata.connector_customer_id.clone(),
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&diesel_models::types::BillingConnectorPaymentMethodDetails>
for api_models::payments::BillingConnectorPaymentMethodDetails
{
fn foreign_from(metadata: &diesel_models::types::BillingConnectorPaymentMethodDetails) -> Self {
match metadata {
diesel_models::types::BillingConnectorPaymentMethodDetails::Card(card_details) => {
Self::Card(api_models::payments::BillingConnectorAdditionalCardInfo {
card_issuer: card_details.card_issuer.clone(),
card_network: card_details.card_network.clone(),
})
}
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&hyperswitch_domain_models::payments::payment_attempt::ErrorDetails>
for api_models::payments::ErrorDetails
{
fn foreign_from(
error_details: &hyperswitch_domain_models::payments::payment_attempt::ErrorDetails,
) -> Self {
Self {
code: error_details.code.to_owned(),
message: error_details.message.to_owned(),
reason: error_details.reason.clone(),
unified_code: error_details.unified_code.clone(),
unified_message: error_details.unified_message.clone(),
network_advice_code: error_details.network_advice_code.clone(),
network_decline_code: error_details.network_decline_code.clone(),
network_error_message: error_details.network_error_message.clone(),
}
}
}
#[cfg(feature = "v2")]
impl
ForeignFrom<
&hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata,
> for api_models::payments::PaymentAttemptFeatureMetadata
{
fn foreign_from(
feature_metadata: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptFeatureMetadata,
) -> Self {
let revenue_recovery = feature_metadata.revenue_recovery.as_ref().map(|recovery| {
api_models::payments::PaymentAttemptRevenueRecoveryData {
attempt_triggered_by: recovery.attempt_triggered_by,
charge_id: recovery.charge_id.clone(),
}
});
Self { revenue_recovery }
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<&diesel_models::types::FeatureMetadata> for api_models::payments::FeatureMetadata {
fn foreign_from(feature_metadata: &diesel_models::types::FeatureMetadata) -> Self {
let revenue_recovery = feature_metadata
.payment_revenue_recovery_metadata
.as_ref()
.map(|payment_revenue_recovery_metadata| {
api_models::payments::PaymentRevenueRecoveryMetadata {
total_retry_count: payment_revenue_recovery_metadata.total_retry_count,
payment_connector_transmission: Some(
payment_revenue_recovery_metadata.payment_connector_transmission,
),
connector: payment_revenue_recovery_metadata.connector,
billing_connector_id: payment_revenue_recovery_metadata
.billing_connector_id
.clone(),
active_attempt_payment_connector_id: payment_revenue_recovery_metadata
.active_attempt_payment_connector_id
.clone(),
payment_method_type: payment_revenue_recovery_metadata.payment_method_type,
payment_method_subtype: payment_revenue_recovery_metadata
.payment_method_subtype,
billing_connector_payment_details:
api_models::payments::BillingConnectorPaymentDetails::foreign_from(
&payment_revenue_recovery_metadata.billing_connector_payment_details,
),
invoice_next_billing_time: payment_revenue_recovery_metadata
.invoice_next_billing_time,
billing_connector_payment_method_details:payment_revenue_recovery_metadata
.billing_connector_payment_method_details.as_ref().map(api_models::payments::BillingConnectorPaymentMethodDetails::foreign_from),
first_payment_attempt_network_advice_code: payment_revenue_recovery_metadata
.first_payment_attempt_network_advice_code
.clone(),
first_payment_attempt_network_decline_code: payment_revenue_recovery_metadata
.first_payment_attempt_network_decline_code
.clone(),
first_payment_attempt_pg_error_code: payment_revenue_recovery_metadata
.first_payment_attempt_pg_error_code
.clone(),
invoice_billing_started_at_time: payment_revenue_recovery_metadata
.invoice_billing_started_at_time,
}
});
let apple_pay_details = feature_metadata
.apple_pay_recurring_details
.clone()
.map(api_models::payments::ApplePayRecurringDetails::foreign_from);
let redirect_res = feature_metadata
.redirect_response
.clone()
.map(api_models::payments::RedirectResponse::foreign_from);
Self {
revenue_recovery,
apple_pay_recurring_details: apple_pay_details,
redirect_response: redirect_res,
search_tags: feature_metadata.search_tags.clone(),
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<hyperswitch_domain_models::payments::AmountDetails>
for api_models::payments::AmountDetailsResponse
{
fn foreign_from(amount_details: hyperswitch_domain_models::payments::AmountDetails) -> Self {
Self {
order_amount: amount_details.order_amount,
currency: amount_details.currency,
shipping_cost: amount_details.shipping_cost,
order_tax_amount: amount_details.tax_details.and_then(|tax_details| {
tax_details.default.map(|default| default.order_tax_amount)
}),
external_tax_calculation: amount_details.skip_external_tax_calculation,
surcharge_calculation: amount_details.skip_surcharge_calculation,
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<api_models::admin::PaymentLinkConfigRequest>
for diesel_models::PaymentLinkConfigRequestForPayments
{
fn foreign_from(config: api_models::admin::PaymentLinkConfigRequest) -> Self {
Self {
theme: config.theme,
logo: config.logo,
seller_name: config.seller_name,
sdk_layout: config.sdk_layout,
display_sdk_only: config.display_sdk_only,
enabled_saved_payment_method: config.enabled_saved_payment_method,
hide_card_nickname_field: config.hide_card_nickname_field,
show_card_form_by_default: config.show_card_form_by_default,
details_layout: config.details_layout,
transaction_details: config.transaction_details.map(|transaction_details| {
transaction_details
.iter()
.map(|details| {
diesel_models::PaymentLinkTransactionDetails::foreign_from(details.clone())
})
.collect()
}),
background_image: config.background_image.map(|background_image| {
diesel_models::business_profile::PaymentLinkBackgroundImageConfig::foreign_from(
background_image.clone(),
)
}),
payment_button_text: config.payment_button_text,
custom_message_for_card_terms: config.custom_message_for_card_terms,
payment_button_colour: config.payment_button_colour,
skip_status_screen: config.skip_status_screen,
background_colour: config.background_colour,
payment_button_text_colour: config.payment_button_text_colour,
sdk_ui_rules: config.sdk_ui_rules,
payment_link_ui_rules: config.payment_link_ui_rules,
enable_button_only_on_form_ready: config.enable_button_only_on_form_ready,
payment_form_header_text: config.payment_form_header_text,
payment_form_label_type: config.payment_form_label_type,
show_card_terms: config.show_card_terms,
is_setup_mandate_flow: config.is_setup_mandate_flow,
color_icon_card_cvc_error: config.color_icon_card_cvc_error,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<api_models::admin::PaymentLinkTransactionDetails>
for diesel_models::PaymentLinkTransactionDetails
{
fn foreign_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self {
Self {
key: from.key,
value: from.value,
ui_configuration: from
.ui_configuration
.map(diesel_models::TransactionDetailsUiConfiguration::foreign_from),
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<api_models::admin::TransactionDetailsUiConfiguration>
for diesel_models::TransactionDetailsUiConfiguration
{
fn foreign_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self {
Self {
position: from.position,
is_key_bold: from.is_key_bold,
is_value_bold: from.is_value_bold,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<diesel_models::PaymentLinkConfigRequestForPayments>
for api_models::admin::PaymentLinkConfigRequest
{
fn foreign_from(config: diesel_models::PaymentLinkConfigRequestForPayments) -> Self {
Self {
theme: config.theme,
logo: config.logo,
seller_name: config.seller_name,
sdk_layout: config.sdk_layout,
display_sdk_only: config.display_sdk_only,
enabled_saved_payment_method: config.enabled_saved_payment_method,
hide_card_nickname_field: config.hide_card_nickname_field,
show_card_form_by_default: config.show_card_form_by_default,
details_layout: config.details_layout,
transaction_details: config.transaction_details.map(|transaction_details| {
transaction_details
.iter()
.map(|details| {
api_models::admin::PaymentLinkTransactionDetails::foreign_from(
details.clone(),
)
})
.collect()
}),
background_image: config.background_image.map(|background_image| {
api_models::admin::PaymentLinkBackgroundImageConfig::foreign_from(
background_image.clone(),
)
}),
payment_button_text: config.payment_button_text,
custom_message_for_card_terms: config.custom_message_for_card_terms,
payment_button_colour: config.payment_button_colour,
skip_status_screen: config.skip_status_screen,
background_colour: config.background_colour,
payment_button_text_colour: config.payment_button_text_colour,
sdk_ui_rules: config.sdk_ui_rules,
payment_link_ui_rules: config.payment_link_ui_rules,
enable_button_only_on_form_ready: config.enable_button_only_on_form_ready,
payment_form_header_text: config.payment_form_header_text,
payment_form_label_type: config.payment_form_label_type,
show_card_terms: config.show_card_terms,
is_setup_mandate_flow: config.is_setup_mandate_flow,
color_icon_card_cvc_error: config.color_icon_card_cvc_error,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<diesel_models::PaymentLinkTransactionDetails>
for api_models::admin::PaymentLinkTransactionDetails
{
fn foreign_from(from: diesel_models::PaymentLinkTransactionDetails) -> Self {
Self {
key: from.key,
value: from.value,
ui_configuration: from
.ui_configuration
.map(api_models::admin::TransactionDetailsUiConfiguration::foreign_from),
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<diesel_models::TransactionDetailsUiConfiguration>
for api_models::admin::TransactionDetailsUiConfiguration
{
fn foreign_from(from: diesel_models::TransactionDetailsUiConfiguration) -> Self {
Self {
position: from.position,
is_key_bold: from.is_key_bold,
is_value_bold: from.is_value_bold,
}
}
}
impl ForeignFrom<DieselConnectorMandateReferenceId> for ConnectorMandateReferenceId {
fn foreign_from(value: DieselConnectorMandateReferenceId) -> Self {
Self::new(
value.connector_mandate_id,
value.payment_method_id,
None,
value.mandate_metadata,
value.connector_mandate_request_reference_id,
)
}
}
impl ForeignFrom<ConnectorMandateReferenceId> for DieselConnectorMandateReferenceId {
fn foreign_from(value: ConnectorMandateReferenceId) -> Self {
Self {
connector_mandate_id: value.get_connector_mandate_id(),
payment_method_id: value.get_payment_method_id(),
mandate_metadata: value.get_mandate_metadata(),
connector_mandate_request_reference_id: value
.get_connector_mandate_request_reference_id(),
}
}
}
impl ForeignFrom<DieselNetworkDetails> for NetworkDetails {
fn foreign_from(value: DieselNetworkDetails) -> Self {
Self {
network_advice_code: value.network_advice_code,
}
}
}
impl ForeignFrom<NetworkDetails> for DieselNetworkDetails {
fn foreign_from(value: NetworkDetails) -> Self {
Self {
network_advice_code: value.network_advice_code,
}
}
}
#[cfg(feature = "v2")]
impl ForeignFrom<diesel_models::ConnectorTokenDetails>
for Option<api_models::payments::ConnectorTokenDetails>
{
fn foreign_from(value: diesel_models::ConnectorTokenDetails) -> Self {
let connector_token_request_reference_id =
value.connector_token_request_reference_id.clone();
value.connector_mandate_id.clone().map(|mandate_id| {
api_models::payments::ConnectorTokenDetails {
token: mandate_id,
connector_token_request_reference_id,
}
})
}
}
impl
ForeignFrom<(
Self,
Option<&api_models::payments::AdditionalPaymentData>,
Option<enums::PaymentMethod>,
)> for Option<enums::PaymentMethodType>
{
fn foreign_from(
req: (
Self,
Option<&api_models::payments::AdditionalPaymentData>,
Option<enums::PaymentMethod>,
),
) -> Self {
let (payment_method_type, additional_pm_data, payment_method) = req;
match (additional_pm_data, payment_method, payment_method_type) {
(
Some(api_models::payments::AdditionalPaymentData::Card(card_info)),
Some(enums::PaymentMethod::Card),
original_type,
) => {
let bin_card_type = card_info.card_type.as_ref().and_then(|card_type_str| {
let normalized_type = card_type_str.trim().to_lowercase();
if normalized_type.is_empty() {
return None;
}
api_models::enums::PaymentMethodType::from_str(&normalized_type)
.map_err(|_| {
crate::logger::warn!("Invalid BIN card_type: '{}'", card_type_str);
})
.ok()
});
match (original_type, bin_card_type) {
// Override when there's a mismatch
(
Some(
original @ (enums::PaymentMethodType::Debit
| enums::PaymentMethodType::Credit),
),
Some(bin_type),
) if original != bin_type => {
crate::logger::info!("BIN lookup override: {} -> {}", original, bin_type);
bin_card_type
}
// Use BIN lookup if no original type exists
(None, Some(bin_type)) => {
crate::logger::info!(
"BIN lookup override: No original payment method type, using BIN result={}",
bin_type
);
Some(bin_type)
}
// Default
_ => original_type,
}
}
// Skip BIN lookup for non-card payments
_ => payment_method_type,
}
}
}
#[cfg(feature = "v1")]
impl From<pm_types::TokenResponse> for domain::NetworkTokenData {
fn from(token_response: pm_types::TokenResponse) -> Self {
Self {
token_number: token_response.authentication_details.token,
token_exp_month: token_response.token_details.exp_month,
token_exp_year: token_response.token_details.exp_year,
token_cryptogram: Some(token_response.authentication_details.cryptogram),
card_issuer: None,
card_network: Some(token_response.network),
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
eci: None,
}
}
}
impl ForeignFrom<&hyperswitch_domain_models::router_data::ErrorResponse> for DieselNetworkDetails {
fn foreign_from(err: &hyperswitch_domain_models::router_data::ErrorResponse) -> Self {
Self {
network_advice_code: err.network_advice_code.clone(),
}
}
}
impl ForeignFrom<common_types::three_ds_decision_rule_engine::ThreeDSDecision>
for common_enums::AuthenticationType
{
fn foreign_from(
three_ds_decision: common_types::three_ds_decision_rule_engine::ThreeDSDecision,
) -> Self {
match three_ds_decision {
common_types::three_ds_decision_rule_engine::ThreeDSDecision::NoThreeDs => Self::NoThreeDs,
common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengeRequested
| common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengePreferred
| common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedTra
| common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedLowValue
| common_types::three_ds_decision_rule_engine::ThreeDSDecision::IssuerThreeDsExemptionRequested => Self::ThreeDs,
}
}
}
impl ForeignFrom<common_types::three_ds_decision_rule_engine::ThreeDSDecision>
for Option<common_enums::ScaExemptionType>
{
fn foreign_from(
three_ds_decision: common_types::three_ds_decision_rule_engine::ThreeDSDecision,
) -> Self {
match three_ds_decision {
common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedTra => {
Some(common_enums::ScaExemptionType::TransactionRiskAnalysis)
}
common_types::three_ds_decision_rule_engine::ThreeDSDecision::ThreeDsExemptionRequestedLowValue => {
Some(common_enums::ScaExemptionType::LowValue)
}
common_types::three_ds_decision_rule_engine::ThreeDSDecision::NoThreeDs
| common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengeRequested
| common_types::three_ds_decision_rule_engine::ThreeDSDecision::ChallengePreferred
| common_types::three_ds_decision_rule_engine::ThreeDSDecision::IssuerThreeDsExemptionRequested => {
None
}
}
}
}
| crates/router/src/core/payments/transformers.rs | router::src::core::payments::transformers | 52,088 | true |
// File: crates/router/src/core/payments/conditional_configs.rs
// Module: router::src::core::payments::conditional_configs
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)
}
| crates/router/src/core/payments/conditional_configs.rs | router::src::core::payments::conditional_configs | 795 | true |
// File: crates/router/src/core/payments/vault_session.rs
// Module: router::src::core::payments::vault_session
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},
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>,
merchant_context: &domain::MerchantContext,
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,
merchant_context.get_merchant_key_store(),
external_vault_source,
)
.await?,
));
let updated_customer = call_create_connector_customer_if_required(
state,
customer,
merchant_context,
&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(
&state.into(),
&customer_id,
customer,
updated_customer,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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,
merchant_context,
&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>,
merchant_context: &domain::MerchantContext,
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();
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(),
merchant_context,
customer,
merchant_connector_account_type,
None,
None,
)
.await?;
let connector_customer_id = router_data
.create_connector_customer(state, &connector)
.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,
merchant_context: &domain::MerchantContext,
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 => "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,
merchant_context,
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,
merchant_context: &domain::MerchantContext,
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,
merchant_context,
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,
merchant_context: &domain::MerchantContext,
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,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account,
None,
None,
connector_customer_id,
)
.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()
}
| crates/router/src/core/payments/vault_session.rs | router::src::core::payments::vault_session | 2,864 | true |
// File: crates/router/src/core/payments/access_token.rs
// Module: router::src::core::payments::access_token
use std::fmt::Debug;
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use hyperswitch_interfaces::api::ConnectorSpecifications;
use crate::{
consts,
core::{
errors::{self, RouterResult},
payments,
},
routes::{metrics, SessionState},
services::{self, logger},
types::{self, api as api_types, domain},
};
/// 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,
merchant_context: &domain::MerchantContext,
router_data: &types::RouterData<F, Req, Res>,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
if connector
.connector_name
.supports_access_token(router_data.payment_method)
{
let merchant_id = merchant_context.get_merchant_account().get_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 old_access_token = store
.get_access_token(merchant_id, &merchant_connector_id_or_connector_name)
.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_context.get_merchant_account().get_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,
merchant_context,
&refresh_token_router_data,
)
.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(
merchant_id,
&merchant_connector_id_or_connector_name,
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,
_merchant_context: &domain::MerchantContext,
router_data: &types::RouterData<
api_types::AccessTokenAuth,
types::AccessTokenRequestData,
types::AccessToken,
>,
) -> 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 = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.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))
}
| crates/router/src/core/payments/access_token.rs | router::src::core::payments::access_token | 2,493 | true |
// File: crates/router/src/core/payments/helpers.rs
// Module: router::src::core::payments::helpers
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;
#[cfg(feature = "v1")]
use common_enums::enums::{CallConnectorAction, ExecutionMode, GatewaySystem};
use common_enums::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};
#[cfg(feature = "v1")]
use external_services::grpc_client;
use futures::future::Either;
#[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::KlarnaSdkResponse,
};
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::{
call_connector_service,
flows::{ConstructFlowSpecificData, Feature},
operations::ValidateResult as OperationsValidateResult,
should_add_task_to_process_tracker, OperationSessionGetters, OperationSessionSetters,
TokenizationAction,
},
unified_connector_service::{
send_comparison_data, update_gateway_system_in_feature_metadata, ComparisonData,
},
};
#[cfg(feature = "v1")]
use crate::routes;
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;
let key_manager_state = &session_state.into();
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(
key_manager_state,
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(
key_manager_state,
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(
key_manager_state,
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(
key_manager_state,
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;
let key_manager_state = &state.into();
Ok(match address_id {
Some(id) => Some(
db.find_address_by_merchant_id_payment_id_address_id(
key_manager_state,
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(
key_manager_state,
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(
&state.into(),
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>,
merchant_context: &domain::MerchantContext,
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;
let key_manager_state = &state.into();
#[cfg(feature = "v1")]
let connector_name = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
mca_id,
merchant_context.get_merchant_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(key_manager_state, 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,
merchant_context,
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(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
merchant_context.get_merchant_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,
merchant_context.get_merchant_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),
)
}
}
}
None => {
if let Some(mandate_id) = request.mandate_id.clone() {
let mandate_generic_data = Box::pin(get_token_for_recurring_mandate(
state,
request,
merchant_context,
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(
&(state.into()),
merchant_context.get_merchant_key_store(),
customer_id,
merchant_context.get_merchant_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(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_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(
&(state.into()),
merchant_context.get_merchant_key_store(),
&payment_method_id,
merchant_context.get_merchant_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,
merchant_context: &domain::MerchantContext,
mandate_id: String,
) -> RouterResult<MandateGenericData> {
let db = &*state.store;
let mandate = db
.find_mandate_by_merchant_id_mandate_id(
merchant_context.get_merchant_account().get_id(),
mandate_id.as_str(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
let key_manager_state: KeyManagerState = state.into();
let original_payment_intent = mandate
.original_payment_id
.as_ref()
.async_map(|payment_id| async {
db.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
payment_id,
&mandate.merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.map_err(|err| logger::error!(mandate_original_payment_not_found=?err))
.ok()
})
.await
.flatten();
let original_payment_attempt = original_payment_intent
.as_ref()
.async_map(|payment_intent| async {
db.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
&mandate.merchant_id,
payment_intent.active_attempt.get_id().as_str(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.map_err(|err| logger::error!(mandate_original_payment_attempt_not_found=?err))
.ok()
})
.await
.flatten();
let original_payment_authorized_amount = original_payment_attempt
.clone()
.map(|pa| pa.net_amount.get_total_amount().get_amount_as_i64());
let original_payment_authorized_currency =
original_payment_intent.clone().and_then(|pi| pi.currency);
let customer = req.get_customer_id().get_required_value("customer_id")?;
let payment_method_id = {
if &mandate.customer_id != customer {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "customer_id must match mandate customer_id".into()
}))?
}
if mandate.mandate_status != storage_enums::MandateStatus::Active {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "mandate is not active".into()
}))?
};
mandate.payment_method_id.clone()
};
verify_mandate_details(
req.amount.get_required_value("amount")?.into(),
req.currency.get_required_value("currency")?,
mandate.clone(),
)?;
let payment_method = db
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method_id.as_str(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let token = Uuid::new_v4().to_string();
let payment_method_type = payment_method.get_payment_method_subtype();
let mandate_connector_details = payments::MandateConnectorDetails {
connector: mandate.connector,
merchant_connector_id: mandate.merchant_connector_id,
};
if let Some(enums::PaymentMethod::Card) = payment_method.get_payment_method_type() {
if state.conf.locker.locker_enabled {
let _ = cards::get_lookup_key_from_locker(
state,
&token,
&payment_method,
merchant_context.get_merchant_key_store(),
)
.await?;
}
if let Some(payment_method_from_request) = req.payment_method {
let pm: storage_enums::PaymentMethod = payment_method_from_request;
if payment_method
.get_payment_method_type()
.is_some_and(|payment_method| payment_method != pm)
{
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message:
"payment method in request does not match previously provided payment \
method information"
.into()
}))?
}
};
Ok(MandateGenericData {
token: Some(token),
payment_method: payment_method.get_payment_method_type(),
recurring_mandate_payment_data: Some(RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
original_payment_authorized_currency,
mandate_metadata: None,
}),
payment_method_type: payment_method.get_payment_method_subtype(),
mandate_connector: Some(mandate_connector_details),
mandate_data: None,
payment_method_info: Some(payment_method),
})
} else {
Ok(MandateGenericData {
token: None,
payment_method: payment_method.get_payment_method_type(),
recurring_mandate_payment_data: Some(RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
original_payment_authorized_currency,
mandate_metadata: None,
}),
payment_method_type: payment_method.get_payment_method_subtype(),
mandate_connector: Some(mandate_connector_details),
mandate_data: None,
payment_method_info: Some(payment_method),
})
}
}
#[instrument(skip_all)]
/// Check weather the merchant id in the request
/// and merchant id in the merchant account are same.
pub fn validate_merchant_id(
merchant_id: &id_type::MerchantId,
request_merchant_id: Option<&id_type::MerchantId>,
) -> CustomResult<(), errors::ApiErrorResponse> {
// Get Merchant Id from the merchant
// or get from merchant account
let request_merchant_id = request_merchant_id.unwrap_or(merchant_id);
utils::when(merchant_id.ne(request_merchant_id), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"Invalid `merchant_id`: {} not found in merchant account",
request_merchant_id.get_string_repr()
)
}))
})
}
#[instrument(skip_all)]
pub fn validate_request_amount_and_amount_to_capture(
op_amount: Option<api::Amount>,
op_amount_to_capture: Option<MinorUnit>,
surcharge_details: Option<RequestSurchargeDetails>,
) -> CustomResult<(), errors::ApiErrorResponse> {
match (op_amount, op_amount_to_capture) {
(None, _) => Ok(()),
(Some(_amount), None) => Ok(()),
(Some(amount), Some(amount_to_capture)) => {
match amount {
api::Amount::Value(amount_inner) => {
// If both amount and amount to capture is present
// then amount to be capture should be less than or equal to request amount
let total_capturable_amount = MinorUnit::new(amount_inner.get())
+ surcharge_details
.map(|surcharge_details| surcharge_details.get_total_surcharge_amount())
.unwrap_or_default();
utils::when(!amount_to_capture.le(&total_capturable_amount), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"amount_to_capture is greater than amount capture_amount: {amount_to_capture:?} request_amount: {amount:?}"
)
}))
})
}
api::Amount::Zero => {
// If the amount is Null but still amount_to_capture is passed this is invalid and
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "amount_to_capture should not exist for when amount = 0"
.to_string()
}))
}
}
}
}
}
#[cfg(feature = "v1")]
/// if capture method = automatic, amount_to_capture(if provided) must be equal to amount
#[instrument(skip_all)]
pub fn validate_amount_to_capture_and_capture_method(
payment_attempt: Option<&PaymentAttempt>,
request: &api_models::payments::PaymentsRequest,
) -> CustomResult<(), errors::ApiErrorResponse> {
let option_net_amount = hyperswitch_domain_models::payments::payment_attempt::NetAmount::from_payments_request_and_payment_attempt(
request,
payment_attempt,
);
let capture_method = request
.capture_method
.or(payment_attempt
.map(|payment_attempt| payment_attempt.capture_method.unwrap_or_default()))
.unwrap_or_default();
if matches!(
capture_method,
api_enums::CaptureMethod::Automatic | api_enums::CaptureMethod::SequentialAutomatic
) {
let total_capturable_amount =
option_net_amount.map(|net_amount| net_amount.get_total_amount());
let amount_to_capture = request
.amount_to_capture
.or(payment_attempt.and_then(|pa| pa.amount_to_capture));
if let Some((total_capturable_amount, amount_to_capture)) =
total_capturable_amount.zip(amount_to_capture)
{
utils::when(amount_to_capture != total_capturable_amount, || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "amount_to_capture must be equal to total_capturable_amount when capture_method = automatic".into()
}))
})
} else {
Ok(())
}
} else {
Ok(())
}
}
#[instrument(skip_all)]
pub fn validate_card_data(
payment_method_data: Option<api::PaymentMethodData>,
) -> CustomResult<(), errors::ApiErrorResponse> {
if let Some(api::PaymentMethodData::Card(card)) = payment_method_data {
let cvc = card.card_cvc.peek().to_string();
if cvc.len() < 3 || cvc.len() > 4 {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid card_cvc length".to_string()
}))?
}
let card_cvc =
cvc.parse::<u16>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_cvc",
})?;
::cards::CardSecurityCode::try_from(card_cvc).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Card CVC".to_string(),
},
)?;
validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;
}
Ok(())
}
#[instrument(skip_all)]
pub fn validate_card_expiry(
card_exp_month: &masking::Secret<String>,
card_exp_year: &masking::Secret<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let exp_month = card_exp_month
.peek()
.to_string()
.parse::<u8>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Month".to_string(),
},
)?;
let mut year_str = card_exp_year.peek().to_string();
if year_str.len() == 2 {
year_str = format!("20{year_str}");
}
let exp_year =
year_str
.parse::<u16>()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_exp_year",
})?;
let year = ::cards::CardExpirationYear::try_from(exp_year).change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid Expiry Year".to_string(),
},
)?;
let card_expiration = ::cards::CardExpiration { month, year };
let is_expired = card_expiration.is_expired().change_context(
errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid card data".to_string(),
},
)?;
if is_expired {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Card Expired".to_string()
}))?
}
Ok(())
}
pub fn infer_payment_type(
amount: api::Amount,
mandate_type: Option<&api::MandateTransactionType>,
) -> api_enums::PaymentType {
match mandate_type {
Some(api::MandateTransactionType::NewMandateTransaction) => {
if let api::Amount::Value(_) = amount {
api_enums::PaymentType::NewMandate
} else {
api_enums::PaymentType::SetupMandate
}
}
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
api_enums::PaymentType::RecurringMandate
}
None => api_enums::PaymentType::Normal,
}
}
pub fn validate_mandate(
req: impl Into<api::MandateValidationFields>,
is_confirm_operation: bool,
) -> CustomResult<Option<api::MandateTransactionType>, errors::ApiErrorResponse> {
let req: api::MandateValidationFields = req.into();
match req.validate_and_get_mandate_type().change_context(
errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
},
)? {
Some(api::MandateTransactionType::NewMandateTransaction) => {
validate_new_mandate_request(req, is_confirm_operation)?;
Ok(Some(api::MandateTransactionType::NewMandateTransaction))
}
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
validate_recurring_mandate(req)?;
Ok(Some(
api::MandateTransactionType::RecurringMandateTransaction,
))
}
None => Ok(None),
}
}
pub fn validate_recurring_details_and_token(
recurring_details: &Option<RecurringDetails>,
payment_token: &Option<String>,
mandate_id: &Option<String>,
) -> CustomResult<(), errors::ApiErrorResponse> {
utils::when(
recurring_details.is_some() && payment_token.is_some(),
|| {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Expected one out of recurring_details and payment_token but got both"
.into()
}))
},
)?;
utils::when(recurring_details.is_some() && mandate_id.is_some(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Expected one out of recurring_details and mandate_id but got both".into()
}))
})?;
Ok(())
}
pub fn validate_overcapture_request(
enable_overcapture: &Option<common_types::primitive_wrappers::EnableOvercaptureBool>,
capture_method: &Option<common_enums::CaptureMethod>,
) -> CustomResult<(), errors::ApiErrorResponse> {
if let Some(overcapture) = enable_overcapture {
utils::when(
*overcapture.deref()
&& !matches!(*capture_method, Some(common_enums::CaptureMethod::Manual)),
|| {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "Invalid overcapture request: supported only with manual capture"
.into()
}))
},
)?;
}
Ok(())
}
fn validate_new_mandate_request(
req: api::MandateValidationFields,
is_confirm_operation: bool,
) -> RouterResult<()> {
// We need not check for customer_id in the confirm request if it is already passed
// in create request
fp_utils::when(!is_confirm_operation && req.customer_id.is_none(), || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`customer_id` is mandatory for mandates".into()
}))
})?;
let mandate_data = req
.mandate_data
.clone()
.get_required_value("mandate_data")?;
// Only use this validation if the customer_acceptance is present
if mandate_data
.customer_acceptance
.map(|inner| inner.acceptance_type == api::AcceptanceType::Online && inner.online.is_none())
.unwrap_or(false)
{
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`mandate_data.customer_acceptance.online` is required when \
`mandate_data.customer_acceptance.acceptance_type` is `online`"
.into()
}))?
}
let mandate_details = match mandate_data.mandate_type {
Some(api_models::payments::MandateType::SingleUse(details)) => Some(details),
Some(api_models::payments::MandateType::MultiUse(details)) => details,
_ => None,
};
mandate_details.and_then(|md| md.start_date.zip(md.end_date)).map(|(start_date, end_date)|
utils::when (start_date >= end_date, || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`mandate_data.mandate_type.{multi_use|single_use}.start_date` should be greater than \
`mandate_data.mandate_type.{multi_use|single_use}.end_date`"
.into()
}))
})).transpose()?;
Ok(())
}
pub fn validate_customer_id_mandatory_cases(
has_setup_future_usage: bool,
customer_id: Option<&id_type::CustomerId>,
) -> RouterResult<()> {
match (has_setup_future_usage, customer_id) {
(true, None) => Err(errors::ApiErrorResponse::PreconditionFailed {
message: "customer_id is mandatory when setup_future_usage is given".to_string(),
}
.into()),
_ => Ok(()),
}
}
#[cfg(feature = "v1")]
pub fn create_startpay_url(
base_url: &str,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
) -> String {
format!(
"{}/payments/redirect/{}/{}/{}",
base_url,
payment_intent.get_id().get_string_repr(),
payment_intent.merchant_id.get_string_repr(),
payment_attempt.attempt_id
)
}
pub fn create_redirect_url(
router_base_url: &String,
payment_attempt: &PaymentAttempt,
connector_name: impl std::fmt::Display,
creds_identifier: Option<&str>,
) -> String {
let creds_identifier_path = creds_identifier.map_or_else(String::new, |cd| format!("/{cd}"));
format!(
"{}/payments/{}/{}/redirect/response/{}",
router_base_url,
payment_attempt.payment_id.get_string_repr(),
payment_attempt.merchant_id.get_string_repr(),
connector_name,
) + creds_identifier_path.as_ref()
}
pub fn create_authentication_url(
router_base_url: &str,
payment_attempt: &PaymentAttempt,
) -> String {
format!(
"{router_base_url}/payments/{}/3ds/authentication",
payment_attempt.payment_id.get_string_repr()
)
}
pub fn create_authorize_url(
router_base_url: &str,
payment_attempt: &PaymentAttempt,
connector_name: impl std::fmt::Display,
) -> String {
format!(
"{}/payments/{}/{}/authorize/{}",
router_base_url,
payment_attempt.payment_id.get_string_repr(),
payment_attempt.merchant_id.get_string_repr(),
connector_name
)
}
pub fn create_webhook_url(
router_base_url: &str,
merchant_id: &id_type::MerchantId,
merchant_connector_id_or_connector_name: &str,
) -> String {
format!(
"{}/webhooks/{}/{}",
router_base_url,
merchant_id.get_string_repr(),
merchant_connector_id_or_connector_name,
)
}
pub fn create_complete_authorize_url(
router_base_url: &String,
payment_attempt: &PaymentAttempt,
connector_name: impl std::fmt::Display,
creds_identifier: Option<&str>,
) -> String {
let creds_identifier = creds_identifier.map_or_else(String::new, |creds_identifier| {
format!("/{creds_identifier}")
});
format!(
"{}/payments/{}/{}/redirect/complete/{}{}",
router_base_url,
payment_attempt.payment_id.get_string_repr(),
payment_attempt.merchant_id.get_string_repr(),
connector_name,
creds_identifier
)
}
fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> {
let recurring_details = req
.recurring_details
.get_required_value("recurring_details")?;
match recurring_details {
RecurringDetails::ProcessorPaymentToken(_)
| RecurringDetails::NetworkTransactionIdAndCardDetails(_) => Ok(()),
_ => {
req.customer_id.check_value_present("customer_id")?;
let confirm = req.confirm.get_required_value("confirm")?;
if !confirm {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`confirm` must be `true` for mandates".into()
}))?
}
let off_session = req.off_session.get_required_value("off_session")?;
if !off_session {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "`off_session` should be `true` for mandates".into()
}))?
}
Ok(())
}
}
}
pub fn verify_mandate_details(
request_amount: MinorUnit,
request_currency: api_enums::Currency,
mandate: storage::Mandate,
) -> RouterResult<()> {
match mandate.mandate_type {
storage_enums::MandateType::SingleUse => utils::when(
mandate
.mandate_amount
.map(|mandate_amount| request_amount.get_amount_as_i64() > mandate_amount)
.unwrap_or(true),
|| {
Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
reason: "request amount is greater than mandate amount".into()
}))
},
),
storage::enums::MandateType::MultiUse => utils::when(
mandate
.mandate_amount
.map(|mandate_amount| {
(mandate.amount_captured.unwrap_or(0) + request_amount.get_amount_as_i64())
> mandate_amount
})
.unwrap_or(false),
|| {
Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
reason: "request amount is greater than mandate amount".into()
}))
},
),
}?;
utils::when(
mandate
.mandate_currency
.map(|mandate_currency| mandate_currency != request_currency)
.unwrap_or(false),
|| {
Err(report!(errors::ApiErrorResponse::MandateValidationFailed {
reason: "cross currency mandates not supported".into()
}))
},
)
}
pub fn verify_mandate_details_for_recurring_payments(
mandate_merchant_id: &id_type::MerchantId,
merchant_id: &id_type::MerchantId,
mandate_customer_id: &id_type::CustomerId,
customer_id: &id_type::CustomerId,
) -> RouterResult<()> {
if mandate_merchant_id != merchant_id {
Err(report!(errors::ApiErrorResponse::MandateNotFound))?
}
if mandate_customer_id != customer_id {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: "customer_id must match mandate customer_id".into()
}))?
}
Ok(())
}
#[instrument(skip_all)]
pub fn payment_attempt_status_fsm(
payment_method_data: Option<&api::payments::PaymentMethodData>,
confirm: Option<bool>,
) -> storage_enums::AttemptStatus {
match payment_method_data {
Some(_) => match confirm {
Some(true) => storage_enums::AttemptStatus::PaymentMethodAwaited,
_ => storage_enums::AttemptStatus::ConfirmationAwaited,
},
None => storage_enums::AttemptStatus::PaymentMethodAwaited,
}
}
pub fn payment_intent_status_fsm(
payment_method_data: Option<&api::PaymentMethodData>,
confirm: Option<bool>,
) -> storage_enums::IntentStatus {
match payment_method_data {
Some(_) => match confirm {
Some(true) => storage_enums::IntentStatus::RequiresPaymentMethod,
_ => storage_enums::IntentStatus::RequiresConfirmation,
},
None => storage_enums::IntentStatus::RequiresPaymentMethod,
}
}
#[cfg(feature = "v1")]
pub async fn add_domain_task_to_pt<Op>(
operation: &Op,
state: &SessionState,
payment_attempt: &PaymentAttempt,
requeue: bool,
schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse>
where
Op: std::fmt::Debug,
{
if check_if_operation_confirm(operation) {
match schedule_time {
Some(stime) => {
if !requeue {
// Here, increment the count of added tasks every time a payment has been confirmed or PSync has been called
metrics::TASKS_ADDED_COUNT.add(
1,
router_env::metric_attributes!(("flow", format!("{:#?}", operation))),
);
super::add_process_sync_task(&*state.store, payment_attempt, stime)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while adding task to process tracker")
} else {
// When the requeue is true, we reset the tasks count as we reset the task every time it is requeued
metrics::TASKS_RESET_COUNT.add(
1,
router_env::metric_attributes!(("flow", format!("{:#?}", operation))),
);
super::reset_process_sync_task(&*state.store, payment_attempt, stime)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while updating task in process tracker")
}
}
None => Ok(()),
}
} else {
Ok(())
}
}
pub fn response_operation<'a, F, R, D>() -> BoxedOperation<'a, F, R, D>
where
F: Send + Clone,
PaymentResponse: Operation<F, R, Data = D>,
{
Box::new(PaymentResponse)
}
pub fn validate_max_amount(
amount: api_models::payments::Amount,
) -> CustomResult<(), errors::ApiErrorResponse> {
match amount {
api_models::payments::Amount::Value(value) => {
utils::when(value.get() > consts::MAX_ALLOWED_AMOUNT, || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"amount should not be more than {}",
consts::MAX_ALLOWED_AMOUNT
)
}))
})
}
api_models::payments::Amount::Zero => Ok(()),
}
}
#[cfg(feature = "v1")]
/// Check whether the customer information that is sent in the root of payments request
/// and in the customer object are same, if the values mismatch return an error
pub fn validate_customer_information(
request: &api_models::payments::PaymentsRequest,
) -> RouterResult<()> {
if let Some(mismatched_fields) = request.validate_customer_details_in_request() {
let mismatched_fields = mismatched_fields.join(", ");
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"The field names `{mismatched_fields}` sent in both places is ambiguous"
),
})?
} else {
Ok(())
}
}
pub async fn validate_card_ip_blocking_for_business_profile(
state: &SessionState,
ip: IpAddr,
fingerprnt: masking::Secret<String>,
card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig,
) -> RouterResult<String> {
let cache_key = format!(
"{}_{}_{}",
consts::CARD_IP_BLOCKING_CACHE_KEY_PREFIX,
fingerprnt.peek(),
ip
);
let unsuccessful_payment_threshold = card_testing_guard_config.card_ip_blocking_threshold;
validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await
}
pub async fn validate_guest_user_card_blocking_for_business_profile(
state: &SessionState,
fingerprnt: masking::Secret<String>,
customer_id: Option<id_type::CustomerId>,
card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig,
) -> RouterResult<String> {
let cache_key = format!(
"{}_{}",
consts::GUEST_USER_CARD_BLOCKING_CACHE_KEY_PREFIX,
fingerprnt.peek()
);
let unsuccessful_payment_threshold =
card_testing_guard_config.guest_user_card_blocking_threshold;
if customer_id.is_none() {
Ok(validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await?)
} else {
Ok(cache_key)
}
}
pub async fn validate_customer_id_blocking_for_business_profile(
state: &SessionState,
customer_id: id_type::CustomerId,
profile_id: &id_type::ProfileId,
card_testing_guard_config: &diesel_models::business_profile::CardTestingGuardConfig,
) -> RouterResult<String> {
let cache_key = format!(
"{}_{}_{}",
consts::CUSTOMER_ID_BLOCKING_PREFIX,
profile_id.get_string_repr(),
customer_id.get_string_repr(),
);
let unsuccessful_payment_threshold = card_testing_guard_config.customer_id_blocking_threshold;
validate_blocking_threshold(state, unsuccessful_payment_threshold, cache_key).await
}
pub async fn validate_blocking_threshold(
state: &SessionState,
unsuccessful_payment_threshold: i32,
cache_key: String,
) -> RouterResult<String> {
match services::card_testing_guard::get_blocked_count_from_cache(state, &cache_key).await {
Ok(Some(unsuccessful_payment_count)) => {
if unsuccessful_payment_count >= unsuccessful_payment_threshold {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Blocked due to suspicious activity".to_string(),
})?
} else {
Ok(cache_key)
}
}
Ok(None) => Ok(cache_key),
Err(error) => Err(errors::ApiErrorResponse::InternalServerError).attach_printable(error)?,
}
}
#[cfg(feature = "v1")]
/// Get the customer details from customer field if present
/// or from the individual fields in `PaymentsRequest`
#[instrument(skip_all)]
pub fn get_customer_details_from_request(
request: &api_models::payments::PaymentsRequest,
) -> CustomerDetails {
let customer_id = request.get_customer_id().map(ToOwned::to_owned);
let customer_name = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.name.clone())
.or(request.name.clone());
let customer_email = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.email.clone())
.or(request.email.clone());
let customer_phone = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.phone.clone())
.or(request.phone.clone());
let customer_phone_code = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.phone_country_code.clone())
.or(request.phone_country_code.clone());
let tax_registration_id = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.tax_registration_id.clone());
CustomerDetails {
customer_id,
name: customer_name,
email: customer_email,
phone: customer_phone,
phone_country_code: customer_phone_code,
tax_registration_id,
}
}
pub async fn get_connector_default(
_state: &SessionState,
request_connector: Option<serde_json::Value>,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
Ok(request_connector.map_or(
api::ConnectorChoice::Decide,
api::ConnectorChoice::StraightThrough,
))
}
#[cfg(feature = "v2")]
pub async fn get_connector_data_from_request(
state: &SessionState,
req: Option<common_types::domain::MerchantConnectorAuthDetails>,
) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> {
let connector = req
.as_ref()
.map(|connector_details| connector_details.connector_name.to_string())
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_connector_details",
})?;
let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector,
api::GetToken::Connector,
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
Ok(connector_data)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::type_complexity)]
pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
_state: &SessionState,
_operation: BoxedOperation<'a, F, R, D>,
_payment_data: &mut PaymentData<F>,
_req: Option<CustomerDetails>,
_merchant_id: &id_type::MerchantId,
_key_store: &domain::MerchantKeyStore,
_storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::type_complexity)]
pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
state: &SessionState,
operation: BoxedOperation<'a, F, R, D>,
payment_data: &mut PaymentData<F>,
req: Option<CustomerDetails>,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> {
let request_customer_details = req
.get_required_value("customer")
.change_context(errors::StorageError::ValueNotFound("customer".to_owned()))?;
let temp_customer_data = if request_customer_details.name.is_some()
|| request_customer_details.email.is_some()
|| request_customer_details.phone.is_some()
|| request_customer_details.phone_country_code.is_some()
|| request_customer_details.tax_registration_id.is_some()
{
Some(CustomerData {
name: request_customer_details.name.clone(),
email: request_customer_details.email.clone(),
phone: request_customer_details.phone.clone(),
phone_country_code: request_customer_details.phone_country_code.clone(),
tax_registration_id: request_customer_details.tax_registration_id.clone(),
})
} else {
None
};
// Updation of Customer Details for the cases where both customer_id and specific customer
// details are provided in Payment Update Request
let raw_customer_details = payment_data
.payment_intent
.customer_details
.clone()
.map(|customer_details_encrypted| {
customer_details_encrypted
.into_inner()
.expose()
.parse_value::<CustomerData>("CustomerData")
})
.transpose()
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Failed to parse customer data from payment intent")?
.map(|parsed_customer_data| CustomerData {
name: request_customer_details
.name
.clone()
.or(parsed_customer_data.name.clone()),
email: request_customer_details
.email
.clone()
.or(parsed_customer_data.email.clone()),
phone: request_customer_details
.phone
.clone()
.or(parsed_customer_data.phone.clone()),
phone_country_code: request_customer_details
.phone_country_code
.clone()
.or(parsed_customer_data.phone_country_code.clone()),
tax_registration_id: request_customer_details
.tax_registration_id
.clone()
.or(parsed_customer_data.tax_registration_id.clone()),
})
.or(temp_customer_data);
let key_manager_state = state.into();
payment_data.payment_intent.customer_details = raw_customer_details
.clone()
.async_map(|customer_details| {
create_encrypted_data(&key_manager_state, key_store, customer_details)
})
.await
.transpose()
.change_context(errors::StorageError::EncryptionError)
.attach_printable("Unable to encrypt customer details")?;
let customer_id = request_customer_details
.customer_id
.or(payment_data.payment_intent.customer_id.clone());
let db = &*state.store;
let key_manager_state = &state.into();
let optional_customer = match customer_id {
Some(customer_id) => {
let customer_data = db
.find_customer_optional_by_customer_id_merchant_id(
key_manager_state,
&customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await?;
let key = key_store.key.get_inner().peek();
let encrypted_data = types::crypto_operation(
key_manager_state,
type_name!(domain::Customer),
types::CryptoOperation::BatchEncrypt(
domain::FromRequestEncryptableCustomer::to_encryptable(
domain::FromRequestEncryptableCustomer {
name: request_customer_details.name.clone(),
email: request_customer_details
.email
.as_ref()
.map(|e| e.clone().expose().switch_strategy()),
phone: request_customer_details.phone.clone(),
tax_registration_id: None,
},
),
),
Identifier::Merchant(key_store.merchant_id.clone()),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while Update")?;
let encryptable_customer =
domain::FromRequestEncryptableCustomer::from_encryptable(encrypted_data)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed while encrypting Customer while Update")?;
Some(match customer_data {
Some(c) => {
// Update the customer data if new data is passed in the request
if request_customer_details.email.is_some()
| request_customer_details.name.is_some()
| request_customer_details.phone.is_some()
| request_customer_details.phone_country_code.is_some()
| request_customer_details.tax_registration_id.is_some()
{
let customer_update = Update {
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<
masking::Secret<String, pii::EmailStrategy>,
> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: Box::new(encryptable_customer.phone),
phone_country_code: request_customer_details.phone_country_code,
description: None,
connector_customer: Box::new(None),
metadata: Box::new(None),
address_id: None,
tax_registration_id: encryptable_customer.tax_registration_id,
};
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_id.to_owned(),
c,
customer_update,
key_store,
storage_scheme,
)
.await
} else {
Ok(c)
}
}
None => {
let new_customer = domain::Customer {
customer_id,
merchant_id: merchant_id.to_owned(),
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<
masking::Secret<String, pii::EmailStrategy>,
> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: request_customer_details.phone_country_code.clone(),
description: None,
created_at: common_utils::date_time::now(),
metadata: None,
modified_at: common_utils::date_time::now(),
connector_customer: None,
address_id: None,
default_payment_method_id: None,
updated_by: None,
version: common_types::consts::API_VERSION,
tax_registration_id: encryptable_customer.tax_registration_id,
};
metrics::CUSTOMER_CREATED.add(1, &[]);
db.insert_customer(new_customer, key_manager_state, key_store, storage_scheme)
.await
}
})
}
None => match &payment_data.payment_intent.customer_id {
None => None,
Some(customer_id) => db
.find_customer_optional_by_customer_id_merchant_id(
key_manager_state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await?
.map(Ok),
},
};
Ok((
operation,
match optional_customer {
Some(customer) => {
let customer = customer?;
payment_data.payment_intent.customer_id = Some(customer.customer_id.clone());
payment_data.email = payment_data.email.clone().or_else(|| {
customer
.email
.clone()
.map(|encrypted_value| encrypted_value.into())
});
Some(customer)
}
None => None,
},
))
}
#[cfg(feature = "v1")]
pub async fn retrieve_payment_method_with_temporary_token(
state: &SessionState,
token: &str,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
merchant_key_store: &domain::MerchantKeyStore,
card_token_data: Option<&domain::CardToken>,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
let (pm, supplementary_data) =
vault::Vault::get_payment_method_data_from_locker(state, token, merchant_key_store)
.await
.attach_printable(
"Payment method for given token not found or there was a problem fetching it",
)?;
utils::when(
supplementary_data
.customer_id
.ne(&payment_intent.customer_id),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed { message: "customer associated with payment method and customer passed in payment are not same".into() })
},
)?;
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(match pm {
Some(domain::PaymentMethodData::Card(card)) => {
let mut updated_card = card.clone();
let mut is_card_updated = false;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
let name_on_card =
card_token_data.and_then(|token_data| token_data.card_holder_name.clone());
if let Some(name) = name_on_card.clone() {
if !name.peek().is_empty() {
is_card_updated = true;
updated_card.nick_name = name_on_card;
}
}
if let Some(token_data) = card_token_data {
if let Some(cvc) = token_data.card_cvc.clone() {
is_card_updated = true;
updated_card.card_cvc = cvc;
}
}
// populate additional card details from payment_attempt.payment_method_data (additional_payment_data) if not present in the locker
if updated_card.card_issuer.is_none()
|| updated_card.card_network.is_none()
|| updated_card.card_type.is_none()
|| updated_card.card_issuing_country.is_none()
{
let additional_payment_method_data: Option<
api_models::payments::AdditionalPaymentData,
> = payment_attempt
.payment_method_data
.clone()
.and_then(|data| match data {
serde_json::Value::Null => None, // This is to handle the case when the payment_method_data is null
_ => Some(data.parse_value("AdditionalPaymentData")),
})
.transpose()
.map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}"))
.ok()
.flatten();
if let Some(api_models::payments::AdditionalPaymentData::Card(card)) =
additional_payment_method_data
{
is_card_updated = true;
updated_card.card_issuer = updated_card.card_issuer.or(card.card_issuer);
updated_card.card_network = updated_card.card_network.or(card.card_network);
updated_card.card_type = updated_card.card_type.or(card.card_type);
updated_card.card_issuing_country = updated_card
.card_issuing_country
.or(card.card_issuing_country);
};
};
if is_card_updated {
let updated_pm = domain::PaymentMethodData::Card(updated_card);
vault::Vault::store_payment_method_data_in_locker(
state,
Some(token.to_owned()),
&updated_pm,
payment_intent.customer_id.to_owned(),
enums::PaymentMethod::Card,
merchant_key_store,
)
.await?;
Some((updated_pm, enums::PaymentMethod::Card))
} else {
Some((
domain::PaymentMethodData::Card(card),
enums::PaymentMethod::Card,
))
}
}
Some(the_pm @ domain::PaymentMethodData::Wallet(_)) => {
Some((the_pm, enums::PaymentMethod::Wallet))
}
Some(the_pm @ domain::PaymentMethodData::BankTransfer(_)) => {
Some((the_pm, enums::PaymentMethod::BankTransfer))
}
Some(the_pm @ domain::PaymentMethodData::BankRedirect(_)) => {
Some((the_pm, enums::PaymentMethod::BankRedirect))
}
Some(the_pm @ domain::PaymentMethodData::BankDebit(_)) => {
Some((the_pm, enums::PaymentMethod::BankDebit))
}
Some(_) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method received from locker is unsupported by locker")?,
None => None,
})
}
#[cfg(feature = "v2")]
pub async fn retrieve_card_with_permanent_token(
state: &SessionState,
locker_id: &str,
_payment_method_id: &id_type::GlobalPaymentMethodId,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<domain::PaymentMethodData> {
todo!()
}
pub enum VaultFetchAction {
FetchCardDetailsFromLocker,
FetchCardDetailsForNetworkTransactionIdFlowFromLocker,
FetchNetworkTokenDataFromTokenizationService(String),
FetchNetworkTokenDetailsFromLocker(api_models::payments::NetworkTokenWithNTIRef),
NoFetchAction,
}
pub fn decide_payment_method_retrieval_action(
is_network_tokenization_enabled: bool,
mandate_id: Option<api_models::payments::MandateIds>,
connector: Option<api_enums::Connector>,
network_tokenization_supported_connectors: &HashSet<api_enums::Connector>,
should_retry_with_pan: bool,
network_token_requestor_ref_id: Option<String>,
) -> VaultFetchAction {
let standard_flow = || {
determine_standard_vault_action(
is_network_tokenization_enabled,
mandate_id,
connector,
network_tokenization_supported_connectors,
network_token_requestor_ref_id,
)
};
if should_retry_with_pan {
VaultFetchAction::FetchCardDetailsFromLocker
} else {
standard_flow()
}
}
pub async fn is_ucs_enabled(state: &SessionState, config_key: &str) -> bool {
let db = state.store.as_ref();
db.find_config_by_key_unwrap_or(config_key, Some("false".to_string()))
.await
.inspect_err(|error| {
logger::error!(
?error,
"Failed to fetch `{config_key}` UCS enabled config from DB"
);
})
.ok()
.and_then(|config| {
config
.config
.parse::<bool>()
.inspect_err(|error| {
logger::error!(?error, "Failed to parse `{config_key}` UCS enabled config");
})
.ok()
})
.unwrap_or(false)
}
pub async fn should_execute_based_on_rollout(
state: &SessionState,
config_key: &str,
) -> RouterResult<bool> {
let db = state.store.as_ref();
match db.find_config_by_key(config_key).await {
Ok(rollout_config) => match rollout_config.config.parse::<f64>() {
Ok(rollout_percent) => {
if !(0.0..=1.0).contains(&rollout_percent) {
logger::warn!(
rollout_percent,
"Rollout percent out of bounds. Must be between 0.0 and 1.0"
);
return Ok(false);
}
let sampled_value: f64 = rand::thread_rng().gen_range(0.0..1.0);
Ok(sampled_value < rollout_percent)
}
Err(err) => {
logger::error!(error = ?err, "Failed to parse rollout percent");
Ok(false)
}
},
Err(err) => {
logger::error!(error = ?err, "Failed to fetch rollout config from DB");
Ok(false)
}
}
}
pub fn determine_standard_vault_action(
is_network_tokenization_enabled: bool,
mandate_id: Option<api_models::payments::MandateIds>,
connector: Option<api_enums::Connector>,
network_tokenization_supported_connectors: &HashSet<api_enums::Connector>,
network_token_requestor_ref_id: Option<String>,
) -> VaultFetchAction {
let is_network_transaction_id_flow = mandate_id
.as_ref()
.map(|mandate_ids| mandate_ids.is_network_transaction_id_flow())
.unwrap_or(false);
if !is_network_tokenization_enabled {
if is_network_transaction_id_flow {
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker
} else {
VaultFetchAction::FetchCardDetailsFromLocker
}
} else {
match mandate_id {
Some(mandate_ids) => match mandate_ids.mandate_reference_id {
Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(nt_data)) => {
VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data)
}
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => {
VaultFetchAction::NoFetchAction
}
},
None => {
//saved card flow
let is_network_token_supported_connector = connector
.map(|conn| network_tokenization_supported_connectors.contains(&conn))
.unwrap_or(false);
match (
is_network_token_supported_connector,
network_token_requestor_ref_id,
) {
(true, Some(ref_id)) => {
VaultFetchAction::FetchNetworkTokenDataFromTokenizationService(ref_id)
}
(false, Some(_)) | (true, None) | (false, None) => {
VaultFetchAction::FetchCardDetailsFromLocker
}
}
}
}
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_payment_method_data_with_permanent_token(
state: &SessionState,
locker_id: &str,
_payment_method_id: &str,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
mandate_id: Option<api_models::payments::MandateIds>,
payment_method_info: domain::PaymentMethod,
business_profile: &domain::Profile,
connector: Option<String>,
should_retry_with_pan: bool,
vault_data: Option<&domain_payments::VaultData>,
) -> RouterResult<domain::PaymentMethodData> {
let customer_id = payment_intent
.customer_id
.as_ref()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "no customer id provided for the payment".to_string(),
})?;
let network_tokenization_supported_connectors = &state
.conf
.network_tokenization_supported_connectors
.connector_list;
let connector_variant = connector
.as_ref()
.map(|conn| {
api_enums::Connector::from_str(conn.as_str())
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector:?}"))
})
.transpose()?;
let vault_fetch_action = decide_payment_method_retrieval_action(
business_profile.is_network_tokenization_enabled,
mandate_id,
connector_variant,
network_tokenization_supported_connectors,
should_retry_with_pan,
payment_method_info
.network_token_requestor_reference_id
.clone(),
);
let co_badged_card_data = payment_method_info
.get_payment_methods_data()
.and_then(|payment_methods_data| payment_methods_data.get_co_badged_card_data());
match vault_fetch_action {
VaultFetchAction::FetchCardDetailsFromLocker => {
let card = vault_data
.and_then(|vault_data| vault_data.get_card_vault_data())
.map(Ok)
.async_unwrap_or_else(|| async {
Box::pin(fetch_card_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
card_token_data,
co_badged_card_data,
payment_method_info,
merchant_key_store,
))
.await
})
.await?;
Ok(domain::PaymentMethodData::Card(card))
}
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker => {
fetch_card_details_for_network_transaction_flow_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")
}
VaultFetchAction::FetchNetworkTokenDataFromTokenizationService(
network_token_requestor_ref_id,
) => {
logger::info!("Fetching network token data from tokenization service");
match network_tokenization::get_token_from_tokenization_service(
state,
network_token_requestor_ref_id,
&payment_method_info,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch network token data from tokenization service")
{
Ok(network_token_data) => {
Ok(domain::PaymentMethodData::NetworkToken(network_token_data))
}
Err(err) => {
logger::info!(
"Failed to fetch network token data from tokenization service {err:?}"
);
logger::info!("Falling back to fetch card details from locker");
Ok(domain::PaymentMethodData::Card(
vault_data
.and_then(|vault_data| vault_data.get_card_vault_data())
.map(Ok)
.async_unwrap_or_else(|| async {
Box::pin(fetch_card_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
card_token_data,
co_badged_card_data,
payment_method_info,
merchant_key_store,
))
.await
})
.await?,
))
}
}
}
VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data) => {
if let Some(network_token_locker_id) =
payment_method_info.network_token_locker_id.as_ref()
{
let network_token_data = vault_data
.and_then(|vault_data| vault_data.get_network_token_data())
.map(Ok)
.async_unwrap_or_else(|| async {
fetch_network_token_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
network_token_locker_id,
nt_data,
)
.await
})
.await?;
Ok(domain::PaymentMethodData::NetworkToken(network_token_data))
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Network token locker id is not present")
}
}
VaultFetchAction::NoFetchAction => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method data is not present"),
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_card_with_permanent_token_for_external_authentication(
state: &SessionState,
locker_id: &str,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<domain::PaymentMethodData> {
let customer_id = payment_intent
.customer_id
.as_ref()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "no customer id provided for the payment".to_string(),
})?;
Ok(domain::PaymentMethodData::Card(
fetch_card_details_from_internal_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
card_token_data,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")?,
))
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn fetch_card_details_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
card_token_data: Option<&domain::CardToken>,
co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,
payment_method_info: domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<domain::Card> {
match &payment_method_info.vault_source_details.clone() {
domain::PaymentMethodVaultSourceDetails::ExternalVault {
ref external_vault_source,
} => {
fetch_card_details_from_external_vault(
state,
merchant_id,
card_token_data,
co_badged_card_data,
payment_method_info,
merchant_key_store,
external_vault_source,
)
.await
}
domain::PaymentMethodVaultSourceDetails::InternalVault => {
fetch_card_details_from_internal_locker(
state,
customer_id,
merchant_id,
locker_id,
card_token_data,
co_badged_card_data,
)
.await
}
}
}
#[cfg(feature = "v1")]
pub async fn fetch_card_details_from_internal_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
card_token_data: Option<&domain::CardToken>,
co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,
) -> RouterResult<domain::Card> {
logger::debug!("Fetching card details from locker");
let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")?;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
let name_on_card = if let Some(name) = card.name_on_card.clone() {
if name.clone().expose().is_empty() {
card_token_data
.and_then(|token_data| token_data.card_holder_name.clone())
.or(Some(name))
} else {
card.name_on_card
}
} else {
card_token_data.and_then(|token_data| token_data.card_holder_name.clone())
};
let api_card = api::Card {
card_number: card.card_number,
card_holder_name: name_on_card,
card_exp_month: card.card_exp_month,
card_exp_year: card.card_exp_year,
card_cvc: card_token_data
.cloned()
.unwrap_or_default()
.card_cvc
.unwrap_or_default(),
card_issuer: None,
nick_name: card.nick_name.map(masking::Secret::new),
card_network: card
.card_brand
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.map_err(|e| {
logger::error!("Failed to parse card network {e:?}");
})
.ok()
.flatten(),
card_type: None,
card_issuing_country: None,
bank_code: None,
};
Ok(domain::Card::from((api_card, co_badged_card_data)))
}
#[cfg(feature = "v1")]
pub async fn fetch_card_details_from_external_vault(
state: &SessionState,
merchant_id: &id_type::MerchantId,
card_token_data: Option<&domain::CardToken>,
co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,
payment_method_info: domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
external_vault_mca_id: &id_type::MerchantConnectorAccountId,
) -> RouterResult<domain::Card> {
let key_manager_state = &state.into();
let merchant_connector_account_details = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
external_vault_mca_id,
merchant_key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: external_vault_mca_id.get_string_repr().to_string(),
})?;
let vault_resp = vault::retrieve_payment_method_from_vault_external_v1(
state,
merchant_id,
&payment_method_info,
merchant_connector_account_details,
)
.await?;
let payment_methods_data = payment_method_info.get_payment_methods_data();
match vault_resp {
hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card) => Ok(
domain::Card::from((card, card_token_data, co_badged_card_data)),
),
hyperswitch_domain_models::vault::PaymentMethodVaultingData::CardNumber(card_number) => {
let payment_methods_data = payment_methods_data
.get_required_value("PaymentMethodsData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment methods data not present")?;
let card = payment_methods_data
.get_card_details()
.get_required_value("CardDetails")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Card details not present")?;
Ok(
domain::Card::try_from((card_number, card_token_data, co_badged_card_data, card))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to generate card data")?,
)
}
}
}
#[cfg(feature = "v1")]
pub async fn fetch_network_token_details_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
network_token_locker_id: &str,
network_transaction_data: api_models::payments::NetworkTokenWithNTIRef,
) -> RouterResult<domain::NetworkTokenData> {
let mut token_data =
cards::get_card_from_locker(state, customer_id, merchant_id, network_token_locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to fetch network token information from the permanent locker",
)?;
let expiry = network_transaction_data
.token_exp_month
.zip(network_transaction_data.token_exp_year);
if let Some((exp_month, exp_year)) = expiry {
token_data.card_exp_month = exp_month;
token_data.card_exp_year = exp_year;
}
let card_network = token_data
.card_brand
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.map_err(|e| {
logger::error!("Failed to parse card network {e:?}");
})
.ok()
.flatten();
let network_token_data = domain::NetworkTokenData {
token_number: token_data.card_number,
token_cryptogram: None,
token_exp_month: token_data.card_exp_month,
token_exp_year: token_data.card_exp_year,
nick_name: token_data.nick_name.map(masking::Secret::new),
card_issuer: None,
card_network,
card_type: None,
card_issuing_country: None,
bank_code: None,
eci: None,
};
Ok(network_token_data)
}
#[cfg(feature = "v1")]
pub async fn fetch_card_details_for_network_transaction_flow_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
) -> RouterResult<domain::PaymentMethodData> {
let card_details_from_locker =
cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card details from locker")?;
let card_network = card_details_from_locker
.card_brand
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.map_err(|e| {
logger::error!("Failed to parse card network {e:?}");
})
.ok()
.flatten();
let card_details_for_network_transaction_id =
hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId {
card_number: card_details_from_locker.card_number,
card_exp_month: card_details_from_locker.card_exp_month,
card_exp_year: card_details_from_locker.card_exp_year,
card_issuer: None,
card_network,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: card_details_from_locker.nick_name.map(masking::Secret::new),
card_holder_name: card_details_from_locker.name_on_card.clone(),
};
Ok(
domain::PaymentMethodData::CardDetailsForNetworkTransactionId(
card_details_for_network_transaction_id,
),
)
}
#[cfg(feature = "v2")]
pub async fn retrieve_payment_method_from_db_with_token_data(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<Option<domain::PaymentMethod>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn retrieve_payment_method_from_db_with_token_data(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<Option<domain::PaymentMethod>> {
match token_data {
storage::PaymentTokenData::PermanentCard(data) => {
if let Some(ref payment_method_id) = data.payment_method_id {
state
.store
.find_payment_method(
&(state.into()),
merchant_key_store,
payment_method_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("error retrieving payment method from DB")
.map(Some)
} else {
Ok(None)
}
}
storage::PaymentTokenData::WalletToken(data) => state
.store
.find_payment_method(
&(state.into()),
merchant_key_store,
&data.payment_method_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("error retrieveing payment method from DB")
.map(Some),
storage::PaymentTokenData::Temporary(_)
| storage::PaymentTokenData::TemporaryGeneric(_)
| storage::PaymentTokenData::Permanent(_)
| storage::PaymentTokenData::AuthBankDebit(_) => Ok(None),
}
}
#[cfg(feature = "v1")]
pub async fn retrieve_payment_token_data(
state: &SessionState,
token: String,
payment_method: Option<storage_enums::PaymentMethod>,
) -> RouterResult<storage::PaymentTokenData> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!(
"pm_token_{}_{}_hyperswitch",
token,
payment_method.get_required_value("payment_method")?
);
let token_data_string = redis_conn
.get_key::<Option<String>>(&key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?
.ok_or(error_stack::Report::new(
errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".to_owned(),
},
))?;
let token_data_result = token_data_string
.clone()
.parse_struct("PaymentTokenData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to deserialize hyperswitch token data");
let token_data = match token_data_result {
Ok(data) => data,
Err(e) => {
// The purpose of this logic is backwards compatibility to support tokens
// in redis that might be following the old format.
if token_data_string.starts_with('{') {
return Err(e);
} else {
storage::PaymentTokenData::temporary_generic(token_data_string)
}
}
};
Ok(token_data)
}
#[cfg(feature = "v2")]
pub async fn make_pm_data<'a, F: Clone, R, D>(
_operation: BoxedOperation<'a, F, R, D>,
_state: &'a SessionState,
_payment_data: &mut PaymentData<F>,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_storage_scheme: common_enums::enums::MerchantStorageScheme,
_business_profile: Option<&domain::Profile>,
) -> RouterResult<(
BoxedOperation<'a, F, R, D>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
todo!()
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn make_pm_data<'a, F: Clone, R, D>(
operation: BoxedOperation<'a, F, R, D>,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
storage_scheme: common_enums::enums::MerchantStorageScheme,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
BoxedOperation<'a, F, R, D>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
use super::OperationSessionSetters;
use crate::core::payments::OperationSessionGetters;
let request = payment_data.payment_method_data.clone();
let mut card_token_data = payment_data
.payment_method_data
.clone()
.and_then(|pmd| match pmd {
domain::PaymentMethodData::CardToken(token_data) => Some(token_data),
_ => None,
})
.or(Some(domain::CardToken::default()));
if let Some(cvc) = payment_data.card_cvc.clone() {
if let Some(token_data) = card_token_data.as_mut() {
token_data.card_cvc = Some(cvc);
}
}
if payment_data.token_data.is_none() {
if let Some(payment_method_info) = &payment_data.payment_method_info {
if payment_method_info.get_payment_method_type()
== Some(storage_enums::PaymentMethod::Card)
{
payment_data.token_data =
Some(storage::PaymentTokenData::PermanentCard(CardTokenData {
payment_method_id: Some(payment_method_info.get_id().clone()),
locker_id: payment_method_info
.locker_id
.clone()
.or(Some(payment_method_info.get_id().clone())),
token: payment_method_info
.locker_id
.clone()
.unwrap_or(payment_method_info.get_id().clone()),
network_token_locker_id: payment_method_info
.network_token_requestor_reference_id
.clone()
.or(Some(payment_method_info.get_id().clone())),
}));
}
}
}
let mandate_id = payment_data.mandate_id.clone();
// TODO: Handle case where payment method and token both are present in request properly.
let (payment_method, pm_id) = match (&request, payment_data.token_data.as_ref()) {
(_, Some(hyperswitch_token)) => {
let existing_vault_data = payment_data.get_vault_operation();
let vault_data = existing_vault_data.and_then(|data| match data {
domain_payments::VaultOperation::ExistingVaultData(vault_data) => Some(vault_data),
domain_payments::VaultOperation::SaveCardData(_)
| domain_payments::VaultOperation::SaveCardAndNetworkTokenData(_) => None,
});
let pm_data = Box::pin(payment_methods::retrieve_payment_method_with_token(
state,
merchant_key_store,
hyperswitch_token,
&payment_data.payment_intent,
&payment_data.payment_attempt,
card_token_data.as_ref(),
customer,
storage_scheme,
mandate_id,
payment_data.payment_method_info.clone(),
business_profile,
should_retry_with_pan,
vault_data,
))
.await;
let payment_method_details = pm_data.attach_printable("in 'make_pm_data'")?;
if let Some(ref payment_method_data) = payment_method_details.payment_method_data {
let updated_vault_operation =
domain_payments::VaultOperation::get_updated_vault_data(
existing_vault_data,
payment_method_data,
);
if let Some(vault_operation) = updated_vault_operation {
payment_data.set_vault_operation(vault_operation);
}
// Temporarily store payment method data along with the cvc in redis for saved card payments, if required by the connector based on its configs
if payment_data.token.is_none() {
let (_, payment_token) = payment_methods::retrieve_payment_method_core(
&Some(payment_method_data.clone()),
state,
&payment_data.payment_intent,
&payment_data.payment_attempt,
merchant_key_store,
Some(business_profile),
)
.await?;
payment_data.token = payment_token;
}
};
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(
if let Some(payment_method_data) = payment_method_details.payment_method_data {
payment_data.payment_attempt.payment_method =
payment_method_details.payment_method;
(
Some(payment_method_data),
payment_method_details.payment_method_id,
)
} else {
(None, payment_method_details.payment_method_id)
},
)
}
(Some(_), _) => {
let (payment_method_data, payment_token) =
payment_methods::retrieve_payment_method_core(
&request,
state,
&payment_data.payment_intent,
&payment_data.payment_attempt,
merchant_key_store,
Some(business_profile),
)
.await?;
payment_data.token = payment_token;
Ok((payment_method_data, None))
}
_ => Ok((None, None)),
}?;
Ok((operation, payment_method, pm_id))
}
#[cfg(feature = "v1")]
pub async fn store_in_vault_and_generate_ppmt(
state: &SessionState,
payment_method_data: &domain::PaymentMethodData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
payment_method: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<String> {
let router_token = vault::Vault::store_payment_method_data_in_locker(
state,
None,
payment_method_data,
payment_intent.customer_id.to_owned(),
payment_method,
merchant_key_store,
)
.await?;
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
let key_for_hyperswitch_token = payment_attempt.get_payment_method().map(|payment_method| {
payment_methods_handler::ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
payment_method,
))
});
let intent_fulfillment_time = business_profile
.and_then(|b_profile| b_profile.get_order_fulfillment_time())
.unwrap_or(consts::DEFAULT_FULFILLMENT_TIME);
if let Some(key_for_hyperswitch_token) = key_for_hyperswitch_token {
key_for_hyperswitch_token
.insert(
intent_fulfillment_time,
storage::PaymentTokenData::temporary_generic(router_token),
state,
)
.await?;
};
Ok(parent_payment_method_token)
}
#[cfg(feature = "v2")]
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
if should_store_payment_method_data_in_vault(
&state.conf.temp_locker_enable_config,
payment_attempt.connector.clone(),
payment_method,
) || payment_intent.request_external_three_ds_authentication == Some(true)
{
let parent_payment_method_token = store_in_vault_and_generate_ppmt(
state,
payment_method_data,
payment_intent,
payment_attempt,
payment_method,
merchant_key_store,
business_profile,
)
.await?;
return Ok(Some(parent_payment_method_token));
}
Ok(None)
}
pub fn should_store_payment_method_data_in_vault(
temp_locker_enable_config: &TempLockerEnableConfig,
option_connector: Option<String>,
payment_method: enums::PaymentMethod,
) -> bool {
option_connector
.map(|connector| {
temp_locker_enable_config
.0
.get(&connector)
.map(|config| config.payment_method.contains(&payment_method))
.unwrap_or(false)
})
.unwrap_or(true)
}
#[instrument(skip_all)]
pub(crate) fn validate_capture_method(
capture_method: storage_enums::CaptureMethod,
) -> RouterResult<()> {
utils::when(
capture_method == storage_enums::CaptureMethod::Automatic,
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "capture_method".to_string(),
current_flow: "captured".to_string(),
current_value: capture_method.to_string(),
states: "manual, manual_multiple, scheduled".to_string()
}))
},
)
}
#[instrument(skip_all)]
pub(crate) fn validate_status_with_capture_method(
status: storage_enums::IntentStatus,
capture_method: storage_enums::CaptureMethod,
) -> RouterResult<()> {
if status == storage_enums::IntentStatus::Processing
&& !(capture_method == storage_enums::CaptureMethod::ManualMultiple)
{
return Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "capture_method".to_string(),
current_flow: "captured".to_string(),
current_value: capture_method.to_string(),
states: "manual_multiple".to_string()
}));
}
utils::when(
status != storage_enums::IntentStatus::RequiresCapture
&& status != storage_enums::IntentStatus::PartiallyCapturedAndCapturable
&& status != storage_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
&& status != storage_enums::IntentStatus::Processing,
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "payment.status".to_string(),
current_flow: "captured".to_string(),
current_value: status.to_string(),
states: "requires_capture, partially_captured_and_capturable, processing"
.to_string()
}))
},
)
}
#[instrument(skip_all)]
pub(crate) fn validate_amount_to_capture(
amount: i64,
amount_to_capture: Option<i64>,
) -> RouterResult<()> {
utils::when(amount_to_capture.is_some_and(|value| value <= 0), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount".to_string(),
expected_format: "positive integer".to_string(),
}))
})?;
utils::when(
amount_to_capture.is_some() && (Some(amount) < amount_to_capture),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "amount_to_capture is greater than amount".to_string()
}))
},
)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub(crate) fn validate_payment_method_fields_present(
req: &api_models::payments::PaymentsRequest,
) -> RouterResult<()> {
let payment_method_data =
req.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
});
utils::when(
req.payment_method.is_none() && payment_method_data.is_some(),
|| {
Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method",
})
},
)?;
utils::when(
!matches!(
req.payment_method,
Some(api_enums::PaymentMethod::Card) | None
) && (req.payment_method_type.is_none()),
|| {
Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_type",
})
},
)?;
utils::when(
req.payment_method.is_some()
&& payment_method_data.is_none()
&& req.payment_token.is_none()
&& req.recurring_details.is_none()
&& req.ctp_service_details.is_none(),
|| {
Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_data",
})
},
)?;
utils::when(
req.payment_method.is_some() && req.payment_method_type.is_some(),
|| {
req.payment_method
.map_or(Ok(()), |req_payment_method| {
req.payment_method_type.map_or(Ok(()), |req_payment_method_type| {
if !validate_payment_method_type_against_payment_method(req_payment_method, req_payment_method_type) {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: ("payment_method_type doesn't correspond to the specified payment_method"
.to_string()),
})
} else {
Ok(())
}
})
})
},
)?;
let validate_payment_method_and_payment_method_data =
|req_payment_method_data, req_payment_method: api_enums::PaymentMethod| {
api_enums::PaymentMethod::foreign_try_from(req_payment_method_data).and_then(|payment_method|
if req_payment_method != payment_method {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: ("payment_method_data doesn't correspond to the specified payment_method"
.to_string()),
})
} else {
Ok(())
})
};
utils::when(
req.payment_method.is_some() && payment_method_data.is_some(),
|| {
payment_method_data
.cloned()
.map_or(Ok(()), |payment_method_data| {
req.payment_method.map_or(Ok(()), |req_payment_method| {
validate_payment_method_and_payment_method_data(
payment_method_data,
req_payment_method,
)
})
})
},
)?;
Ok(())
}
pub fn check_force_psync_precondition(status: storage_enums::AttemptStatus) -> bool {
!matches!(
status,
storage_enums::AttemptStatus::Charged
| storage_enums::AttemptStatus::AutoRefunded
| storage_enums::AttemptStatus::Voided
| storage_enums::AttemptStatus::CodInitiated
| storage_enums::AttemptStatus::Started
| storage_enums::AttemptStatus::Failure
)
}
pub fn append_option<T, U, F, V>(func: F, option1: Option<T>, option2: Option<U>) -> Option<V>
where
F: FnOnce(T, U) -> V,
{
Some(func(option1?, option2?))
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub(super) async fn filter_by_constraints(
state: &SessionState,
constraints: &PaymentIntentFetchConstraints,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, errors::StorageError> {
let db = &*state.store;
let result = db
.filter_payment_intent_by_constraints(
&(state).into(),
merchant_id,
constraints,
key_store,
storage_scheme,
)
.await?;
Ok(result)
}
#[cfg(feature = "olap")]
pub(super) fn validate_payment_list_request(
req: &api::PaymentListConstraints,
) -> CustomResult<(), errors::ApiErrorResponse> {
use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V1;
utils::when(
req.limit > PAYMENTS_LIST_MAX_LIMIT_V1 || req.limit < 1,
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("limit should be in between 1 and {PAYMENTS_LIST_MAX_LIMIT_V1}"),
})
},
)?;
Ok(())
}
#[cfg(feature = "olap")]
pub(super) fn validate_payment_list_request_for_joins(
limit: u32,
) -> CustomResult<(), errors::ApiErrorResponse> {
use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2;
utils::when(!(1..=PAYMENTS_LIST_MAX_LIMIT_V2).contains(&limit), || {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("limit should be in between 1 and {PAYMENTS_LIST_MAX_LIMIT_V2}"),
})
})?;
Ok(())
}
#[cfg(feature = "v1")]
pub fn get_handle_response_url(
payment_id: id_type::PaymentId,
business_profile: &domain::Profile,
response: &api::PaymentsResponse,
connector: String,
) -> RouterResult<api::RedirectionResponse> {
let payments_return_url = response.return_url.as_ref();
let redirection_response = make_pg_redirect_response(payment_id, response, connector);
let return_url = make_merchant_url_with_response(
business_profile,
redirection_response,
payments_return_url,
response.client_secret.as_ref(),
response.manual_retry_allowed,
)
.attach_printable("Failed to make merchant url with response")?;
make_url_with_signature(&return_url, business_profile)
}
#[cfg(feature = "v1")]
pub fn get_handle_response_url_for_modular_authentication(
authentication_id: id_type::AuthenticationId,
business_profile: &domain::Profile,
response: &api_models::authentication::AuthenticationAuthenticateResponse,
connector: String,
return_url: Option<String>,
client_secret: Option<&masking::Secret<String>>,
amount: Option<MinorUnit>,
) -> RouterResult<api::RedirectionResponse> {
let authentication_return_url = return_url;
let trans_status = response
.transaction_status
.clone()
.get_required_value("transaction_status")?;
let redirection_response = make_pg_redirect_response_for_authentication(
authentication_id,
connector,
amount,
trans_status,
);
let return_url = make_merchant_url_with_response_for_authentication(
business_profile,
redirection_response,
authentication_return_url.as_ref(),
client_secret,
None,
)
.attach_printable("Failed to make merchant url with response")?;
make_url_with_signature(&return_url, business_profile)
}
#[cfg(feature = "v1")]
pub fn make_merchant_url_with_response_for_authentication(
business_profile: &domain::Profile,
redirection_response: hyperswitch_domain_models::authentication::PgRedirectResponseForAuthentication,
request_return_url: Option<&String>,
client_secret: Option<&masking::Secret<String>>,
manual_retry_allowed: Option<bool>,
) -> RouterResult<String> {
// take return url if provided in the request else use merchant return url
let url = request_return_url
.or(business_profile.return_url.as_ref())
.get_required_value("return_url")?;
let status_check = redirection_response.status;
let authentication_client_secret = client_secret
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Expected client secret to be `Some`")?;
let authentication_id = redirection_response
.authentication_id
.get_string_repr()
.to_owned();
let merchant_url_with_response = if business_profile.redirect_to_merchant_with_http_post {
url::Url::parse_with_params(
url,
&[
("status", status_check.to_string()),
("authentication_id", authentication_id),
(
"authentication_client_secret",
authentication_client_secret.peek().to_string(),
),
(
"manual_retry_allowed",
manual_retry_allowed.unwrap_or(false).to_string(),
),
],
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse the url with param")?
} else {
let amount = redirection_response.amount.get_required_value("amount")?;
url::Url::parse_with_params(
url,
&[
("status", status_check.to_string()),
("authentication_id", authentication_id),
(
"authentication_client_secret",
authentication_client_secret.peek().to_string(),
),
("amount", amount.to_string()),
(
"manual_retry_allowed",
manual_retry_allowed.unwrap_or(false).to_string(),
),
],
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse the url with param")?
};
Ok(merchant_url_with_response.to_string())
}
#[cfg(feature = "v1")]
pub fn make_merchant_url_with_response(
business_profile: &domain::Profile,
redirection_response: api::PgRedirectResponse,
request_return_url: Option<&String>,
client_secret: Option<&masking::Secret<String>>,
manual_retry_allowed: Option<bool>,
) -> RouterResult<String> {
// take return url if provided in the request else use merchant return url
let url = request_return_url
.or(business_profile.return_url.as_ref())
.get_required_value("return_url")?;
let status_check = redirection_response.status;
let payment_client_secret = client_secret
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Expected client secret to be `Some`")?;
let payment_id = redirection_response.payment_id.get_string_repr().to_owned();
let merchant_url_with_response = if business_profile.redirect_to_merchant_with_http_post {
url::Url::parse_with_params(
url,
&[
("status", status_check.to_string()),
("payment_id", payment_id),
(
"payment_intent_client_secret",
payment_client_secret.peek().to_string(),
),
(
"manual_retry_allowed",
manual_retry_allowed.unwrap_or(false).to_string(),
),
],
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse the url with param")?
} else {
let amount = redirection_response.amount.get_required_value("amount")?;
url::Url::parse_with_params(
url,
&[
("status", status_check.to_string()),
("payment_id", payment_id),
(
"payment_intent_client_secret",
payment_client_secret.peek().to_string(),
),
("amount", amount.to_string()),
(
"manual_retry_allowed",
manual_retry_allowed.unwrap_or(false).to_string(),
),
],
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse the url with param")?
};
Ok(merchant_url_with_response.to_string())
}
#[cfg(feature = "v1")]
pub async fn make_ephemeral_key(
state: SessionState,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
) -> errors::RouterResponse<ephemeral_key::EphemeralKey> {
let store = &state.store;
let id = utils::generate_id(consts::ID_LENGTH, "eki");
let secret = format!("epk_{}", &Uuid::new_v4().simple().to_string());
let ek = ephemeral_key::EphemeralKeyNew {
id,
customer_id,
merchant_id: merchant_id.to_owned(),
secret,
};
let ek = store
.create_ephemeral_key(ek, state.conf.eph_key.validity)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create ephemeral key")?;
Ok(services::ApplicationResponse::Json(ek))
}
#[cfg(feature = "v2")]
pub async fn make_client_secret(
state: SessionState,
resource_id: api_models::ephemeral_key::ResourceId,
merchant_context: domain::MerchantContext,
headers: &actix_web::http::header::HeaderMap,
) -> errors::RouterResponse<ClientSecretResponse> {
let db = &state.store;
let key_manager_state = &((&state).into());
match &resource_id {
api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => {
db.find_customer_by_global_id(
key_manager_state,
global_customer_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
}
}
let resource_id = match resource_id {
api_models::ephemeral_key::ResourceId::Customer(global_customer_id) => {
common_utils::types::authentication::ResourceId::Customer(global_customer_id)
}
};
let client_secret = create_client_secret(
&state,
merchant_context.get_merchant_account().get_id(),
resource_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create client secret")?;
let response = ClientSecretResponse::foreign_try_from(client_secret)
.attach_printable("Only customer is supported as resource_id in response")?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn create_client_secret(
state: &SessionState,
merchant_id: &id_type::MerchantId,
resource_id: common_utils::types::authentication::ResourceId,
) -> RouterResult<ephemeral_key::ClientSecretType> {
use common_utils::generate_time_ordered_id;
let store = &state.store;
let id = id_type::ClientSecretId::generate();
let secret = masking::Secret::new(generate_time_ordered_id("cs"));
let client_secret = ephemeral_key::ClientSecretTypeNew {
id,
merchant_id: merchant_id.to_owned(),
secret,
resource_id,
};
let client_secret = store
.create_client_secret(client_secret, state.conf.eph_key.validity)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create client secret")?;
Ok(client_secret)
}
#[cfg(feature = "v1")]
pub async fn delete_ephemeral_key(
state: SessionState,
ek_id: String,
) -> errors::RouterResponse<ephemeral_key::EphemeralKey> {
let db = state.store.as_ref();
let ek = db
.delete_ephemeral_key(&ek_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to delete ephemeral key")?;
Ok(services::ApplicationResponse::Json(ek))
}
#[cfg(feature = "v2")]
pub async fn delete_client_secret(
state: SessionState,
ephemeral_key_id: String,
) -> errors::RouterResponse<ClientSecretResponse> {
let db = state.store.as_ref();
let ephemeral_key = db
.delete_client_secret(&ephemeral_key_id)
.await
.map_err(|err| match err.current_context() {
errors::StorageError::ValueNotFound(_) => {
err.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Ephemeral Key not found".to_string(),
})
}
_ => err.change_context(errors::ApiErrorResponse::InternalServerError),
})
.attach_printable("Unable to delete ephemeral key")?;
let response = ClientSecretResponse::foreign_try_from(ephemeral_key)
.attach_printable("Only customer is supported as resource_id in response")?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v1")]
pub fn make_pg_redirect_response(
payment_id: id_type::PaymentId,
response: &api::PaymentsResponse,
connector: String,
) -> api::PgRedirectResponse {
api::PgRedirectResponse {
payment_id,
status: response.status,
gateway_id: connector,
customer_id: response.customer_id.to_owned(),
amount: Some(response.amount),
}
}
#[cfg(feature = "v1")]
pub fn make_pg_redirect_response_for_authentication(
authentication_id: id_type::AuthenticationId,
connector: String,
amount: Option<MinorUnit>,
trans_status: common_enums::TransactionStatus,
) -> hyperswitch_domain_models::authentication::PgRedirectResponseForAuthentication {
hyperswitch_domain_models::authentication::PgRedirectResponseForAuthentication {
authentication_id,
status: trans_status,
gateway_id: connector,
customer_id: None,
amount,
}
}
#[cfg(feature = "v1")]
pub fn make_url_with_signature(
redirect_url: &str,
business_profile: &domain::Profile,
) -> RouterResult<api::RedirectionResponse> {
let mut url = url::Url::parse(redirect_url)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse the url")?;
let mut base_url = url.clone();
base_url.query_pairs_mut().clear();
let url = if business_profile.enable_payment_response_hash {
let key = business_profile
.payment_response_hash_key
.as_ref()
.get_required_value("payment_response_hash_key")?;
let signature = hmac_sha512_sorted_query_params(
&mut url.query_pairs().collect::<Vec<_>>(),
key.as_str(),
)?;
url.query_pairs_mut()
.append_pair("signature", &signature)
.append_pair("signature_algorithm", "HMAC-SHA512");
url.to_owned()
} else {
url.to_owned()
};
let parameters = url
.query_pairs()
.collect::<Vec<_>>()
.iter()
.map(|(key, value)| (key.clone().into_owned(), value.clone().into_owned()))
.collect::<Vec<_>>();
Ok(api::RedirectionResponse {
return_url: base_url.to_string(),
params: parameters,
return_url_with_query_params: url.to_string(),
http_method: if business_profile.redirect_to_merchant_with_http_post {
services::Method::Post.to_string()
} else {
services::Method::Get.to_string()
},
headers: Vec::new(),
})
}
pub fn hmac_sha512_sorted_query_params(
params: &mut [(Cow<'_, str>, Cow<'_, str>)],
key: &str,
) -> RouterResult<String> {
params.sort();
let final_string = params
.iter()
.map(|(key, value)| format!("{key}={value}"))
.collect::<Vec<_>>()
.join("&");
let signature = crypto::HmacSha512::sign_message(
&crypto::HmacSha512,
key.as_bytes(),
final_string.as_bytes(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to sign the message")?;
Ok(hex::encode(signature))
}
pub fn check_if_operation_confirm<Op: std::fmt::Debug>(operations: Op) -> bool {
format!("{operations:?}") == "PaymentConfirm"
}
#[allow(clippy::too_many_arguments)]
pub fn generate_mandate(
merchant_id: id_type::MerchantId,
payment_id: id_type::PaymentId,
connector: String,
setup_mandate_details: Option<MandateData>,
customer_id: &Option<id_type::CustomerId>,
payment_method_id: String,
connector_mandate_id: Option<pii::SecretSerdeValue>,
network_txn_id: Option<String>,
payment_method_data_option: Option<domain::payments::PaymentMethodData>,
mandate_reference: Option<MandateReference>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
) -> CustomResult<Option<storage::MandateNew>, errors::ApiErrorResponse> {
match (setup_mandate_details, customer_id) {
(Some(data), Some(cus_id)) => {
let mandate_id = utils::generate_id(consts::ID_LENGTH, "man");
// The construction of the mandate new must be visible
let mut new_mandate = storage::MandateNew::default();
let customer_acceptance = data
.customer_acceptance
.get_required_value("customer_acceptance")?;
new_mandate
.set_mandate_id(mandate_id)
.set_customer_id(cus_id.clone())
.set_merchant_id(merchant_id)
.set_original_payment_id(Some(payment_id))
.set_payment_method_id(payment_method_id)
.set_connector(connector)
.set_mandate_status(storage_enums::MandateStatus::Active)
.set_connector_mandate_ids(connector_mandate_id)
.set_network_transaction_id(network_txn_id)
.set_customer_ip_address(
customer_acceptance
.get_ip_address()
.map(masking::Secret::new),
)
.set_customer_user_agent_extended(customer_acceptance.get_user_agent())
.set_customer_accepted_at(Some(customer_acceptance.get_accepted_at()))
.set_metadata(payment_method_data_option.map(|payment_method_data| {
pii::SecretSerdeValue::new(
serde_json::to_value(payment_method_data).unwrap_or_default(),
)
}))
.set_connector_mandate_id(
mandate_reference.and_then(|reference| reference.connector_mandate_id),
)
.set_merchant_connector_id(merchant_connector_id);
Ok(Some(
match data.mandate_type.get_required_value("mandate_type")? {
hyperswitch_domain_models::mandates::MandateDataType::SingleUse(data) => {
new_mandate
.set_mandate_amount(Some(data.amount.get_amount_as_i64()))
.set_mandate_currency(Some(data.currency))
.set_mandate_type(storage_enums::MandateType::SingleUse)
.to_owned()
}
hyperswitch_domain_models::mandates::MandateDataType::MultiUse(op_data) => {
match op_data {
Some(data) => new_mandate
.set_mandate_amount(Some(data.amount.get_amount_as_i64()))
.set_mandate_currency(Some(data.currency))
.set_start_date(data.start_date)
.set_end_date(data.end_date),
// .set_metadata(data.metadata),
// we are storing PaymentMethodData in metadata of mandate
None => &mut new_mandate,
}
.set_mandate_type(storage_enums::MandateType::MultiUse)
.to_owned()
}
},
))
}
(_, _) => Ok(None),
}
}
#[cfg(feature = "v1")]
// A function to manually authenticate the client secret with intent fulfillment time
pub fn authenticate_client_secret(
request_client_secret: Option<&String>,
payment_intent: &PaymentIntent,
) -> Result<(), errors::ApiErrorResponse> {
match (request_client_secret, &payment_intent.client_secret) {
(Some(req_cs), Some(pi_cs)) => {
if req_cs != pi_cs {
Err(errors::ApiErrorResponse::ClientSecretInvalid)
} else {
let current_timestamp = common_utils::date_time::now();
let session_expiry = payment_intent.session_expiry.unwrap_or(
payment_intent
.created_at
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
);
fp_utils::when(current_timestamp > session_expiry, || {
Err(errors::ApiErrorResponse::ClientSecretExpired)
})
}
}
// If there is no client in payment intent, then it has expired
(Some(_), None) => Err(errors::ApiErrorResponse::ClientSecretExpired),
_ => Ok(()),
}
}
pub(crate) fn validate_payment_status_against_allowed_statuses(
intent_status: storage_enums::IntentStatus,
allowed_statuses: &[storage_enums::IntentStatus],
action: &'static str,
) -> Result<(), errors::ApiErrorResponse> {
fp_utils::when(!allowed_statuses.contains(&intent_status), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"You cannot {action} this payment because it has status {intent_status}",
),
})
})
}
pub(crate) fn validate_payment_status_against_not_allowed_statuses(
intent_status: storage_enums::IntentStatus,
not_allowed_statuses: &[storage_enums::IntentStatus],
action: &'static str,
) -> Result<(), errors::ApiErrorResponse> {
fp_utils::when(not_allowed_statuses.contains(&intent_status), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"You cannot {action} this payment because it has status {intent_status}",
),
})
})
}
#[instrument(skip_all)]
pub(crate) fn validate_pm_or_token_given(
payment_method: &Option<api_enums::PaymentMethod>,
payment_method_data: &Option<api::PaymentMethodData>,
payment_method_type: &Option<api_enums::PaymentMethodType>,
mandate_type: &Option<api::MandateTransactionType>,
token: &Option<String>,
ctp_service_details: &Option<api_models::payments::CtpServiceDetails>,
) -> Result<(), errors::ApiErrorResponse> {
utils::when(
!matches!(
payment_method_type,
Some(api_enums::PaymentMethodType::Paypal)
) && !matches!(
mandate_type,
Some(api::MandateTransactionType::RecurringMandateTransaction)
) && token.is_none()
&& (payment_method_data.is_none() || payment_method.is_none())
&& ctp_service_details.is_none(),
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message:
"A payment token or payment method data or ctp service details is required"
.to_string(),
})
},
)
}
#[cfg(feature = "v2")]
// A function to perform database lookup and then verify the client secret
pub async fn verify_payment_intent_time_and_client_secret(
state: &SessionState,
merchant_context: &domain::MerchantContext,
client_secret: Option<String>,
) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> {
todo!()
}
#[cfg(feature = "v1")]
// A function to perform database lookup and then verify the client secret
pub async fn verify_payment_intent_time_and_client_secret(
state: &SessionState,
merchant_context: &domain::MerchantContext,
client_secret: Option<String>,
) -> error_stack::Result<Option<PaymentIntent>, errors::ApiErrorResponse> {
let db = &*state.store;
client_secret
.async_map(|cs| async move {
let payment_id = get_payment_id_from_client_secret(&cs)?;
let payment_id = id_type::PaymentId::wrap(payment_id).change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_id",
},
)?;
#[cfg(feature = "v1")]
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
let payment_intent = db
.find_payment_intent_by_id(
&state.into(),
&payment_id,
key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
authenticate_client_secret(Some(&cs), &payment_intent)?;
Ok(payment_intent)
})
.await
.transpose()
}
#[cfg(feature = "v1")]
/// Check whether the business details are configured in the merchant account
pub fn validate_business_details(
business_country: Option<api_enums::CountryAlpha2>,
business_label: Option<&String>,
merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
let primary_business_details = merchant_context
.get_merchant_account()
.primary_business_details
.clone()
.parse_value::<Vec<api_models::admin::PrimaryBusinessDetails>>("PrimaryBusinessDetails")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to parse primary business details")?;
business_country
.zip(business_label)
.map(|(business_country, business_label)| {
primary_business_details
.iter()
.find(|business_details| {
&business_details.business == business_label
&& business_details.country == business_country
})
.ok_or(errors::ApiErrorResponse::PreconditionFailed {
message: "business_details are not configured in the merchant account"
.to_string(),
})
})
.transpose()?;
Ok(())
}
#[inline]
pub(crate) fn get_payment_id_from_client_secret(cs: &str) -> RouterResult<String> {
let (payment_id, _) = cs
.rsplit_once("_secret_")
.ok_or(errors::ApiErrorResponse::ClientSecretInvalid)?;
Ok(payment_id.to_string())
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn test_authenticate_client_secret_session_not_expired() {
let payment_intent = PaymentIntent {
payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
merchant_id: id_type::MerchantId::default(),
status: storage_enums::IntentStatus::RequiresCapture,
amount: MinorUnit::new(200),
currency: None,
amount_captured: None,
customer_id: None,
description: None,
return_url: None,
metadata: None,
connector_id: None,
shipping_address_id: None,
billing_address_id: None,
mit_category: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
last_synced: None,
setup_future_usage: None,
fingerprint_id: None,
off_session: None,
client_secret: Some("1".to_string()),
active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
"nopes".to_string(),
),
business_country: None,
business_label: None,
order_details: None,
allowed_payment_method_types: None,
connector_metadata: None,
feature_metadata: None,
attempt_count: 1,
payment_link_id: None,
profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_decision: None,
payment_confirm_source: None,
surcharge_applicable: None,
updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(),
request_incremental_authorization: Some(
common_enums::RequestIncrementalAuthorization::default(),
),
incremental_authorization_allowed: None,
authorization_count: None,
session_expiry: Some(
common_utils::date_time::now()
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
),
request_external_three_ds_authentication: None,
split_payments: None,
frm_metadata: None,
customer_details: None,
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
is_payment_processor_token_flow: None,
organization_id: id_type::OrganizationId::default(),
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
request_extended_authorization: None,
psd2_sca_exemption_type: None,
processor_merchant_id: id_type::MerchantId::default(),
created_by: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
is_iframe_redirection_enabled: None,
is_payment_id_from_merchant: None,
payment_channel: None,
tax_status: None,
discount_amount: None,
order_date: None,
shipping_amount_tax: None,
duty_amount: None,
enable_partial_authorization: None,
enable_overcapture: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
// Check if the result is an Ok variant
}
#[test]
fn test_authenticate_client_secret_session_expired() {
let created_at =
common_utils::date_time::now().saturating_sub(time::Duration::seconds(20 * 60));
let payment_intent = PaymentIntent {
payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
merchant_id: id_type::MerchantId::default(),
status: storage_enums::IntentStatus::RequiresCapture,
amount: MinorUnit::new(200),
currency: None,
amount_captured: None,
customer_id: None,
description: None,
return_url: None,
metadata: None,
connector_id: None,
shipping_address_id: None,
mit_category: None,
billing_address_id: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
created_at,
modified_at: common_utils::date_time::now(),
fingerprint_id: None,
last_synced: None,
setup_future_usage: None,
off_session: None,
client_secret: Some("1".to_string()),
active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
"nopes".to_string(),
),
business_country: None,
business_label: None,
order_details: None,
allowed_payment_method_types: None,
connector_metadata: None,
feature_metadata: None,
attempt_count: 1,
payment_link_id: None,
profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_decision: None,
payment_confirm_source: None,
surcharge_applicable: None,
updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(),
request_incremental_authorization: Some(
common_enums::RequestIncrementalAuthorization::default(),
),
incremental_authorization_allowed: None,
authorization_count: None,
session_expiry: Some(
created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
),
request_external_three_ds_authentication: None,
split_payments: None,
frm_metadata: None,
customer_details: None,
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
is_payment_processor_token_flow: None,
organization_id: id_type::OrganizationId::default(),
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
request_extended_authorization: None,
psd2_sca_exemption_type: None,
processor_merchant_id: id_type::MerchantId::default(),
created_by: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
is_iframe_redirection_enabled: None,
is_payment_id_from_merchant: None,
payment_channel: None,
tax_status: None,
discount_amount: None,
order_date: None,
shipping_amount_tax: None,
duty_amount: None,
enable_partial_authorization: None,
enable_overcapture: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
}
#[test]
fn test_authenticate_client_secret_expired() {
let payment_intent = PaymentIntent {
payment_id: id_type::PaymentId::try_from(Cow::Borrowed("23")).unwrap(),
merchant_id: id_type::MerchantId::default(),
status: storage_enums::IntentStatus::RequiresCapture,
amount: MinorUnit::new(200),
currency: None,
amount_captured: None,
customer_id: None,
description: None,
return_url: None,
metadata: None,
connector_id: None,
mit_category: None,
shipping_address_id: None,
billing_address_id: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)),
modified_at: common_utils::date_time::now(),
last_synced: None,
setup_future_usage: None,
off_session: None,
client_secret: None,
fingerprint_id: None,
active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
"nopes".to_string(),
),
business_country: None,
business_label: None,
order_details: None,
allowed_payment_method_types: None,
connector_metadata: None,
feature_metadata: None,
attempt_count: 1,
payment_link_id: None,
profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_decision: None,
payment_confirm_source: None,
surcharge_applicable: None,
updated_by: storage_enums::MerchantStorageScheme::PostgresOnly.to_string(),
request_incremental_authorization: Some(
common_enums::RequestIncrementalAuthorization::default(),
),
incremental_authorization_allowed: None,
authorization_count: None,
session_expiry: Some(
common_utils::date_time::now()
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
),
request_external_three_ds_authentication: None,
split_payments: None,
frm_metadata: None,
customer_details: None,
billing_details: None,
merchant_order_reference_id: None,
shipping_details: None,
is_payment_processor_token_flow: None,
organization_id: id_type::OrganizationId::default(),
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
request_extended_authorization: None,
psd2_sca_exemption_type: None,
processor_merchant_id: id_type::MerchantId::default(),
created_by: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
is_iframe_redirection_enabled: None,
is_payment_id_from_merchant: None,
payment_channel: None,
tax_status: None,
discount_amount: None,
order_date: None,
shipping_amount_tax: None,
duty_amount: None,
enable_partial_authorization: None,
enable_overcapture: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
}
}
// This function will be removed after moving this functionality to server_wrap and using cache instead of config
#[instrument(skip_all)]
pub async fn insert_merchant_connector_creds_to_config(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
merchant_connector_details: admin::MerchantConnectorDetailsWrap,
) -> RouterResult<()> {
if let Some(encoded_data) = merchant_connector_details.encoded_data {
let redis = &db
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key =
merchant_id.get_creds_identifier_key(&merchant_connector_details.creds_identifier);
redis
.serialize_and_set_key_with_expiry(
&key.as_str().into(),
&encoded_data.peek(),
consts::CONNECTOR_CREDS_TOKEN_TTL,
)
.await
.map_or_else(
|e| {
Err(e
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert connector_creds to config"))
},
|_| Ok(()),
)
} else {
Ok(())
}
}
/// Query for merchant connector account either by business label or profile id
/// If profile_id is passed use it, or use connector_label to query merchant connector account
#[instrument(skip_all)]
pub async fn get_merchant_connector_account(
state: &SessionState,
merchant_id: &id_type::MerchantId,
creds_identifier: Option<&str>,
key_store: &domain::MerchantKeyStore,
profile_id: &id_type::ProfileId,
connector_name: &str,
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
) -> RouterResult<MerchantConnectorAccountType> {
let db = &*state.store;
let key_manager_state: &KeyManagerState = &state.into();
match creds_identifier {
Some(creds_identifier) => {
let key = merchant_id.get_creds_identifier_key(creds_identifier);
let cloned_key = key.clone();
let redis_fetch = || async {
db.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
.async_and_then(|redis| async move {
redis
.get_and_deserialize_key(&key.as_str().into(), "String")
.await
.change_context(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: key.clone(),
},
)
.attach_printable(key.clone() + ": Not found in Redis")
})
.await
};
let db_fetch = || async {
db.find_config_by_key(cloned_key.as_str())
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: cloned_key.to_owned(),
},
)
};
let mca_config: String = redis_fetch()
.await
.map_or_else(
|_| {
Either::Left(async {
match db_fetch().await {
Ok(config_entry) => Ok(config_entry.config),
Err(e) => Err(e),
}
})
},
|result| Either::Right(async { Ok(result) }),
)
.await?;
let private_key = state
.conf
.jwekey
.get_inner()
.tunnel_private_key
.peek()
.as_bytes();
let decrypted_mca = services::decrypt_jwe(mca_config.as_str(), services::KeyIdCheck::SkipKeyIdCheck, private_key, jwe::RSA_OAEP_256)
.await
.change_context(errors::ApiErrorResponse::UnprocessableEntity{
message: "decoding merchant_connector_details failed due to invalid data format!".into()})
.attach_printable(
"Failed to decrypt merchant_connector_details sent in request and then put in cache",
)?;
let res = String::into_bytes(decrypted_mca)
.parse_struct("MerchantConnectorDetails")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to parse merchant_connector_details sent in request and then put in cache",
)?;
Ok(MerchantConnectorAccountType::CacheVal(res))
}
None => {
let mca: RouterResult<domain::MerchantConnectorAccount> =
if let Some(merchant_connector_id) = merchant_connector_id {
#[cfg(feature = "v1")]
{
db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)
}
#[cfg(feature = "v2")]
{
db.find_merchant_connector_account_by_id(
&state.into(),
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)
}
} else {
#[cfg(feature = "v1")]
{
db.find_merchant_connector_account_by_profile_id_connector_name(
key_manager_state,
profile_id,
connector_name,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: format!(
"profile id {} and connector name {connector_name}",
profile_id.get_string_repr()
),
},
)
}
#[cfg(feature = "v2")]
{
todo!()
}
};
mca.map(Box::new).map(MerchantConnectorAccountType::DbVal)
}
}
}
/// This function replaces the request and response type of routerdata with the
/// request and response type passed
/// # Arguments
///
/// * `router_data` - original router data
/// * `request` - new request core/helper
/// * `response` - new response
pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
router_data: RouterData<F1, Req1, Res1>,
request: Req2,
response: Result<Res2, ErrorResponse>,
) -> RouterData<F2, Req2, Res2> {
RouterData {
flow: std::marker::PhantomData,
request,
response,
merchant_id: router_data.merchant_id,
tenant_id: router_data.tenant_id,
address: router_data.address,
amount_captured: router_data.amount_captured,
minor_amount_captured: router_data.minor_amount_captured,
auth_type: router_data.auth_type,
connector: router_data.connector,
connector_auth_type: router_data.connector_auth_type,
connector_meta_data: router_data.connector_meta_data,
description: router_data.description,
payment_id: router_data.payment_id,
payment_method: router_data.payment_method,
payment_method_type: router_data.payment_method_type,
status: router_data.status,
attempt_id: router_data.attempt_id,
access_token: router_data.access_token,
session_token: router_data.session_token,
payment_method_status: router_data.payment_method_status,
reference_id: router_data.reference_id,
payment_method_token: router_data.payment_method_token,
customer_id: router_data.customer_id,
connector_customer: router_data.connector_customer,
preprocessing_id: router_data.preprocessing_id,
payment_method_balance: router_data.payment_method_balance,
recurring_mandate_payment_data: router_data.recurring_mandate_payment_data,
connector_request_reference_id: router_data.connector_request_reference_id,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: router_data.test_mode,
connector_api_version: router_data.connector_api_version,
connector_http_status_code: router_data.connector_http_status_code,
external_latency: router_data.external_latency,
apple_pay_flow: router_data.apple_pay_flow,
frm_metadata: router_data.frm_metadata,
refund_id: router_data.refund_id,
dispute_id: router_data.dispute_id,
connector_response: router_data.connector_response,
integrity_check: Ok(()),
connector_wallets_details: router_data.connector_wallets_details,
additional_merchant_data: router_data.additional_merchant_data,
header_payload: router_data.header_payload,
connector_mandate_request_reference_id: router_data.connector_mandate_request_reference_id,
authentication_id: router_data.authentication_id,
psd2_sca_exemption_type: router_data.psd2_sca_exemption_type,
raw_connector_response: router_data.raw_connector_response,
is_payment_id_from_merchant: router_data.is_payment_id_from_merchant,
l2_l3_data: router_data.l2_l3_data,
minor_amount_capturable: router_data.minor_amount_capturable,
authorized_amount: router_data.authorized_amount,
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub fn get_attempt_type(
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
is_manual_retry_enabled: Option<bool>,
action: &str,
) -> RouterResult<AttemptType> {
match payment_intent.status {
enums::IntentStatus::Failed => {
if matches!(is_manual_retry_enabled, Some(true)) {
// if it is false, don't go ahead with manual retry
fp_utils::when(
!validate_manual_retry_cutoff(
payment_intent.created_at,
payment_intent.session_expiry,
),
|| {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message:
format!("You cannot {action} this payment using `manual_retry` because the allowed duration has expired")
}
))
},
)?;
metrics::MANUAL_RETRY_REQUEST_COUNT.add(
1,
router_env::metric_attributes!((
"merchant_id",
payment_attempt.merchant_id.clone(),
)),
);
match payment_attempt.status {
enums::AttemptStatus::Started
| enums::AttemptStatus::AuthenticationPending
| enums::AttemptStatus::AuthenticationSuccessful
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::Charged
| enums::AttemptStatus::Authorizing
| enums::AttemptStatus::CodInitiated
| enums::AttemptStatus::VoidInitiated
| enums::AttemptStatus::CaptureInitiated
| enums::AttemptStatus::Unresolved
| enums::AttemptStatus::Pending
| enums::AttemptStatus::ConfirmationAwaited
| enums::AttemptStatus::PartialCharged
| enums::AttemptStatus::PartialChargedAndChargeable
| enums::AttemptStatus::Voided
| enums::AttemptStatus::VoidedPostCharge
| enums::AttemptStatus::AutoRefunded
| enums::AttemptStatus::PaymentMethodAwaited
| enums::AttemptStatus::DeviceDataCollectionPending
| enums::AttemptStatus::IntegrityFailure
| enums::AttemptStatus::Expired
| enums::AttemptStatus::PartiallyAuthorized => {
metrics::MANUAL_RETRY_VALIDATION_FAILED.add(
1,
router_env::metric_attributes!((
"merchant_id",
payment_attempt.merchant_id.clone(),
)),
);
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment Attempt unexpected state")
}
storage_enums::AttemptStatus::VoidFailed
| storage_enums::AttemptStatus::RouterDeclined
| storage_enums::AttemptStatus::CaptureFailed => {
metrics::MANUAL_RETRY_VALIDATION_FAILED.add(
1,
router_env::metric_attributes!((
"merchant_id",
payment_attempt.merchant_id.clone(),
)),
);
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message:
format!("You cannot {action} this payment because it has status {}, and the previous attempt has the status {}", payment_intent.status, payment_attempt.status)
}
))
}
storage_enums::AttemptStatus::AuthenticationFailed
| storage_enums::AttemptStatus::AuthorizationFailed
| storage_enums::AttemptStatus::Failure => {
metrics::MANUAL_RETRY_COUNT.add(
1,
router_env::metric_attributes!((
"merchant_id",
payment_attempt.merchant_id.clone(),
)),
);
Ok(AttemptType::New)
}
}
} else {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message:
format!("You cannot {action} this payment because it has status {}, you can enable `manual_retry` in profile to try this payment again", payment_intent.status)
}
))
}
}
enums::IntentStatus::Cancelled
| enums::IntentStatus::CancelledPostCapture
| enums::IntentStatus::RequiresCapture
| enums::IntentStatus::PartiallyCaptured
| enums::IntentStatus::PartiallyCapturedAndCapturable
| enums::IntentStatus::Processing
| enums::IntentStatus::Succeeded
| enums::IntentStatus::Conflicted
| enums::IntentStatus::Expired
| enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"You cannot {action} this payment because it has status {}",
payment_intent.status,
),
}))
}
enums::IntentStatus::RequiresCustomerAction
| enums::IntentStatus::RequiresMerchantAction
| enums::IntentStatus::RequiresPaymentMethod
| enums::IntentStatus::RequiresConfirmation => Ok(AttemptType::SameOld),
}
}
fn validate_manual_retry_cutoff(
created_at: time::PrimitiveDateTime,
session_expiry: Option<time::PrimitiveDateTime>,
) -> bool {
let utc_current_time = time::OffsetDateTime::now_utc();
let primitive_utc_current_time =
time::PrimitiveDateTime::new(utc_current_time.date(), utc_current_time.time());
let time_difference_from_creation = primitive_utc_current_time - created_at;
// cutoff time is 50% of session duration
let cutoff_limit = match session_expiry {
Some(session_expiry) => {
let duration = session_expiry - created_at;
duration.whole_seconds() / 2
}
None => consts::DEFAULT_SESSION_EXPIRY / 2,
};
time_difference_from_creation.whole_seconds() <= cutoff_limit
}
#[derive(Debug, Eq, PartialEq, Clone)]
pub enum AttemptType {
New,
SameOld,
}
impl AttemptType {
#[cfg(feature = "v1")]
// The function creates a new payment_attempt from the previous payment attempt but doesn't populate fields like payment_method, error_code etc.
// Logic to override the fields with data provided in the request should be done after this if required.
// In case if fields are not overridden by the request then they contain the same data that was in the previous attempt provided it is populated in this function.
#[inline(always)]
fn make_new_payment_attempt(
payment_method_data: Option<&api_models::payments::PaymentMethodData>,
old_payment_attempt: PaymentAttempt,
new_attempt_count: i16,
storage_scheme: enums::MerchantStorageScheme,
) -> storage::PaymentAttemptNew {
let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
storage::PaymentAttemptNew {
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,
// A new payment attempt is getting created so, used the same function which is used to populate status in PaymentCreate Flow.
status: payment_attempt_status_fsm(payment_method_data, Some(true)),
currency: old_payment_attempt.currency,
save_to_locker: old_payment_attempt.save_to_locker,
connector: None,
error_message: None,
offer_amount: old_payment_attempt.offer_amount,
payment_method_id: None,
payment_method: None,
capture_method: old_payment_attempt.capture_method,
capture_on: old_payment_attempt.capture_on,
confirm: old_payment_attempt.confirm,
authentication_type: old_payment_attempt.authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason: None,
amount_to_capture: old_payment_attempt.amount_to_capture,
// Once the payment_attempt is authorised then mandate_id is created. If this payment attempt is authorised then mandate_id will be overridden.
// Since mandate_id is a contract between merchant and customer to debit customers amount adding it to newly created attempt
mandate_id: old_payment_attempt.mandate_id,
// The payment could be done from a different browser or same browser, it would probably be overridden by request data.
browser_info: None,
error_code: None,
payment_token: None,
connector_metadata: None,
payment_experience: None,
payment_method_type: None,
payment_method_data: None,
// In case it is passed in create and not in confirm,
business_sub_label: old_payment_attempt.business_sub_label,
// If the algorithm is entered in Create call from server side, it needs to be populated here, however it could be overridden from the request.
straight_through_algorithm: old_payment_attempt.straight_through_algorithm,
mandate_details: old_payment_attempt.mandate_details,
preprocessing_step_id: None,
error_reason: None,
multiple_capture_count: None,
connector_response_reference_id: None,
amount_capturable: old_payment_attempt.net_amount.get_total_amount(),
updated_by: storage_scheme.to_string(),
authentication_data: None,
encoded_data: None,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
net_amount: old_payment_attempt.net_amount,
external_three_ds_authentication_attempted: old_payment_attempt
.external_three_ds_authentication_attempted,
authentication_connector: None,
authentication_id: None,
mandate_data: old_payment_attempt.mandate_data,
// New payment method billing address can be passed for a retry
payment_method_billing_address_id: None,
fingerprint_id: None,
client_source: old_payment_attempt.client_source,
client_version: old_payment_attempt.client_version,
customer_acceptance: old_payment_attempt.customer_acceptance,
organization_id: old_payment_attempt.organization_id,
profile_id: old_payment_attempt.profile_id,
connector_mandate_detail: None,
request_extended_authorization: None,
extended_authorization_applied: None,
capture_before: None,
card_discovery: None,
processor_merchant_id: old_payment_attempt.processor_merchant_id,
created_by: old_payment_attempt.created_by,
setup_future_usage_applied: None,
routing_approach: old_payment_attempt.routing_approach,
connector_request_reference_id: None,
network_transaction_id: None,
network_details: None,
is_stored_credential: old_payment_attempt.is_stored_credential,
authorized_amount: old_payment_attempt.authorized_amount,
}
}
// #[cfg(feature = "v2")]
// // The function creates a new payment_attempt from the previous payment attempt but doesn't populate fields like payment_method, error_code etc.
// // Logic to override the fields with data provided in the request should be done after this if required.
// // In case if fields are not overridden by the request then they contain the same data that was in the previous attempt provided it is populated in this function.
// #[inline(always)]
// fn make_new_payment_attempt(
// _payment_method_data: Option<&api_models::payments::PaymentMethodData>,
// _old_payment_attempt: PaymentAttempt,
// _new_attempt_count: i16,
// _storage_scheme: enums::MerchantStorageScheme,
// ) -> PaymentAttempt {
// todo!()
// }
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn modify_payment_intent_and_payment_attempt(
&self,
request: &api_models::payments::PaymentsRequest,
fetched_payment_intent: PaymentIntent,
fetched_payment_attempt: PaymentAttempt,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<(PaymentIntent, PaymentAttempt)> {
match self {
Self::SameOld => Ok((fetched_payment_intent, fetched_payment_attempt)),
Self::New => {
let db = &*state.store;
let key_manager_state = &state.into();
let new_attempt_count = fetched_payment_intent.attempt_count + 1;
let new_payment_attempt_to_insert = Self::make_new_payment_attempt(
request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
}),
fetched_payment_attempt,
new_attempt_count,
storage_scheme,
);
#[cfg(feature = "v1")]
let new_payment_attempt = db
.insert_payment_attempt(new_payment_attempt_to_insert, storage_scheme)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: fetched_payment_intent.get_id().to_owned(),
})?;
#[cfg(feature = "v2")]
let new_payment_attempt = db
.insert_payment_attempt(
key_manager_state,
key_store,
new_payment_attempt_to_insert,
storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert payment attempt")?;
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
fetched_payment_intent,
storage::PaymentIntentUpdate::StatusAndAttemptUpdate {
status: payment_intent_status_fsm(
request.payment_method_data.as_ref().and_then(
|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
},
),
Some(true),
),
active_attempt_id: new_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)?;
logger::info!(
"manual_retry payment for {:?} with attempt_id {:?}",
updated_payment_intent.get_id(),
new_payment_attempt.get_id()
);
Ok((updated_payment_intent, new_payment_attempt))
}
}
}
}
#[inline(always)]
pub fn is_manual_retry_allowed(
intent_status: &storage_enums::IntentStatus,
attempt_status: &storage_enums::AttemptStatus,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
merchant_id: &id_type::MerchantId,
) -> Option<bool> {
let is_payment_status_eligible_for_retry = match intent_status {
enums::IntentStatus::Failed => match attempt_status {
enums::AttemptStatus::Started
| enums::AttemptStatus::AuthenticationPending
| enums::AttemptStatus::AuthenticationSuccessful
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::Charged
| enums::AttemptStatus::Authorizing
| enums::AttemptStatus::CodInitiated
| enums::AttemptStatus::VoidInitiated
| enums::AttemptStatus::CaptureInitiated
| enums::AttemptStatus::Unresolved
| enums::AttemptStatus::Pending
| enums::AttemptStatus::ConfirmationAwaited
| enums::AttemptStatus::PartialCharged
| enums::AttemptStatus::PartialChargedAndChargeable
| enums::AttemptStatus::Voided
| enums::AttemptStatus::VoidedPostCharge
| enums::AttemptStatus::AutoRefunded
| enums::AttemptStatus::PaymentMethodAwaited
| enums::AttemptStatus::DeviceDataCollectionPending
| enums::AttemptStatus::IntegrityFailure
| enums::AttemptStatus::Expired
| enums::AttemptStatus::PartiallyAuthorized => {
logger::error!("Payment Attempt should not be in this state because Attempt to Intent status mapping doesn't allow it");
None
}
enums::AttemptStatus::VoidFailed
| enums::AttemptStatus::RouterDeclined
| enums::AttemptStatus::CaptureFailed => Some(false),
enums::AttemptStatus::AuthenticationFailed
| enums::AttemptStatus::AuthorizationFailed
| enums::AttemptStatus::Failure => Some(true),
},
enums::IntentStatus::Cancelled
| enums::IntentStatus::CancelledPostCapture
| enums::IntentStatus::RequiresCapture
| enums::IntentStatus::PartiallyCaptured
| enums::IntentStatus::PartiallyCapturedAndCapturable
| enums::IntentStatus::Processing
| enums::IntentStatus::Succeeded
| enums::IntentStatus::Conflicted
| enums::IntentStatus::Expired
| enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => Some(false),
enums::IntentStatus::RequiresCustomerAction
| enums::IntentStatus::RequiresMerchantAction
| enums::IntentStatus::RequiresPaymentMethod
| enums::IntentStatus::RequiresConfirmation => None,
};
let is_merchant_id_enabled_for_retries = !connector_request_reference_id_config
.merchant_ids_send_payment_id_as_connector_request_id
.contains(merchant_id);
is_payment_status_eligible_for_retry
.map(|payment_status_check| payment_status_check && is_merchant_id_enabled_for_retries)
}
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used)]
#[test]
fn test_client_secret_parse() {
let client_secret1 = "pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr";
let client_secret2 = "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr";
let client_secret3 =
"pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr";
assert_eq!(
"pay_3TgelAms4RQec8xSStjF",
super::get_payment_id_from_client_secret(client_secret1).unwrap()
);
assert_eq!(
"pay_3Tgel__Ams4RQ_secret_ec8xSStjF",
super::get_payment_id_from_client_secret(client_secret2).unwrap()
);
assert_eq!(
"pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_",
super::get_payment_id_from_client_secret(client_secret3).unwrap()
);
}
}
#[instrument(skip_all)]
pub async fn get_additional_payment_data(
pm_data: &domain::PaymentMethodData,
db: &dyn StorageInterface,
profile_id: &id_type::ProfileId,
) -> Result<
Option<api_models::payments::AdditionalPaymentData>,
error_stack::Report<errors::ApiErrorResponse>,
> {
match pm_data {
domain::PaymentMethodData::Card(card_data) => {
//todo!
let card_isin = Some(card_data.card_number.get_card_isin());
let enable_extended_bin =db
.find_config_by_key_unwrap_or(
format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(),
Some("false".to_string()))
.await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok();
let card_extended_bin = match enable_extended_bin {
Some(config) if config.config == "true" => {
Some(card_data.card_number.get_extended_card_bin())
}
_ => None,
};
// Added an additional check for card_data.co_badged_card_data.is_some()
// because is_cobadged_card() only returns true if the card number matches a specific regex.
// However, this regex does not cover all possible co-badged networks.
// The co_badged_card_data field is populated based on a co-badged BIN lookup
// and helps identify co-badged cards that may not match the regex alone.
// Determine the card network based on cobadge detection and co-badged BIN data
let is_cobadged_based_on_regex = card_data
.card_number
.is_cobadged_card()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Card cobadge check failed due to an invalid card network regex",
)?;
let (card_network, signature_network, is_regulated) = card_data
.co_badged_card_data
.as_ref()
.map(|co_badged_data| {
logger::debug!("Co-badged card data found");
(
card_data.card_network.clone(),
co_badged_data
.co_badged_card_networks_info
.get_signature_network(),
Some(co_badged_data.is_regulated),
)
})
.or_else(|| {
is_cobadged_based_on_regex.then(|| {
logger::debug!("Card network is cobadged (regex-based detection)");
(card_data.card_network.clone(), None, None)
})
})
.unwrap_or_else(|| {
logger::debug!("Card network is not cobadged");
(None, None, None)
});
let last4 = Some(card_data.card_number.get_last4());
if card_data.card_issuer.is_some()
&& card_network.is_some()
&& card_data.card_type.is_some()
&& card_data.card_issuing_country.is_some()
&& card_data.bank_code.is_some()
{
Ok(Some(api_models::payments::AdditionalPaymentData::Card(
Box::new(api_models::payments::AdditionalCardInfo {
card_issuer: card_data.card_issuer.to_owned(),
card_network,
card_type: card_data.card_type.to_owned(),
card_issuing_country: card_data.card_issuing_country.to_owned(),
bank_code: card_data.bank_code.to_owned(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated,
signature_network: signature_network.clone(),
}),
)))
} else {
let card_info = card_isin
.clone()
.async_and_then(|card_isin| async move {
db.get_card_info(&card_isin)
.await
.map_err(|error| services::logger::warn!(card_info_error=?error))
.ok()
})
.await
.flatten()
.map(|card_info| {
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: card_info.card_issuer,
card_network: card_network.clone().or(card_info.card_network),
bank_code: card_info.bank_code,
card_type: card_info.card_type,
card_issuing_country: card_info.card_issuing_country,
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated,
signature_network: signature_network.clone(),
},
))
});
Ok(Some(card_info.unwrap_or_else(|| {
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: None,
card_network,
bank_code: None,
card_type: None,
card_issuing_country: None,
last4,
card_isin,
card_extended_bin,
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated,
signature_network: signature_network.clone(),
},
))
})))
}
}
domain::PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data {
domain::BankRedirectData::Eps { bank_name, .. } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: bank_name.to_owned(),
details: None,
},
)),
domain::BankRedirectData::Eft { .. } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: None,
},
)),
domain::BankRedirectData::OnlineBankingFpx { issuer } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: Some(issuer.to_owned()),
details: None,
},
)),
domain::BankRedirectData::Ideal { bank_name, .. } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: bank_name.to_owned(),
details: None,
},
)),
domain::BankRedirectData::BancontactCard {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
} => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: Some(
payment_additional_types::BankRedirectDetails::BancontactCard(Box::new(
payment_additional_types::BancontactBankRedirectAdditionalData {
last4: card_number.as_ref().map(|c| c.get_last4()),
card_exp_month: card_exp_month.clone(),
card_exp_year: card_exp_year.clone(),
card_holder_name: card_holder_name.clone(),
},
)),
),
},
)),
domain::BankRedirectData::Blik { blik_code } => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: blik_code.as_ref().map(|blik_code| {
payment_additional_types::BankRedirectDetails::Blik(Box::new(
payment_additional_types::BlikBankRedirectAdditionalData {
blik_code: Some(blik_code.to_owned()),
},
))
}),
},
)),
domain::BankRedirectData::Giropay {
bank_account_bic,
bank_account_iban,
country,
} => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: Some(payment_additional_types::BankRedirectDetails::Giropay(
Box::new(
payment_additional_types::GiropayBankRedirectAdditionalData {
bic: bank_account_bic
.as_ref()
.map(|bic| MaskedSortCode::from(bic.to_owned())),
iban: bank_account_iban
.as_ref()
.map(|iban| MaskedIban::from(iban.to_owned())),
country: *country,
},
),
)),
},
)),
_ => Ok(Some(
api_models::payments::AdditionalPaymentData::BankRedirect {
bank_name: None,
details: None,
},
)),
},
domain::PaymentMethodData::Wallet(wallet) => match wallet {
domain::WalletData::ApplePay(apple_pay_wallet_data) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: Some(api_models::payments::ApplepayPaymentMethod {
display_name: apple_pay_wallet_data.payment_method.display_name.clone(),
network: apple_pay_wallet_data.payment_method.network.clone(),
pm_type: apple_pay_wallet_data.payment_method.pm_type.clone(),
}),
google_pay: None,
samsung_pay: None,
}))
}
domain::WalletData::GooglePay(google_pay_pm_data) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: Some(payment_additional_types::WalletAdditionalDataForCard {
last4: google_pay_pm_data.info.card_details.clone(),
card_network: google_pay_pm_data.info.card_network.clone(),
card_type: Some(google_pay_pm_data.pm_type.clone()),
}),
samsung_pay: None,
}))
}
domain::WalletData::SamsungPay(samsung_pay_pm_data) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: Some(payment_additional_types::WalletAdditionalDataForCard {
last4: samsung_pay_pm_data
.payment_credential
.card_last_four_digits
.clone(),
card_network: samsung_pay_pm_data
.payment_credential
.card_brand
.to_string(),
card_type: None,
}),
}))
}
_ => Ok(Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: None,
})),
},
domain::PaymentMethodData::PayLater(_) => Ok(Some(
api_models::payments::AdditionalPaymentData::PayLater { klarna_sdk: None },
)),
domain::PaymentMethodData::BankTransfer(bank_transfer) => Ok(Some(
api_models::payments::AdditionalPaymentData::BankTransfer {
details: Some((*(bank_transfer.to_owned())).into()),
},
)),
domain::PaymentMethodData::Crypto(crypto) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Crypto {
details: Some(crypto.to_owned().into()),
}))
}
domain::PaymentMethodData::BankDebit(bank_debit) => Ok(Some(
api_models::payments::AdditionalPaymentData::BankDebit {
details: Some(bank_debit.to_owned().into()),
},
)),
domain::PaymentMethodData::MandatePayment => Ok(Some(
api_models::payments::AdditionalPaymentData::MandatePayment {},
)),
domain::PaymentMethodData::Reward => {
Ok(Some(api_models::payments::AdditionalPaymentData::Reward {}))
}
domain::PaymentMethodData::RealTimePayment(realtime_payment) => Ok(Some(
api_models::payments::AdditionalPaymentData::RealTimePayment {
details: Some((*(realtime_payment.to_owned())).into()),
},
)),
domain::PaymentMethodData::Upi(upi) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Upi {
details: Some(upi.to_owned().into()),
}))
}
domain::PaymentMethodData::CardRedirect(card_redirect) => Ok(Some(
api_models::payments::AdditionalPaymentData::CardRedirect {
details: Some(card_redirect.to_owned().into()),
},
)),
domain::PaymentMethodData::Voucher(voucher) => {
Ok(Some(api_models::payments::AdditionalPaymentData::Voucher {
details: Some(voucher.to_owned().into()),
}))
}
domain::PaymentMethodData::GiftCard(gift_card) => Ok(Some(
api_models::payments::AdditionalPaymentData::GiftCard {
details: Some((*(gift_card.to_owned())).into()),
},
)),
domain::PaymentMethodData::CardToken(card_token) => Ok(Some(
api_models::payments::AdditionalPaymentData::CardToken {
details: Some(card_token.to_owned().into()),
},
)),
domain::PaymentMethodData::OpenBanking(open_banking) => Ok(Some(
api_models::payments::AdditionalPaymentData::OpenBanking {
details: Some(open_banking.to_owned().into()),
},
)),
domain::PaymentMethodData::CardDetailsForNetworkTransactionId(card_data) => {
let card_isin = Some(card_data.card_number.get_card_isin());
let enable_extended_bin =db
.find_config_by_key_unwrap_or(
format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(),
Some("false".to_string()))
.await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok();
let card_extended_bin = match enable_extended_bin {
Some(config) if config.config == "true" => {
Some(card_data.card_number.get_extended_card_bin())
}
_ => None,
};
let card_network = match card_data
.card_number
.is_cobadged_card()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Card cobadge check failed due to an invalid card network regex",
)? {
true => card_data.card_network.clone(),
false => None,
};
let last4 = Some(card_data.card_number.get_last4());
if card_data.card_issuer.is_some()
&& card_network.is_some()
&& card_data.card_type.is_some()
&& card_data.card_issuing_country.is_some()
&& card_data.bank_code.is_some()
{
Ok(Some(api_models::payments::AdditionalPaymentData::Card(
Box::new(api_models::payments::AdditionalCardInfo {
card_issuer: card_data.card_issuer.to_owned(),
card_network,
card_type: card_data.card_type.to_owned(),
card_issuing_country: card_data.card_issuing_country.to_owned(),
bank_code: card_data.bank_code.to_owned(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
}),
)))
} else {
let card_info = card_isin
.clone()
.async_and_then(|card_isin| async move {
db.get_card_info(&card_isin)
.await
.map_err(|error| services::logger::warn!(card_info_error=?error))
.ok()
})
.await
.flatten()
.map(|card_info| {
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: card_info.card_issuer,
card_network: card_network.clone().or(card_info.card_network),
bank_code: card_info.bank_code,
card_type: card_info.card_type,
card_issuing_country: card_info.card_issuing_country,
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
},
))
});
Ok(Some(card_info.unwrap_or_else(|| {
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: None,
card_network,
bank_code: None,
card_type: None,
card_issuing_country: None,
last4,
card_isin,
card_extended_bin,
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
// These are filled after calling the processor / connector
payment_checks: None,
authentication_data: None,
is_regulated: None,
signature_network: None,
},
))
})))
}
}
domain::PaymentMethodData::MobilePayment(mobile_payment) => Ok(Some(
api_models::payments::AdditionalPaymentData::MobilePayment {
details: Some(mobile_payment.to_owned().into()),
},
)),
domain::PaymentMethodData::NetworkToken(_) => Ok(None),
}
}
#[cfg(feature = "v1")]
pub fn validate_customer_access(
payment_intent: &PaymentIntent,
auth_flow: services::AuthFlow,
request: &api::PaymentsRequest,
) -> Result<(), errors::ApiErrorResponse> {
if auth_flow == services::AuthFlow::Client && request.get_customer_id().is_some() {
let is_same_customer = request.get_customer_id() == payment_intent.customer_id.as_ref();
if !is_same_customer {
Err(errors::ApiErrorResponse::GenericUnauthorized {
message: "Unauthorised access to update customer".to_string(),
})?;
}
}
Ok(())
}
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
connector_name: Option<&String>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
let option_apple_pay_metadata = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::info!(
"Apple pay metadata parsing for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
})
.ok();
// return true only if the apple flow type is simplified
Ok(matches!(
option_apple_pay_metadata,
Some(
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
api_models::payments::ApplePayCombinedMetadata::Simplified { .. }
)
)
))
}
// This function will return the encrypted connector wallets details with Apple Pay certificates
// Currently apple pay certifiactes are stored in the metadata which is not encrypted.
// In future we want those certificates to be encrypted and stored in the connector_wallets_details.
// As part of migration fallback this function checks apple pay details are present in connector_wallets_details
// If yes, it will encrypt connector_wallets_details and store it in the database.
// If no, it will check if apple pay details are present in metadata and merge it with connector_wallets_details, encrypt and store it.
pub async fn get_connector_wallets_details_with_apple_pay_certificates(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<masking::Secret<serde_json::Value>>> {
let connector_wallet_details_with_apple_pay_metadata_optional =
get_apple_pay_metadata_if_needed(connector_metadata, connector_wallets_details_optional)
.await?;
let connector_wallets_details = connector_wallet_details_with_apple_pay_metadata_optional
.map(|details| {
serde_json::to_value(details)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")
})
.transpose()?
.map(masking::Secret::new);
Ok(connector_wallets_details)
}
async fn get_apple_pay_metadata_if_needed(
connector_metadata: &Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: &Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
if let Some(connector_wallets_details) = connector_wallets_details_optional {
if connector_wallets_details.apple_pay_combined.is_some()
|| connector_wallets_details.apple_pay.is_some()
{
return Ok(Some(connector_wallets_details.clone()));
}
// Otherwise, merge Apple Pay metadata
return get_and_merge_apple_pay_metadata(
connector_metadata.clone(),
Some(connector_wallets_details.clone()),
)
.await;
}
// If connector_wallets_details_optional is None, attempt to get Apple Pay metadata
get_and_merge_apple_pay_metadata(connector_metadata.clone(), None).await
}
async fn get_and_merge_apple_pay_metadata(
connector_metadata: Option<masking::Secret<tera::Value>>,
connector_wallets_details_optional: Option<api_models::admin::ConnectorWalletDetails>,
) -> RouterResult<Option<api_models::admin::ConnectorWalletDetails>> {
let apple_pay_metadata_optional = get_applepay_metadata(connector_metadata)
.map_err(|error| {
logger::error!(
"Apple Pay metadata parsing failed in get_encrypted_connector_wallets_details_with_apple_pay_certificates {:?}",
error
);
})
.ok();
if let Some(apple_pay_metadata) = apple_pay_metadata_optional {
let updated_wallet_details = match apple_pay_metadata {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
apple_pay_combined_metadata,
) => {
let combined_metadata_json = serde_json::to_value(apple_pay_combined_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay combined metadata as JSON")?;
api_models::admin::ConnectorWalletDetails {
apple_pay_combined: Some(masking::Secret::new(combined_metadata_json)),
apple_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.apple_pay.clone()),
amazon_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.amazon_pay.clone()),
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
google_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.google_pay.clone()),
}
}
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
let metadata_json = serde_json::to_value(apple_pay_metadata)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize Apple Pay metadata as JSON")?;
api_models::admin::ConnectorWalletDetails {
apple_pay: Some(masking::Secret::new(metadata_json)),
apple_pay_combined: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.apple_pay_combined.clone()),
amazon_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.amazon_pay.clone()),
samsung_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.samsung_pay.clone()),
paze: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.paze.clone()),
google_pay: connector_wallets_details_optional
.as_ref()
.and_then(|d| d.google_pay.clone()),
}
}
};
return Ok(Some(updated_wallet_details));
}
// Return connector_wallets_details if no Apple Pay metadata was found
Ok(connector_wallets_details_optional)
}
pub fn get_applepay_metadata(
connector_metadata: Option<pii::SecretSerdeValue>,
) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> {
connector_metadata
.clone()
.parse_value::<api_models::payments::ApplepayCombinedSessionTokenData>(
"ApplepayCombinedSessionTokenData",
)
.map(|combined_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
combined_metadata.apple_pay_combined,
)
})
.or_else(|_| {
connector_metadata
.parse_value::<api_models::payments::ApplepaySessionTokenData>(
"ApplepaySessionTokenData",
)
.map(|old_metadata| {
api_models::payments::ApplepaySessionTokenMetadata::ApplePay(
old_metadata.apple_pay,
)
})
})
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "connector_metadata".to_string(),
expected_format: "applepay_metadata_format".to_string(),
})
}
pub fn calculate_debit_routing_savings(net_amount: i64, saving_percentage: f64) -> MinorUnit {
logger::debug!(
?net_amount,
?saving_percentage,
"Calculating debit routing saving amount"
);
let net_decimal = Decimal::from_i64(net_amount).unwrap_or_else(|| {
logger::warn!(?net_amount, "Invalid net_amount, using 0");
Decimal::ZERO
});
let percentage_decimal = Decimal::from_f64(saving_percentage).unwrap_or_else(|| {
logger::warn!(?saving_percentage, "Invalid saving_percentage, using 0");
Decimal::ZERO
});
let savings_decimal = net_decimal * percentage_decimal / Decimal::from(100);
let rounded_savings = savings_decimal.round();
let savings_int = rounded_savings.to_i64().unwrap_or_else(|| {
logger::warn!(
?rounded_savings,
"Debit routing savings calculation overflowed when converting to i64"
);
0
});
MinorUnit::new(savings_int)
}
pub fn get_debit_routing_savings_amount(
payment_method_data: &domain::PaymentMethodData,
payment_attempt: &PaymentAttempt,
) -> Option<MinorUnit> {
let card_network = payment_attempt.extract_card_network()?;
let saving_percentage =
payment_method_data.extract_debit_routing_saving_percentage(&card_network)?;
let net_amount = payment_attempt.get_total_amount().get_amount_as_i64();
Some(calculate_debit_routing_savings(
net_amount,
saving_percentage,
))
}
#[cfg(all(feature = "retry", feature = "v1"))]
pub async fn get_apple_pay_retryable_connectors<F, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &D,
pre_routing_connector_data_list: &[api::ConnectorRoutingData],
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
business_profile: domain::Profile,
) -> CustomResult<Option<Vec<api::ConnectorRoutingData>>, errors::ApiErrorResponse>
where
F: Send + Clone,
D: OperationSessionGetters<F> + Send,
{
let profile_id = business_profile.get_id();
let pre_decided_connector_data_first = pre_routing_connector_data_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
let merchant_connector_account_type = get_merchant_connector_account(
state,
merchant_context.get_merchant_account().get_id(),
payment_data.get_creds_identifier(),
merchant_context.get_merchant_key_store(),
profile_id,
&pre_decided_connector_data_first
.connector_data
.connector_name
.to_string(),
merchant_connector_id,
)
.await?;
let connector_data_list = if is_apple_pay_simplified_flow(
merchant_connector_account_type.get_metadata(),
merchant_connector_account_type
.get_connector_name()
.as_ref(),
)? {
let merchant_connector_account_list = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_context.get_merchant_account().get_id(),
false,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let profile_specific_merchant_connector_account_list = merchant_connector_account_list
.filter_based_on_profile_and_connector_type(
profile_id,
ConnectorType::PaymentProcessor,
);
let mut connector_data_list = vec![pre_decided_connector_data_first.clone()];
for merchant_connector_account in profile_specific_merchant_connector_account_list {
if is_apple_pay_simplified_flow(
merchant_connector_account.metadata.clone(),
Some(&merchant_connector_account.connector_name),
)? {
let routing_data: api::ConnectorRoutingData =
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&merchant_connector_account.connector_name.to_string(),
api::GetToken::Connector,
Some(merchant_connector_account.get_id()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?
.into();
if !connector_data_list.iter().any(|connector_details| {
connector_details.connector_data.merchant_connector_id
== routing_data.connector_data.merchant_connector_id
}) {
connector_data_list.push(routing_data)
}
}
}
#[cfg(feature = "v1")]
let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config(
&*state.clone().store,
profile_id.get_string_repr(),
&api_enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get merchant default fallback connectors config")?;
let mut routing_connector_data_list = Vec::new();
pre_routing_connector_data_list.iter().for_each(|pre_val| {
routing_connector_data_list.push(pre_val.connector_data.merchant_connector_id.clone())
});
fallback_connetors_list.iter().for_each(|fallback_val| {
routing_connector_data_list
.iter()
.all(|val| *val != fallback_val.merchant_connector_id)
.then(|| {
routing_connector_data_list.push(fallback_val.merchant_connector_id.clone())
});
});
// connector_data_list is the list of connectors for which Apple Pay simplified flow is configured.
// This list is arranged in the same order as the merchant's connectors routingconfiguration.
let mut ordered_connector_data_list = Vec::new();
routing_connector_data_list
.iter()
.for_each(|merchant_connector_id| {
let connector_data = connector_data_list.iter().find(|connector_data| {
*merchant_connector_id == connector_data.connector_data.merchant_connector_id
});
if let Some(connector_data_details) = connector_data {
ordered_connector_data_list.push(connector_data_details.clone());
}
});
Some(ordered_connector_data_list)
} else {
None
};
Ok(connector_data_list)
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ApplePayData {
version: masking::Secret<String>,
data: masking::Secret<String>,
signature: masking::Secret<String>,
header: ApplePayHeader,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayHeader {
ephemeral_public_key: masking::Secret<String>,
public_key_hash: masking::Secret<String>,
transaction_id: masking::Secret<String>,
}
impl ApplePayData {
pub fn token_json(
wallet_data: domain::WalletData,
) -> CustomResult<Self, errors::ConnectorError> {
let json_wallet_data: Self = connector::utils::WalletData::get_wallet_token_as_json(
&wallet_data,
"Apple Pay".to_string(),
)?;
Ok(json_wallet_data)
}
pub async fn decrypt(
&self,
payment_processing_certificate: &masking::Secret<String>,
payment_processing_certificate_key: &masking::Secret<String>,
) -> CustomResult<serde_json::Value, errors::ApplePayDecryptionError> {
let merchant_id = self.merchant_id(payment_processing_certificate)?;
let shared_secret = self.shared_secret(payment_processing_certificate_key)?;
let symmetric_key = self.symmetric_key(&merchant_id, &shared_secret)?;
let decrypted = self.decrypt_ciphertext(&symmetric_key)?;
let parsed_decrypted: serde_json::Value = serde_json::from_str(&decrypted)
.change_context(errors::ApplePayDecryptionError::DecryptionFailed)?;
Ok(parsed_decrypted)
}
pub fn merchant_id(
&self,
payment_processing_certificate: &masking::Secret<String>,
) -> CustomResult<String, errors::ApplePayDecryptionError> {
let cert_data = payment_processing_certificate.clone().expose();
let base64_decode_cert_data = BASE64_ENGINE
.decode(cert_data)
.change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?;
// Parsing the certificate using x509-parser
let (_, certificate) = parse_x509_certificate(&base64_decode_cert_data)
.change_context(errors::ApplePayDecryptionError::CertificateParsingFailed)
.attach_printable("Error parsing apple pay PPC")?;
// Finding the merchant ID extension
let apple_pay_m_id = certificate
.extensions()
.iter()
.find(|extension| {
extension
.oid
.to_string()
.eq(consts::MERCHANT_ID_FIELD_EXTENSION_ID)
})
.map(|ext| {
let merchant_id = String::from_utf8_lossy(ext.value)
.trim()
.trim_start_matches('@')
.to_string();
merchant_id
})
.ok_or(errors::ApplePayDecryptionError::MissingMerchantId)
.attach_printable("Unable to find merchant ID extension in the certificate")?;
Ok(apple_pay_m_id)
}
pub fn shared_secret(
&self,
payment_processing_certificate_key: &masking::Secret<String>,
) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> {
let public_ec_bytes = BASE64_ENGINE
.decode(self.header.ephemeral_public_key.peek().as_bytes())
.change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?;
let public_key = PKey::public_key_from_der(&public_ec_bytes)
.change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed)
.attach_printable("Failed to deserialize the public key")?;
let decrypted_apple_pay_ppc_key = payment_processing_certificate_key.clone().expose();
// Create PKey objects from EcKey
let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes())
.change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed)
.attach_printable("Failed to deserialize the private key")?;
// Create the Deriver object and set the peer public key
let mut deriver = Deriver::new(&private_key)
.change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed)
.attach_printable("Failed to create a deriver for the private key")?;
deriver
.set_peer(&public_key)
.change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed)
.attach_printable("Failed to set the peer key for the secret derivation")?;
// Compute the shared secret
let shared_secret = deriver
.derive_to_vec()
.change_context(errors::ApplePayDecryptionError::DerivingSharedSecretKeyFailed)
.attach_printable("Final key derivation failed")?;
Ok(shared_secret)
}
pub fn symmetric_key(
&self,
merchant_id: &str,
shared_secret: &[u8],
) -> CustomResult<Vec<u8>, errors::ApplePayDecryptionError> {
let kdf_algorithm = b"\x0did-aes256-GCM";
let kdf_party_v = hex::decode(merchant_id)
.change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?;
let kdf_party_u = b"Apple";
let kdf_info = [&kdf_algorithm[..], kdf_party_u, &kdf_party_v[..]].concat();
let mut hash = openssl::sha::Sha256::new();
hash.update(b"\x00\x00\x00");
hash.update(b"\x01");
hash.update(shared_secret);
hash.update(&kdf_info[..]);
let symmetric_key = hash.finish();
Ok(symmetric_key.to_vec())
}
pub fn decrypt_ciphertext(
&self,
symmetric_key: &[u8],
) -> CustomResult<String, errors::ApplePayDecryptionError> {
logger::info!("Decrypt apple pay token");
let data = BASE64_ENGINE
.decode(self.data.peek().as_bytes())
.change_context(errors::ApplePayDecryptionError::Base64DecodingFailed)?;
let iv = [0u8; 16]; //Initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process.
let ciphertext = data
.get(..data.len() - 16)
.ok_or(errors::ApplePayDecryptionError::DecryptionFailed)?;
let tag = data
.get(data.len() - 16..)
.ok_or(errors::ApplePayDecryptionError::DecryptionFailed)?;
let cipher = Cipher::aes_256_gcm();
let decrypted_data = decrypt_aead(cipher, symmetric_key, Some(&iv), &[], ciphertext, tag)
.change_context(errors::ApplePayDecryptionError::DecryptionFailed)?;
let decrypted = String::from_utf8(decrypted_data)
.change_context(errors::ApplePayDecryptionError::DecryptionFailed)?;
Ok(decrypted)
}
}
// Structs for keys and the main decryptor
pub struct GooglePayTokenDecryptor {
root_signing_keys: Vec<GooglePayRootSigningKey>,
recipient_id: masking::Secret<String>,
private_key: PKey<openssl::pkey::Private>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EncryptedData {
signature: String,
intermediate_signing_key: IntermediateSigningKey,
protocol_version: GooglePayProtocolVersion,
#[serde(with = "common_utils::custom_serde::json_string")]
signed_message: GooglePaySignedMessage,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePaySignedMessage {
#[serde(with = "common_utils::Base64Serializer")]
encrypted_message: masking::Secret<Vec<u8>>,
#[serde(with = "common_utils::Base64Serializer")]
ephemeral_public_key: masking::Secret<Vec<u8>>,
#[serde(with = "common_utils::Base64Serializer")]
tag: masking::Secret<Vec<u8>>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IntermediateSigningKey {
signed_key: masking::Secret<String>,
signatures: Vec<masking::Secret<String>>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePaySignedKey {
key_value: masking::Secret<String>,
key_expiration: String,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayRootSigningKey {
key_value: masking::Secret<String>,
key_expiration: String,
protocol_version: GooglePayProtocolVersion,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
pub enum GooglePayProtocolVersion {
#[serde(rename = "ECv2")]
EcProtocolVersion2,
}
// Check expiration date validity
fn check_expiration_date_is_valid(
expiration: &str,
) -> CustomResult<bool, errors::GooglePayDecryptionError> {
let expiration_ms = expiration
.parse::<i128>()
.change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?;
// convert milliseconds to nanoseconds (1 millisecond = 1_000_000 nanoseconds) to create OffsetDateTime
let expiration_time =
time::OffsetDateTime::from_unix_timestamp_nanos(expiration_ms * 1_000_000)
.change_context(errors::GooglePayDecryptionError::InvalidExpirationTime)?;
let now = time::OffsetDateTime::now_utc();
Ok(expiration_time > now)
}
// Construct little endian format of u32
fn get_little_endian_format(number: u32) -> Vec<u8> {
number.to_le_bytes().to_vec()
}
// Filter and parse the root signing keys based on protocol version and expiration time
fn filter_root_signing_keys(
root_signing_keys: Vec<GooglePayRootSigningKey>,
) -> CustomResult<Vec<GooglePayRootSigningKey>, errors::GooglePayDecryptionError> {
let filtered_root_signing_keys = root_signing_keys
.iter()
.filter(|key| {
key.protocol_version == GooglePayProtocolVersion::EcProtocolVersion2
&& matches!(
check_expiration_date_is_valid(&key.key_expiration).inspect_err(
|err| logger::warn!(
"Failed to check expirattion due to invalid format: {:?}",
err
)
),
Ok(true)
)
})
.cloned()
.collect::<Vec<GooglePayRootSigningKey>>();
logger::info!(
"Filtered {} out of {} root signing keys",
filtered_root_signing_keys.len(),
root_signing_keys.len()
);
Ok(filtered_root_signing_keys)
}
impl GooglePayTokenDecryptor {
pub fn new(
root_keys: masking::Secret<String>,
recipient_id: masking::Secret<String>,
private_key: masking::Secret<String>,
) -> CustomResult<Self, errors::GooglePayDecryptionError> {
// base64 decode the private key
let decoded_key = BASE64_ENGINE
.decode(private_key.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// base64 decode the root signing keys
let decoded_root_signing_keys = BASE64_ENGINE
.decode(root_keys.expose())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// create a private key from the decoded key
let private_key = PKey::private_key_from_pkcs8(&decoded_key)
.change_context(errors::GooglePayDecryptionError::KeyDeserializationFailed)
.attach_printable("cannot convert private key from decode_key")?;
// parse the root signing keys
let root_keys_vector: Vec<GooglePayRootSigningKey> = decoded_root_signing_keys
.parse_struct("GooglePayRootSigningKey")
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// parse and filter the root signing keys by protocol version
let filtered_root_signing_keys = filter_root_signing_keys(root_keys_vector)?;
Ok(Self {
root_signing_keys: filtered_root_signing_keys,
recipient_id,
private_key,
})
}
// Decrypt the Google pay token
pub fn decrypt_token(
&self,
data: String,
should_verify_signature: bool,
) -> CustomResult<
hyperswitch_domain_models::router_data::GooglePayPredecryptDataInternal,
errors::GooglePayDecryptionError,
> {
// parse the encrypted data
let encrypted_data: EncryptedData = data
.parse_struct("EncryptedData")
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// verify the signature if required
if should_verify_signature {
self.verify_signature(&encrypted_data)?;
}
let ephemeral_public_key = encrypted_data.signed_message.ephemeral_public_key.peek();
let tag = encrypted_data.signed_message.tag.peek();
let encrypted_message = encrypted_data.signed_message.encrypted_message.peek();
// derive the shared key
let shared_key = self.get_shared_key(ephemeral_public_key)?;
// derive the symmetric encryption key and MAC key
let derived_key = self.derive_key(ephemeral_public_key, &shared_key)?;
// First 32 bytes for AES-256 and Remaining bytes for HMAC
let (symmetric_encryption_key, mac_key) = derived_key
.split_at_checked(32)
.ok_or(errors::GooglePayDecryptionError::ParsingFailed)?;
// verify the HMAC of the message
self.verify_hmac(mac_key, tag, encrypted_message)?;
// decrypt the message
let decrypted = self.decrypt_message(symmetric_encryption_key, encrypted_message)?;
// parse the decrypted data
let decrypted_data: hyperswitch_domain_models::router_data::GooglePayPredecryptDataInternal =
decrypted
.parse_struct("GooglePayPredecryptDataInternal")
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// check the expiration date of the decrypted data
if matches!(
check_expiration_date_is_valid(&decrypted_data.message_expiration),
Ok(true)
) {
Ok(decrypted_data)
} else {
Err(errors::GooglePayDecryptionError::DecryptedTokenExpired.into())
}
}
// Verify the signature of the token
fn verify_signature(
&self,
encrypted_data: &EncryptedData,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
// check the protocol version
if encrypted_data.protocol_version != GooglePayProtocolVersion::EcProtocolVersion2 {
return Err(errors::GooglePayDecryptionError::InvalidProtocolVersion.into());
}
// verify the intermediate signing key
self.verify_intermediate_signing_key(encrypted_data)?;
// validate and fetch the signed key
let signed_key = self.validate_signed_key(&encrypted_data.intermediate_signing_key)?;
// verify the signature of the token
self.verify_message_signature(encrypted_data, &signed_key)
}
// Verify the intermediate signing key
fn verify_intermediate_signing_key(
&self,
encrypted_data: &EncryptedData,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
let mut signatrues: Vec<openssl::ecdsa::EcdsaSig> = Vec::new();
// decode and parse the signatures
for signature in encrypted_data.intermediate_signing_key.signatures.iter() {
let signature = BASE64_ENGINE
.decode(signature.peek())
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature)
.change_context(errors::GooglePayDecryptionError::EcdsaSignatureParsingFailed)?;
signatrues.push(ecdsa_signature);
}
// get the sender id i.e. Google
let sender_id = String::from_utf8(consts::SENDER_ID.to_vec())
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// construct the signed data
let signed_data = self.construct_signed_data_for_intermediate_signing_key_verification(
&sender_id,
consts::PROTOCOL,
encrypted_data.intermediate_signing_key.signed_key.peek(),
)?;
// check if any of the signatures are valid for any of the root signing keys
for key in self.root_signing_keys.iter() {
// decode and create public key
let public_key = self
.load_public_key(key.key_value.peek())
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
// fetch the ec key from public key
let ec_key = public_key
.ec_key()
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// hash the signed data
let message_hash = openssl::sha::sha256(&signed_data);
// verify if any of the signatures is valid against the given key
for signature in signatrues.iter() {
let result = signature.verify(&message_hash, &ec_key).change_context(
errors::GooglePayDecryptionError::SignatureVerificationFailed,
)?;
if result {
return Ok(());
}
}
}
Err(errors::GooglePayDecryptionError::InvalidIntermediateSignature.into())
}
// Construct signed data for intermediate signing key verification
fn construct_signed_data_for_intermediate_signing_key_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let length_of_sender_id = u32::try_from(sender_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_protocol_version = u32::try_from(protocol_version.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_signed_key = u32::try_from(signed_key.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let mut signed_data: Vec<u8> = Vec::new();
signed_data.append(&mut get_little_endian_format(length_of_sender_id));
signed_data.append(&mut sender_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_protocol_version));
signed_data.append(&mut protocol_version.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_signed_key));
signed_data.append(&mut signed_key.as_bytes().to_vec());
Ok(signed_data)
}
// Validate and parse signed key
fn validate_signed_key(
&self,
intermediate_signing_key: &IntermediateSigningKey,
) -> CustomResult<GooglePaySignedKey, errors::GooglePayDecryptionError> {
let signed_key: GooglePaySignedKey = intermediate_signing_key
.signed_key
.clone()
.expose()
.parse_struct("GooglePaySignedKey")
.change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?;
if !matches!(
check_expiration_date_is_valid(&signed_key.key_expiration),
Ok(true)
) {
return Err(errors::GooglePayDecryptionError::SignedKeyExpired)?;
}
Ok(signed_key)
}
// Verify the signed message
fn verify_message_signature(
&self,
encrypted_data: &EncryptedData,
signed_key: &GooglePaySignedKey,
) -> CustomResult<(), errors::GooglePayDecryptionError> {
// create a public key from the intermediate signing key
let public_key = self.load_public_key(signed_key.key_value.peek())?;
// base64 decode the signature
let signature = BASE64_ENGINE
.decode(&encrypted_data.signature)
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// parse the signature using ECDSA
let ecdsa_signature = openssl::ecdsa::EcdsaSig::from_der(&signature)
.change_context(errors::GooglePayDecryptionError::EcdsaSignatureFailed)?;
// get the EC key from the public key
let ec_key = public_key
.ec_key()
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// get the sender id i.e. Google
let sender_id = String::from_utf8(consts::SENDER_ID.to_vec())
.change_context(errors::GooglePayDecryptionError::DeserializationFailed)?;
// serialize the signed message to string
let signed_message = serde_json::to_string(&encrypted_data.signed_message)
.change_context(errors::GooglePayDecryptionError::SignedKeyParsingFailure)?;
// construct the signed data
let signed_data = self.construct_signed_data_for_signature_verification(
&sender_id,
consts::PROTOCOL,
&signed_message,
)?;
// hash the signed data
let message_hash = openssl::sha::sha256(&signed_data);
// verify the signature
let result = ecdsa_signature
.verify(&message_hash, &ec_key)
.change_context(errors::GooglePayDecryptionError::SignatureVerificationFailed)?;
if result {
Ok(())
} else {
Err(errors::GooglePayDecryptionError::InvalidSignature)?
}
}
// Fetch the public key
fn load_public_key(
&self,
key: &str,
) -> CustomResult<PKey<openssl::pkey::Public>, errors::GooglePayDecryptionError> {
// decode the base64 string
let der_data = BASE64_ENGINE
.decode(key)
.change_context(errors::GooglePayDecryptionError::Base64DecodingFailed)?;
// parse the DER-encoded data as an EC public key
let ec_key = openssl::ec::EcKey::public_key_from_der(&der_data)
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// wrap the EC key in a PKey (a more general-purpose public key type in OpenSSL)
let public_key = PKey::from_ec_key(ec_key)
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
Ok(public_key)
}
// Construct signed data for signature verification
fn construct_signed_data_for_signature_verification(
&self,
sender_id: &str,
protocol_version: &str,
signed_key: &str,
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let recipient_id = self.recipient_id.clone().expose();
let length_of_sender_id = u32::try_from(sender_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_recipient_id = u32::try_from(recipient_id.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_protocol_version = u32::try_from(protocol_version.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let length_of_signed_key = u32::try_from(signed_key.len())
.change_context(errors::GooglePayDecryptionError::ParsingFailed)?;
let mut signed_data: Vec<u8> = Vec::new();
signed_data.append(&mut get_little_endian_format(length_of_sender_id));
signed_data.append(&mut sender_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_recipient_id));
signed_data.append(&mut recipient_id.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_protocol_version));
signed_data.append(&mut protocol_version.as_bytes().to_vec());
signed_data.append(&mut get_little_endian_format(length_of_signed_key));
signed_data.append(&mut signed_key.as_bytes().to_vec());
Ok(signed_data)
}
// Derive a shared key using ECDH
fn get_shared_key(
&self,
ephemeral_public_key_bytes: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
let group = openssl::ec::EcGroup::from_curve_name(openssl::nid::Nid::X9_62_PRIME256V1)
.change_context(errors::GooglePayDecryptionError::DerivingEcGroupFailed)?;
let mut big_num_context = openssl::bn::BigNumContext::new()
.change_context(errors::GooglePayDecryptionError::BigNumAllocationFailed)?;
let ec_key = openssl::ec::EcPoint::from_bytes(
&group,
ephemeral_public_key_bytes,
&mut big_num_context,
)
.change_context(errors::GooglePayDecryptionError::DerivingEcKeyFailed)?;
// create an ephemeral public key from the given bytes
let ephemeral_public_key = openssl::ec::EcKey::from_public_key(&group, &ec_key)
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
// wrap the public key in a PKey
let ephemeral_pkey = PKey::from_ec_key(ephemeral_public_key)
.change_context(errors::GooglePayDecryptionError::DerivingPublicKeyFailed)?;
// perform ECDH to derive the shared key
let mut deriver = Deriver::new(&self.private_key)
.change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
deriver
.set_peer(&ephemeral_pkey)
.change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
let shared_key = deriver
.derive_to_vec()
.change_context(errors::GooglePayDecryptionError::DerivingSharedSecretKeyFailed)?;
Ok(shared_key)
}
// Derive symmetric key and MAC key using HKDF
fn derive_key(
&self,
ephemeral_public_key_bytes: &[u8],
shared_key: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
// concatenate ephemeral public key and shared key
let input_key_material = [ephemeral_public_key_bytes, shared_key].concat();
// initialize HKDF with SHA-256 as the hash function
// Salt is not provided as per the Google Pay documentation
// https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec
let hkdf: ::hkdf::Hkdf<sha2::Sha256> = ::hkdf::Hkdf::new(None, &input_key_material);
// derive 64 bytes for the output key (symmetric encryption + MAC key)
let mut output_key = vec![0u8; 64];
hkdf.expand(consts::SENDER_ID, &mut output_key)
.map_err(|err| {
logger::error!(
"Failed to derive the shared ephemeral key for Google Pay decryption flow: {:?}",
err
);
report!(errors::GooglePayDecryptionError::DerivingSharedEphemeralKeyFailed)
})?;
Ok(output_key)
}
// Verify the Hmac key
// https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#encrypt-spec
fn verify_hmac(
&self,
mac_key: &[u8],
tag: &[u8],
encrypted_message: &[u8],
) -> CustomResult<(), errors::GooglePayDecryptionError> {
let hmac_key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, mac_key);
ring::hmac::verify(&hmac_key, encrypted_message, tag)
.change_context(errors::GooglePayDecryptionError::HmacVerificationFailed)
}
// Method to decrypt the AES-GCM encrypted message
fn decrypt_message(
&self,
symmetric_key: &[u8],
encrypted_message: &[u8],
) -> CustomResult<Vec<u8>, errors::GooglePayDecryptionError> {
//initialization vector IV is typically used in AES-GCM (Galois/Counter Mode) encryption for randomizing the encryption process.
// zero iv is being passed as specified in Google Pay documentation
// https://developers.google.com/pay/api/android/guides/resources/payment-data-cryptography#decrypt-token
let iv = [0u8; 16];
// extract the tag from the end of the encrypted message
let tag = encrypted_message
.get(encrypted_message.len() - 16..)
.ok_or(errors::GooglePayDecryptionError::ParsingTagError)?;
// decrypt the message using AES-256-CTR
let cipher = Cipher::aes_256_ctr();
let decrypted_data = decrypt_aead(
cipher,
symmetric_key,
Some(&iv),
&[],
encrypted_message,
tag,
)
.change_context(errors::GooglePayDecryptionError::DecryptionFailed)?;
Ok(decrypted_data)
}
}
pub fn decrypt_paze_token(
paze_wallet_data: PazeWalletData,
paze_private_key: masking::Secret<String>,
paze_private_key_passphrase: masking::Secret<String>,
) -> CustomResult<serde_json::Value, errors::PazeDecryptionError> {
let decoded_paze_private_key = BASE64_ENGINE
.decode(paze_private_key.expose().as_bytes())
.change_context(errors::PazeDecryptionError::Base64DecodingFailed)?;
let decrypted_private_key = openssl::rsa::Rsa::private_key_from_pem_passphrase(
decoded_paze_private_key.as_slice(),
paze_private_key_passphrase.expose().as_bytes(),
)
.change_context(errors::PazeDecryptionError::CertificateParsingFailed)?;
let decrypted_private_key_pem = String::from_utf8(
decrypted_private_key
.private_key_to_pem()
.change_context(errors::PazeDecryptionError::CertificateParsingFailed)?,
)
.change_context(errors::PazeDecryptionError::CertificateParsingFailed)?;
let decrypter = jwe::RSA_OAEP_256
.decrypter_from_pem(decrypted_private_key_pem)
.change_context(errors::PazeDecryptionError::CertificateParsingFailed)?;
let paze_complete_response: Vec<&str> = paze_wallet_data
.complete_response
.peek()
.split('.')
.collect();
let encrypted_jwe_key = paze_complete_response
.get(1)
.ok_or(errors::PazeDecryptionError::DecryptionFailed)?
.to_string();
let decoded_jwe_key = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(encrypted_jwe_key)
.change_context(errors::PazeDecryptionError::Base64DecodingFailed)?;
let jws_body: JwsBody = serde_json::from_slice(&decoded_jwe_key)
.change_context(errors::PazeDecryptionError::DecryptionFailed)?;
let (deserialized_payload, _deserialized_header) =
jwe::deserialize_compact(jws_body.secured_payload.peek(), &decrypter)
.change_context(errors::PazeDecryptionError::DecryptionFailed)?;
let encoded_secured_payload_element = String::from_utf8(deserialized_payload)
.change_context(errors::PazeDecryptionError::DecryptionFailed)?
.split('.')
.collect::<Vec<&str>>()
.get(1)
.ok_or(errors::PazeDecryptionError::DecryptionFailed)?
.to_string();
let decoded_secured_payload_element = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(encoded_secured_payload_element)
.change_context(errors::PazeDecryptionError::Base64DecodingFailed)?;
let parsed_decrypted: serde_json::Value =
serde_json::from_slice(&decoded_secured_payload_element)
.change_context(errors::PazeDecryptionError::DecryptionFailed)?;
Ok(parsed_decrypted)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JwsBody {
pub payload_id: String,
pub session_id: String,
pub secured_payload: masking::Secret<String>,
}
pub fn get_key_params_for_surcharge_details(
payment_method_data: &domain::PaymentMethodData,
) -> Option<(
common_enums::PaymentMethod,
common_enums::PaymentMethodType,
Option<common_enums::CardNetwork>,
)> {
match payment_method_data {
domain::PaymentMethodData::Card(card) => {
// surcharge generated will always be same for credit as well as debit
// since surcharge conditions cannot be defined on card_type
Some((
common_enums::PaymentMethod::Card,
common_enums::PaymentMethodType::Credit,
card.card_network.clone(),
))
}
domain::PaymentMethodData::CardRedirect(card_redirect_data) => Some((
common_enums::PaymentMethod::CardRedirect,
card_redirect_data.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::Wallet(wallet) => Some((
common_enums::PaymentMethod::Wallet,
wallet.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::PayLater(pay_later) => Some((
common_enums::PaymentMethod::PayLater,
pay_later.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::BankRedirect(bank_redirect) => Some((
common_enums::PaymentMethod::BankRedirect,
bank_redirect.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::BankDebit(bank_debit) => Some((
common_enums::PaymentMethod::BankDebit,
bank_debit.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::BankTransfer(bank_transfer) => Some((
common_enums::PaymentMethod::BankTransfer,
bank_transfer.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::Crypto(crypto) => Some((
common_enums::PaymentMethod::Crypto,
crypto.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::MandatePayment => None,
domain::PaymentMethodData::Reward => None,
domain::PaymentMethodData::RealTimePayment(real_time_payment) => Some((
common_enums::PaymentMethod::RealTimePayment,
real_time_payment.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::Upi(upi_data) => Some((
common_enums::PaymentMethod::Upi,
upi_data.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::Voucher(voucher) => Some((
common_enums::PaymentMethod::Voucher,
voucher.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::GiftCard(gift_card) => Some((
common_enums::PaymentMethod::GiftCard,
gift_card.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::OpenBanking(ob_data) => Some((
common_enums::PaymentMethod::OpenBanking,
ob_data.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::MobilePayment(mobile_payment) => Some((
common_enums::PaymentMethod::MobilePayment,
mobile_payment.get_payment_method_type(),
None,
)),
domain::PaymentMethodData::CardToken(_)
| domain::PaymentMethodData::NetworkToken(_)
| domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => None,
}
}
pub fn validate_payment_link_request(
request: &api::PaymentsRequest,
) -> Result<(), errors::ApiErrorResponse> {
#[cfg(feature = "v1")]
if request.confirm == Some(true) {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "cannot confirm a payment while creating a payment link".to_string(),
});
}
if request.return_url.is_none() {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "return_url must be sent while creating a payment link".to_string(),
});
}
Ok(())
}
pub async fn get_gsm_record(
state: &SessionState,
error_code: Option<String>,
error_message: Option<String>,
connector_name: String,
flow: String,
) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> {
let get_gsm = || async {
state.store.find_gsm_rule(
connector_name.clone(),
flow.clone(),
"sub_flow".to_string(),
error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response
error_message.clone().unwrap_or_default(),
)
.await
.map_err(|err| {
if err.current_context().is_db_not_found() {
logger::warn!(
"GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}",
connector_name,
flow,
error_code,
error_message
);
metrics::AUTO_RETRY_GSM_MISS_COUNT.add( 1, &[]);
} else {
metrics::AUTO_RETRY_GSM_FETCH_FAILURE_COUNT.add( 1, &[]);
};
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch decision from gsm")
})
};
get_gsm()
.await
.inspect_err(|err| {
// warn log should suffice here because we are not propagating this error
logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision");
})
.ok()
}
pub async fn get_unified_translation(
state: &SessionState,
unified_code: String,
unified_message: String,
locale: String,
) -> Option<String> {
let get_unified_translation = || async {
state.store.find_translation(
unified_code.clone(),
unified_message.clone(),
locale.clone(),
)
.await
.map_err(|err| {
if err.current_context().is_db_not_found() {
logger::warn!(
"Translation missing for unified_code - {:?}, unified_message - {:?}, locale - {:?}",
unified_code,
unified_message,
locale
);
}
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch translation from unified_translations")
})
};
get_unified_translation()
.await
.inspect_err(|err| {
// warn log should suffice here because we are not propagating this error
logger::warn!(get_translation_error=?err, "error fetching unified translations");
})
.ok()
}
pub fn validate_order_details_amount(
order_details: Vec<api_models::payments::OrderDetailsWithAmount>,
amount: MinorUnit,
should_validate: bool,
) -> Result<(), errors::ApiErrorResponse> {
if should_validate {
let total_order_details_amount: MinorUnit = order_details
.iter()
.map(|order| order.amount * order.quantity)
.sum();
if total_order_details_amount != amount {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Total sum of order details doesn't match amount in payment request"
.to_string(),
})
} else {
Ok(())
}
} else {
Ok(())
}
}
// This function validates the client secret expiry set by the merchant in the request
pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErrorResponse> {
if !(consts::MIN_SESSION_EXPIRY..=consts::MAX_SESSION_EXPIRY).contains(&session_expiry) {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "session_expiry should be between 60(1 min) to 7890000(3 months).".to_string(),
})
} else {
Ok(())
}
}
pub fn get_recipient_id_for_open_banking(
merchant_data: &AdditionalMerchantData,
) -> Result<Option<String>, errors::ApiErrorResponse> {
match merchant_data {
AdditionalMerchantData::OpenBankingRecipientData(data) => match data {
MerchantRecipientData::ConnectorRecipientId(id) => Ok(Some(id.peek().clone())),
MerchantRecipientData::AccountData(acc_data) => {
let connector_recipient_id = match acc_data {
MerchantAccountData::Bacs {
connector_recipient_id,
..
}
| MerchantAccountData::Iban {
connector_recipient_id,
..
}
| MerchantAccountData::FasterPayments {
connector_recipient_id,
..
}
| MerchantAccountData::Sepa {
connector_recipient_id,
..
}
| MerchantAccountData::SepaInstant {
connector_recipient_id,
..
}
| MerchantAccountData::Elixir {
connector_recipient_id,
..
}
| MerchantAccountData::Bankgiro {
connector_recipient_id,
..
}
| MerchantAccountData::Plusgiro {
connector_recipient_id,
..
} => connector_recipient_id,
};
match connector_recipient_id {
Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())),
Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())),
_ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: "recipient_id".to_string(),
}),
}
}
_ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: "recipient_id".to_string(),
}),
},
}
}
pub fn get_connector_data_with_token(
state: &SessionState,
connector_name: String,
merchant_connector_account_id: Option<id_type::MerchantConnectorAccountId>,
payment_method_type: api_models::enums::PaymentMethodType,
) -> RouterResult<api::ConnectorData> {
let connector_data_result = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name.to_string(),
// Default value, will be replaced by the result of decide_session_token_flow
api::GetToken::Connector,
merchant_connector_account_id.clone(),
);
let connector_type = decide_session_token_flow(
&connector_data_result?.connector,
payment_method_type,
connector_name.clone(),
);
logger::debug!(session_token_flow=?connector_type, "Session token flow decided for payment method type: {:?}", payment_method_type);
api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name.to_string(),
connector_type,
merchant_connector_account_id,
)
.inspect_err(|err| {
logger::error!(session_token_error=?err);
})
}
/// Decides the session token flow based on payment method type
pub fn decide_session_token_flow(
connector: &hyperswitch_interfaces::connector_integration_interface::ConnectorEnum,
payment_method_type: api_models::enums::PaymentMethodType,
connector_name: String,
) -> api::GetToken {
if connector.validate_sdk_session_token_for_payment_method(&payment_method_type) {
logger::debug!(
"SDK session token validation succeeded for payment_method_type {:?} in connector {} , proceeding with Connector token flow",
payment_method_type, connector_name
);
return api::GetToken::Connector;
}
match payment_method_type {
api_models::enums::PaymentMethodType::ApplePay => api::GetToken::ApplePayMetadata,
api_models::enums::PaymentMethodType::GooglePay => api::GetToken::GpayMetadata,
api_models::enums::PaymentMethodType::Paypal => api::GetToken::PaypalSdkMetadata,
api_models::enums::PaymentMethodType::SamsungPay => api::GetToken::SamsungPayMetadata,
api_models::enums::PaymentMethodType::Paze => api::GetToken::PazeMetadata,
_ => api::GetToken::Connector,
}
}
// This function validates the intent fulfillment time expiry set by the merchant in the request
pub fn validate_intent_fulfillment_expiry(
intent_fulfillment_time: u32,
) -> Result<(), errors::ApiErrorResponse> {
if !(consts::MIN_INTENT_FULFILLMENT_EXPIRY..=consts::MAX_INTENT_FULFILLMENT_EXPIRY)
.contains(&intent_fulfillment_time)
{
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "intent_fulfillment_time should be between 60(1 min) to 1800(30 mins)."
.to_string(),
})
} else {
Ok(())
}
}
pub fn add_connector_response_to_additional_payment_data(
additional_payment_data: api_models::payments::AdditionalPaymentData,
connector_response_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> api_models::payments::AdditionalPaymentData {
match (
&additional_payment_data,
connector_response_payment_method_data,
) {
(
api_models::payments::AdditionalPaymentData::Card(additional_card_data),
AdditionalPaymentMethodConnectorResponse::Card {
authentication_data,
payment_checks,
..
},
) => api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
payment_checks,
authentication_data,
..*additional_card_data.clone()
},
)),
(
api_models::payments::AdditionalPaymentData::PayLater { .. },
AdditionalPaymentMethodConnectorResponse::PayLater {
klarna_sdk: Some(KlarnaSdkResponse { payment_type }),
},
) => api_models::payments::AdditionalPaymentData::PayLater {
klarna_sdk: Some(api_models::payments::KlarnaSdkPaymentMethod { payment_type }),
},
_ => additional_payment_data,
}
}
pub fn update_additional_payment_data_with_connector_response_pm_data(
additional_payment_data: Option<serde_json::Value>,
connector_response_pm_data: Option<AdditionalPaymentMethodConnectorResponse>,
) -> RouterResult<Option<serde_json::Value>> {
let parsed_additional_payment_method_data = additional_payment_data
.as_ref()
.map(|payment_method_data| {
payment_method_data
.clone()
.parse_value::<api_models::payments::AdditionalPaymentData>(
"additional_payment_method_data",
)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse value into additional_payment_method_data")?;
let additional_payment_method_data = parsed_additional_payment_method_data
.zip(connector_response_pm_data)
.map(|(additional_pm_data, connector_response_pm_data)| {
add_connector_response_to_additional_payment_data(
additional_pm_data,
connector_response_pm_data,
)
});
additional_payment_method_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")
}
#[cfg(feature = "v2")]
pub async fn get_payment_method_details_from_payment_token(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn get_payment_method_details_from_payment_token(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {
let hyperswitch_token = if let Some(token) = payment_attempt.payment_token.clone() {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!(
"pm_token_{}_{}_hyperswitch",
token,
payment_attempt
.payment_method
.to_owned()
.get_required_value("payment_method")?,
);
let token_data_string = redis_conn
.get_key::<Option<String>>(&key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?
.ok_or(error_stack::Report::new(
errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".to_owned(),
},
))?;
let token_data_result = token_data_string
.clone()
.parse_struct("PaymentTokenData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to deserialize hyperswitch token data");
let token_data = match token_data_result {
Ok(data) => data,
Err(e) => {
// The purpose of this logic is backwards compatibility to support tokens
// in redis that might be following the old format.
if token_data_string.starts_with('{') {
return Err(e);
} else {
storage::PaymentTokenData::temporary_generic(token_data_string)
}
}
};
Some(token_data)
} else {
None
};
let token = hyperswitch_token
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing hyperswitch_token")?;
match token {
storage::PaymentTokenData::TemporaryGeneric(generic_token) => {
retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
payment_attempt,
key_store,
None,
)
.await
}
storage::PaymentTokenData::Temporary(generic_token) => {
retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
payment_attempt,
key_store,
None,
)
.await
}
storage::PaymentTokenData::Permanent(card_token) => {
retrieve_card_with_permanent_token_for_external_authentication(
state,
&card_token.token,
payment_intent,
None,
key_store,
storage_scheme,
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))
}
storage::PaymentTokenData::PermanentCard(card_token) => {
retrieve_card_with_permanent_token_for_external_authentication(
state,
&card_token.token,
payment_intent,
None,
key_store,
storage_scheme,
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))
}
storage::PaymentTokenData::AuthBankDebit(auth_token) => {
retrieve_payment_method_from_auth_service(
state,
key_store,
&auth_token,
payment_intent,
&None,
)
.await
}
storage::PaymentTokenData::WalletToken(_) => Ok(None),
}
}
// This function validates the mandate_data with its setup_future_usage
pub fn validate_mandate_data_and_future_usage(
setup_future_usages: Option<api_enums::FutureUsage>,
mandate_details_present: bool,
) -> Result<(), errors::ApiErrorResponse> {
if mandate_details_present
&& (Some(api_enums::FutureUsage::OnSession) == setup_future_usages
|| setup_future_usages.is_none())
{
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "`setup_future_usage` must be `off_session` for mandates".into(),
})
} else {
Ok(())
}
}
#[derive(Debug, Clone)]
pub enum UnifiedAuthenticationServiceFlow {
ClickToPayInitiate,
ExternalAuthenticationInitiate {
acquirer_details: Option<authentication::types::AcquirerDetails>,
card: Box<hyperswitch_domain_models::payment_method_data::Card>,
token: String,
},
ExternalAuthenticationPostAuthenticate {
authentication_id: id_type::AuthenticationId,
},
}
#[cfg(feature = "v1")]
pub async fn decide_action_for_unified_authentication_service<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
payment_data: &mut PaymentData<F>,
connector_call_type: &api::ConnectorCallType,
mandate_type: Option<api_models::payments::MandateTransactionType>,
) -> RouterResult<Option<UnifiedAuthenticationServiceFlow>> {
let external_authentication_flow = get_payment_external_authentication_flow_during_confirm(
state,
key_store,
business_profile,
payment_data,
connector_call_type,
mandate_type,
)
.await?;
Ok(match external_authentication_flow {
Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow {
acquirer_details,
card,
token,
}) => Some(
UnifiedAuthenticationServiceFlow::ExternalAuthenticationInitiate {
acquirer_details,
card,
token,
},
),
Some(PaymentExternalAuthenticationFlow::PostAuthenticationFlow { authentication_id }) => {
Some(
UnifiedAuthenticationServiceFlow::ExternalAuthenticationPostAuthenticate {
authentication_id,
},
)
}
None => {
if let Some(payment_method) = payment_data.payment_attempt.payment_method {
if payment_method == storage_enums::PaymentMethod::Card
&& business_profile.is_click_to_pay_enabled
&& payment_data.service_details.is_some()
{
Some(UnifiedAuthenticationServiceFlow::ClickToPayInitiate)
} else {
None
}
} else {
logger::info!(
payment_method=?payment_data.payment_attempt.payment_method,
click_to_pay_enabled=?business_profile.is_click_to_pay_enabled,
"skipping unified authentication service call since payment conditions are not satisfied"
);
None
}
}
})
}
pub enum PaymentExternalAuthenticationFlow {
PreAuthenticationFlow {
acquirer_details: Option<authentication::types::AcquirerDetails>,
card: Box<hyperswitch_domain_models::payment_method_data::Card>,
token: String,
},
PostAuthenticationFlow {
authentication_id: id_type::AuthenticationId,
},
}
#[cfg(feature = "v1")]
pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
payment_data: &mut PaymentData<F>,
connector_call_type: &api::ConnectorCallType,
mandate_type: Option<api_models::payments::MandateTransactionType>,
) -> RouterResult<Option<PaymentExternalAuthenticationFlow>> {
let authentication_id = payment_data.payment_attempt.authentication_id.clone();
let is_authentication_type_3ds = payment_data.payment_attempt.authentication_type
== Some(common_enums::AuthenticationType::ThreeDs);
let separate_authentication_requested = payment_data
.payment_intent
.request_external_three_ds_authentication
.unwrap_or(false);
let separate_three_ds_authentication_attempted = payment_data
.payment_attempt
.external_three_ds_authentication_attempted
.unwrap_or(false);
let connector_supports_separate_authn =
authentication::utils::get_connector_data_if_separate_authn_supported(connector_call_type);
logger::info!("is_pre_authn_call {:?}", authentication_id.is_none());
logger::info!(
"separate_authentication_requested {:?}",
separate_authentication_requested
);
logger::info!(
"payment connector supports external authentication: {:?}",
connector_supports_separate_authn.is_some()
);
let card = payment_data.payment_method_data.as_ref().and_then(|pmd| {
if let domain::PaymentMethodData::Card(card) = pmd {
Some(card.clone())
} else {
None
}
});
Ok(if separate_three_ds_authentication_attempted {
authentication_id.map(|authentication_id| {
PaymentExternalAuthenticationFlow::PostAuthenticationFlow { authentication_id }
})
} else if separate_authentication_requested
&& is_authentication_type_3ds
&& mandate_type
!= Some(api_models::payments::MandateTransactionType::RecurringMandateTransaction)
{
if let Some((connector_data, card)) = connector_supports_separate_authn.zip(card) {
let token = payment_data
.token
.clone()
.get_required_value("token")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"payment_data.token should not be None while making pre authentication call",
)?;
let payment_connector_mca = get_merchant_connector_account(
state,
&business_profile.merchant_id,
None,
key_store,
business_profile.get_id(),
connector_data.connector_name.to_string().as_str(),
connector_data.merchant_connector_id.as_ref(),
)
.await?;
let acquirer_details = payment_connector_mca
.get_metadata()
.clone()
.and_then(|metadata| {
metadata
.peek()
.clone()
.parse_value::<authentication::types::AcquirerDetails>("AcquirerDetails")
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message:
"acquirer_bin and acquirer_merchant_id not found in Payment Connector's Metadata"
.to_string(),
})
.inspect_err(|err| {
logger::error!(
"Failed to parse acquirer details from Payment Connector's Metadata: {:?}",
err
);
})
.ok()
});
Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow {
card: Box::new(card),
token,
acquirer_details,
})
} else {
None
}
} else {
None
})
}
pub fn get_redis_key_for_extended_card_info(
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
) -> String {
format!(
"{}_{}_extended_card_info",
merchant_id.get_string_repr(),
payment_id.get_string_repr()
)
}
pub fn check_integrity_based_on_flow<T, Request>(
request: &Request,
payment_response_data: &Result<PaymentsResponseData, ErrorResponse>,
) -> Result<(), common_utils::errors::IntegrityCheckError>
where
T: FlowIntegrity,
Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>,
{
let connector_transaction_id = match payment_response_data {
Ok(resp_data) => match resp_data {
PaymentsResponseData::TransactionResponse {
connector_response_reference_id,
..
} => connector_response_reference_id,
PaymentsResponseData::TransactionUnresolvedResponse {
connector_response_reference_id,
..
} => connector_response_reference_id,
PaymentsResponseData::PreProcessingResponse {
connector_response_reference_id,
..
} => connector_response_reference_id,
_ => &None,
},
Err(_) => &None,
};
request.check_integrity(request, connector_transaction_id.to_owned())
}
pub async fn config_skip_saving_wallet_at_connector(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
) -> CustomResult<Option<Vec<storage_enums::PaymentMethodType>>, errors::ApiErrorResponse> {
let config = db
.find_config_by_key_unwrap_or(
&merchant_id.get_skip_saving_wallet_at_connector_key(),
Some("[]".to_string()),
)
.await;
Ok(match config {
Ok(conf) => Some(
serde_json::from_str::<Vec<storage_enums::PaymentMethodType>>(&conf.config)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("skip_save_wallet_at_connector config parsing failed")?,
),
Err(error) => {
logger::error!(?error);
None
}
})
}
#[cfg(feature = "v1")]
pub async fn override_setup_future_usage_to_on_session<F, D>(
db: &dyn StorageInterface,
payment_data: &mut D,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send,
{
if payment_data.get_payment_intent().setup_future_usage == Some(enums::FutureUsage::OffSession)
{
let skip_saving_wallet_at_connector_optional = config_skip_saving_wallet_at_connector(
db,
&payment_data.get_payment_intent().merchant_id,
)
.await?;
if let Some(skip_saving_wallet_at_connector) = skip_saving_wallet_at_connector_optional {
if let Some(payment_method_type) =
payment_data.get_payment_attempt().get_payment_method_type()
{
if skip_saving_wallet_at_connector.contains(&payment_method_type) {
logger::debug!("Override setup_future_usage from off_session to on_session based on the merchant's skip_saving_wallet_at_connector configuration to avoid creating a connector mandate.");
payment_data
.set_setup_future_usage_in_payment_intent(enums::FutureUsage::OnSession);
}
}
};
};
Ok(())
}
pub async fn validate_routing_id_with_profile_id(
db: &dyn StorageInterface,
routing_id: &id_type::RoutingId,
profile_id: &id_type::ProfileId,
) -> CustomResult<(), errors::ApiErrorResponse> {
let _routing_id = db
.find_routing_algorithm_metadata_by_algorithm_id_profile_id(routing_id, profile_id)
.await
.map_err(|err| {
if err.current_context().is_db_not_found() {
logger::warn!(
"Routing id not found for routing id - {:?} and profile id - {:?}",
routing_id,
profile_id
);
err.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "routing_algorithm_id".to_string(),
expected_format: "A valid routing_id that belongs to the business_profile"
.to_string(),
})
} else {
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to validate routing id")
}
})?;
Ok(())
}
#[cfg(feature = "v1")]
pub async fn validate_merchant_connector_ids_in_connector_mandate_details(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: &api_models::payment_methods::CommonMandateReference,
merchant_id: &id_type::MerchantId,
card_network: Option<api_enums::CardNetwork>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let db = &*state.store;
let merchant_connector_account_list = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_id,
true,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let merchant_connector_account_details_hash_map: std::collections::HashMap<
id_type::MerchantConnectorAccountId,
domain::MerchantConnectorAccount,
> = merchant_connector_account_list
.iter()
.map(|merchant_connector_account| {
(
merchant_connector_account.get_id(),
merchant_connector_account.clone(),
)
})
.collect();
if let Some(payment_mandate_reference) = &connector_mandate_details.payments {
let payments_map = payment_mandate_reference.0.clone();
for (migrating_merchant_connector_id, migrating_connector_mandate_details) in payments_map {
match (
card_network.clone(),
merchant_connector_account_details_hash_map.get(&migrating_merchant_connector_id),
) {
(Some(enums::CardNetwork::Discover), Some(merchant_connector_account_details)) => {
if let ("cybersource", None) = (
merchant_connector_account_details.connector_name.as_str(),
migrating_connector_mandate_details
.original_payment_authorized_amount
.zip(
migrating_connector_mandate_details
.original_payment_authorized_currency,
),
) {
Err(errors::ApiErrorResponse::MissingRequiredFields {
field_names: vec![
"original_payment_authorized_currency",
"original_payment_authorized_amount",
],
})
.attach_printable(format!(
"Invalid connector_mandate_details provided for connector {migrating_merchant_connector_id:?}",
))?
}
}
(_, Some(_)) => (),
(_, None) => Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "merchant_connector_id",
})
.attach_printable_lazy(|| {
format!(
"{migrating_merchant_connector_id:?} invalid merchant connector id in connector_mandate_details",
)
})?,
}
}
} else {
router_env::logger::error!("payment mandate reference not found");
}
Ok(())
}
pub fn validate_platform_request_for_marketplace(
amount: api::Amount,
split_payments: Option<common_types::payments::SplitPaymentsRequest>,
) -> Result<(), errors::ApiErrorResponse> {
match split_payments {
Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) => match amount {
api::Amount::Zero => {
if stripe_split_payment
.application_fees
.as_ref()
.map_or(MinorUnit::zero(), |amount| *amount)
!= MinorUnit::zero()
{
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "split_payments.stripe_split_payment.application_fees",
});
}
}
api::Amount::Value(amount) => {
if stripe_split_payment
.application_fees
.as_ref()
.map_or(MinorUnit::zero(), |amount| *amount)
> amount.into()
{
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "split_payments.stripe_split_payment.application_fees",
});
}
}
},
Some(common_types::payments::SplitPaymentsRequest::AdyenSplitPayment(
adyen_split_payment,
)) => {
let total_split_amount: i64 = adyen_split_payment
.split_items
.iter()
.map(|split_item| {
split_item
.amount
.unwrap_or(MinorUnit::new(0))
.get_amount_as_i64()
})
.sum();
match amount {
api::Amount::Zero => {
if total_split_amount != 0 {
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "Sum of split amounts should be equal to the total amount",
});
}
}
api::Amount::Value(amount) => {
let i64_amount: i64 = amount.into();
if !adyen_split_payment.split_items.is_empty()
&& i64_amount != total_split_amount
{
return Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Sum of split amounts should be equal to the total amount"
.to_string(),
});
}
}
};
adyen_split_payment
.split_items
.iter()
.try_for_each(|split_item| {
match split_item.split_type {
common_enums::AdyenSplitType::BalanceAccount => {
if split_item.account.is_none() {
return Err(errors::ApiErrorResponse::MissingRequiredField {
field_name:
"split_payments.adyen_split_payment.split_items.account",
});
}
}
common_enums::AdyenSplitType::Commission
| enums::AdyenSplitType::Vat
| enums::AdyenSplitType::TopUp => {
if split_item.amount.is_none() {
return Err(errors::ApiErrorResponse::MissingRequiredField {
field_name:
"split_payments.adyen_split_payment.split_items.amount",
});
}
if let enums::AdyenSplitType::TopUp = split_item.split_type {
if split_item.account.is_none() {
return Err(errors::ApiErrorResponse::MissingRequiredField {
field_name:
"split_payments.adyen_split_payment.split_items.account",
});
}
if adyen_split_payment.store.is_some() {
return Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Topup split payment is not available via Adyen Platform"
.to_string(),
});
}
}
}
enums::AdyenSplitType::AcquiringFees
| enums::AdyenSplitType::PaymentFee
| enums::AdyenSplitType::AdyenFees
| enums::AdyenSplitType::AdyenCommission
| enums::AdyenSplitType::AdyenMarkup
| enums::AdyenSplitType::Interchange
| enums::AdyenSplitType::SchemeFee => {}
};
Ok(())
})?;
}
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
xendit_split_payment,
)) => match xendit_split_payment {
common_types::payments::XenditSplitRequest::MultipleSplits(
xendit_multiple_split_payment,
) => {
match amount {
api::Amount::Zero => {
let total_split_amount: i64 = xendit_multiple_split_payment
.routes
.iter()
.map(|route| {
route
.flat_amount
.unwrap_or(MinorUnit::new(0))
.get_amount_as_i64()
})
.sum();
if total_split_amount != 0 {
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name:
"Sum of split amounts should be equal to the total amount",
});
}
}
api::Amount::Value(amount) => {
let total_payment_amount: i64 = amount.into();
let total_split_amount: i64 = xendit_multiple_split_payment
.routes
.into_iter()
.map(|route| {
if route.flat_amount.is_none() && route.percent_amount.is_none() {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Expected either split_payments.xendit_split_payment.routes.flat_amount or split_payments.xendit_split_payment.routes.percent_amount to be provided".to_string(),
})
} else if route.flat_amount.is_some() && route.percent_amount.is_some(){
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Expected either split_payments.xendit_split_payment.routes.flat_amount or split_payments.xendit_split_payment.routes.percent_amount, but not both".to_string(),
})
} else {
Ok(route
.flat_amount
.map(|amount| amount.get_amount_as_i64())
.or(route.percent_amount.map(|percentage| (percentage * total_payment_amount) / 100))
.unwrap_or(0))
}
})
.collect::<Result<Vec<i64>, _>>()?
.into_iter()
.sum();
if total_payment_amount < total_split_amount {
return Err(errors::ApiErrorResponse::PreconditionFailed {
message:
"The sum of split amounts should not exceed the total amount"
.to_string(),
});
}
}
};
}
common_types::payments::XenditSplitRequest::SingleSplit(_) => (),
},
None => (),
}
Ok(())
}
pub async fn is_merchant_eligible_authentication_service(
merchant_id: &id_type::MerchantId,
state: &SessionState,
) -> RouterResult<bool> {
let merchants_eligible_for_authentication_service = state
.store
.as_ref()
.find_config_by_key_unwrap_or(
consts::AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG,
Some("[]".to_string()),
)
.await;
let auth_eligible_array: Vec<String> = match merchants_eligible_for_authentication_service {
Ok(config) => serde_json::from_str(&config.config)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse authentication service config")?,
Err(err) => {
logger::error!(
"Error fetching authentication service enabled merchant config {:?}",
err
);
Vec::new()
}
};
Ok(auth_eligible_array.contains(&merchant_id.get_string_repr().to_owned()))
}
#[cfg(feature = "v1")]
pub async fn validate_allowed_payment_method_types_request(
state: &SessionState,
profile_id: &id_type::ProfileId,
merchant_context: &domain::MerchantContext,
allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>,
) -> CustomResult<(), errors::ApiErrorResponse> {
if let Some(allowed_payment_method_types) = allowed_payment_method_types {
let db = &*state.store;
let all_connector_accounts = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_context.get_merchant_account().get_id(),
false,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch merchant connector account for given merchant id")?;
let filtered_connector_accounts = all_connector_accounts
.filter_based_on_profile_and_connector_type(
profile_id,
ConnectorType::PaymentProcessor,
);
let supporting_payment_method_types: HashSet<_> = filtered_connector_accounts
.iter()
.flat_map(|connector_account| {
connector_account
.payment_methods_enabled
.clone()
.unwrap_or_default()
.into_iter()
.map(|payment_methods_enabled| {
payment_methods_enabled
.parse_value::<api_models::admin::PaymentMethodsEnabled>(
"payment_methods_enabled",
)
})
.filter_map(|parsed_payment_method_result| {
parsed_payment_method_result
.inspect_err(|err| {
logger::error!(
"Unable to deserialize payment methods enabled: {:?}",
err
);
})
.ok()
})
.flat_map(|parsed_payment_methods_enabled| {
parsed_payment_methods_enabled
.payment_method_types
.unwrap_or_default()
.into_iter()
.map(|payment_method_type| payment_method_type.payment_method_type)
})
})
.collect();
let unsupported_payment_methods: Vec<_> = allowed_payment_method_types
.iter()
.filter(|allowed_pmt| !supporting_payment_method_types.contains(allowed_pmt))
.collect();
if !unsupported_payment_methods.is_empty() {
metrics::PAYMENT_METHOD_TYPES_MISCONFIGURATION_METRIC.add(
1,
router_env::metric_attributes!((
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
)),
);
}
fp_utils::when(
unsupported_payment_methods.len() == allowed_payment_method_types.len(),
|| {
Err(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable(format!(
"None of the allowed payment method types {allowed_payment_method_types:?} are configured for this merchant connector account.",
))
},
)?;
}
Ok(())
}
async fn get_payment_update_enabled_for_client_auth(
merchant_id: &id_type::MerchantId,
state: &SessionState,
) -> bool {
let key = merchant_id.get_payment_update_enabled_for_client_auth_key();
let db = &*state.store;
let update_enabled = db.find_config_by_key(key.as_str()).await;
match update_enabled {
Ok(conf) => conf.config.to_lowercase() == "true",
Err(error) => {
logger::error!(?error);
false
}
}
}
pub async fn allow_payment_update_enabled_for_client_auth(
merchant_id: &id_type::MerchantId,
state: &SessionState,
auth_flow: services::AuthFlow,
) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
match auth_flow {
services::AuthFlow::Client => {
if get_payment_update_enabled_for_client_auth(merchant_id, state).await {
Ok(())
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Client auth for payment update is not enabled.")
}
}
services::AuthFlow::Merchant => Ok(()),
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn get_merchant_connector_account_v2(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,
) -> RouterResult<domain::MerchantConnectorAccount> {
let db = &*state.store;
match merchant_connector_id {
Some(merchant_connector_id) => db
.find_merchant_connector_account_by_id(&state.into(), merchant_connector_id, key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
}),
None => Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_connector_id",
})
.attach_printable("merchant_connector_id is not provided"),
}
}
pub fn is_stored_credential(
recurring_details: &Option<RecurringDetails>,
payment_token: &Option<String>,
is_mandate: bool,
is_stored_credential_prev: Option<bool>,
) -> Option<bool> {
if is_stored_credential_prev == Some(true)
|| recurring_details.is_some()
|| payment_token.is_some()
|| is_mandate
{
Some(true)
} else {
is_stored_credential_prev
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
// Helper function to process through UCS gateway
pub async fn process_through_ucs<'a, F, RouterDReq, ApiRequest, D>(
state: &'a SessionState,
req_state: routes::app::ReqState,
merchant_context: &'a domain::MerchantContext,
operation: &'a BoxedOperation<'a, F, ApiRequest, D>,
payment_data: &'a mut D,
customer: &Option<domain::Customer>,
validate_result: &'a OperationsValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: domain_payments::HeaderPayload,
frm_suggestion: Option<enums::FrmSuggestion>,
business_profile: &'a domain::Profile,
merchant_connector_account: MerchantConnectorAccountType,
mut router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
) -> RouterResult<(
RouterData<F, RouterDReq, PaymentsResponseData>,
MerchantConnectorAccountType,
)>
where
F: Send + Clone + Sync + 'static,
RouterDReq: Send + Sync + Clone + 'static + Serialize,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>,
RouterData<F, RouterDReq, PaymentsResponseData>:
Feature<F, RouterDReq> + Send + Clone + Serialize,
dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>,
{
router_env::logger::info!(
"Processing payment through UCS gateway system - payment_id={}, attempt_id={}",
payment_data
.get_payment_intent()
.payment_id
.get_string_repr(),
payment_data.get_payment_attempt().attempt_id
);
// Add task to process tracker if needed
if should_add_task_to_process_tracker(payment_data) {
operation
.to_domain()?
.add_task_to_process_tracker(
state,
payment_data.get_payment_attempt(),
validate_result.requeue,
schedule_time,
)
.await
.map_err(|error| router_env::logger::error!(process_tracker_error=?error))
.ok();
}
// Update feature metadata to track UCS usage for stickiness
update_gateway_system_in_feature_metadata(
payment_data,
GatewaySystem::UnifiedConnectorService,
)?;
// Update trackers
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
frm_suggestion,
header_payload.clone(),
)
.await?;
// Call UCS
let lineage_ids = grpc_client::LineageIds::new(
business_profile.merchant_id.clone(),
business_profile.get_id().clone(),
);
router_data
.call_unified_connector_service(
state,
&header_payload,
lineage_ids,
merchant_connector_account.clone(),
merchant_context,
ExecutionMode::Primary, // UCS is called in primary mode
)
.await?;
Ok((router_data, merchant_connector_account))
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
// Helper function to process through Direct gateway
pub async fn process_through_direct<'a, F, RouterDReq, ApiRequest, D>(
state: &'a SessionState,
req_state: routes::app::ReqState,
merchant_context: &'a domain::MerchantContext,
connector: api::ConnectorData,
operation: &'a BoxedOperation<'a, F, ApiRequest, D>,
payment_data: &'a mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
validate_result: &'a OperationsValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: domain_payments::HeaderPayload,
frm_suggestion: Option<enums::FrmSuggestion>,
business_profile: &'a domain::Profile,
is_retry_payment: bool,
all_keys_required: Option<bool>,
merchant_connector_account: MerchantConnectorAccountType,
router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
tokenization_action: TokenizationAction,
) -> RouterResult<(
RouterData<F, RouterDReq, PaymentsResponseData>,
MerchantConnectorAccountType,
)>
where
F: Send + Clone + Sync + 'static,
RouterDReq: Send + Sync + Clone + 'static + Serialize,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>,
RouterData<F, RouterDReq, PaymentsResponseData>:
Feature<F, RouterDReq> + Send + Clone + Serialize,
dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>,
{
router_env::logger::info!(
"Processing payment through Direct gateway system - payment_id={}, attempt_id={}",
payment_data
.get_payment_intent()
.payment_id
.get_string_repr(),
payment_data.get_payment_attempt().attempt_id
);
// Update feature metadata to track Direct routing usage for stickiness
update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?;
call_connector_service(
state,
req_state,
merchant_context,
connector,
operation,
payment_data,
customer,
call_connector_action,
validate_result,
schedule_time,
header_payload,
frm_suggestion,
business_profile,
is_retry_payment,
all_keys_required,
merchant_connector_account,
router_data,
tokenization_action,
)
.await
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
// Helper function to process through Direct with Shadow UCS
pub async fn process_through_direct_with_shadow_unified_connector_service<
'a,
F,
RouterDReq,
ApiRequest,
D,
>(
state: &'a SessionState,
req_state: routes::app::ReqState,
merchant_context: &'a domain::MerchantContext,
connector: api::ConnectorData,
operation: &'a BoxedOperation<'a, F, ApiRequest, D>,
payment_data: &'a mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
validate_result: &'a OperationsValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: domain_payments::HeaderPayload,
frm_suggestion: Option<enums::FrmSuggestion>,
business_profile: &'a domain::Profile,
is_retry_payment: bool,
all_keys_required: Option<bool>,
merchant_connector_account: MerchantConnectorAccountType,
router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
tokenization_action: TokenizationAction,
) -> RouterResult<(
RouterData<F, RouterDReq, PaymentsResponseData>,
MerchantConnectorAccountType,
)>
where
F: Send + Clone + Sync + 'static,
RouterDReq: Send + Sync + Clone + 'static + Serialize,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>,
RouterData<F, RouterDReq, PaymentsResponseData>:
Feature<F, RouterDReq> + Send + Clone + Serialize,
dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>,
{
router_env::logger::info!(
"Processing payment through Direct gateway system with UCS in shadow mode - payment_id={}, attempt_id={}",
payment_data.get_payment_intent().payment_id.get_string_repr(),
payment_data.get_payment_attempt().attempt_id
);
// Clone data needed for shadow UCS call
let unified_connector_service_router_data = router_data.clone();
let unified_connector_service_merchant_connector_account = merchant_connector_account.clone();
let unified_connector_service_merchant_context = merchant_context.clone();
let unified_connector_service_header_payload = header_payload.clone();
let unified_connector_service_state = state.clone();
let lineage_ids = grpc_client::LineageIds::new(
business_profile.merchant_id.clone(),
business_profile.get_id().clone(),
);
// Update feature metadata to track Direct routing usage for stickiness
update_gateway_system_in_feature_metadata(payment_data, GatewaySystem::Direct)?;
// Call Direct connector service
let result = call_connector_service(
state,
req_state,
merchant_context,
connector,
operation,
payment_data,
customer,
call_connector_action,
validate_result,
schedule_time,
header_payload,
frm_suggestion,
business_profile,
is_retry_payment,
all_keys_required,
merchant_connector_account,
router_data,
tokenization_action,
)
.await?;
// Spawn shadow UCS call in background
let direct_router_data = result.0.clone();
tokio::spawn(async move {
execute_shadow_unified_connector_service_call(
unified_connector_service_state,
unified_connector_service_router_data,
direct_router_data,
unified_connector_service_header_payload,
lineage_ids,
unified_connector_service_merchant_connector_account,
unified_connector_service_merchant_context,
)
.await
});
Ok(result)
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
// Helper function to execute shadow UCS call
pub async fn execute_shadow_unified_connector_service_call<F, RouterDReq>(
state: SessionState,
mut unified_connector_service_router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
direct_router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
header_payload: domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
merchant_connector_account: MerchantConnectorAccountType,
merchant_context: domain::MerchantContext,
) where
F: Send + Clone + Sync + 'static,
RouterDReq: Send + Sync + Clone + 'static + Serialize,
RouterData<F, RouterDReq, PaymentsResponseData>:
Feature<F, RouterDReq> + Send + Clone + Serialize,
dyn api::Connector: services::api::ConnectorIntegration<F, RouterDReq, PaymentsResponseData>,
{
// Call UCS in shadow mode
let _unified_connector_service_result = unified_connector_service_router_data
.call_unified_connector_service(
&state,
&header_payload,
lineage_ids,
merchant_connector_account,
&merchant_context,
ExecutionMode::Shadow, // Shadow mode for UCS
)
.await
.map_err(|e| router_env::logger::debug!("Shadow UCS call failed: {:?}", e));
// Compare results
match serialize_router_data_and_send_to_comparison_service(
&state,
direct_router_data,
unified_connector_service_router_data,
)
.await
{
Ok(_) => router_env::logger::debug!("Shadow UCS comparison completed successfully"),
Err(e) => router_env::logger::debug!("Shadow UCS comparison failed: {:?}", e),
}
}
#[cfg(feature = "v1")]
pub async fn serialize_router_data_and_send_to_comparison_service<F, RouterDReq>(
state: &SessionState,
hyperswitch_router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
unified_connector_service_router_data: RouterData<F, RouterDReq, PaymentsResponseData>,
) -> RouterResult<()>
where
F: Send + Clone + Sync + 'static,
RouterDReq: Send + Sync + Clone + 'static + Serialize,
{
router_env::logger::info!("Simulating UCS call for shadow mode comparison");
let hyperswitch_data = match serde_json::to_value(hyperswitch_router_data) {
Ok(data) => masking::Secret::new(data),
Err(_) => {
router_env::logger::debug!("Failed to serialize HS router data");
return Ok(());
}
};
let unified_connector_service_data =
match serde_json::to_value(unified_connector_service_router_data) {
Ok(data) => masking::Secret::new(data),
Err(_) => {
router_env::logger::debug!("Failed to serialize UCS router data");
return Ok(());
}
};
let comparison_data = ComparisonData {
hyperswitch_data,
unified_connector_service_data,
};
let _ = send_comparison_data(state, comparison_data)
.await
.map_err(|e| {
router_env::logger::debug!("Failed to send comparison data: {:?}", e);
});
Ok(())
}
| crates/router/src/core/payments/helpers.rs | router::src::core::payments::helpers | 63,677 | true |
// File: crates/router/src/core/payments/session_operation.rs
// Module: router::src::core::payments::session_operation
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,
merchant_context: domain::MerchantContext,
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,
merchant_context.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,
&merchant_context,
)
}
#[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,
merchant_context: domain::MerchantContext,
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, &merchant_context)?;
let operations::GetTrackerResponse { mut payment_data } = operation
.to_get_tracker()?
.get_trackers(
state,
&payment_id,
&req,
&merchant_context,
&profile,
&header_payload,
)
.await?;
let (_operation, customer) = operation
.to_domain()?
.get_customer_details(
state,
&mut payment_data,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_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,
&merchant_context,
&operation,
&profile,
&mut payment_data,
header_payload.clone(),
)
.await?;
let connector = operation
.to_domain()?
.perform_routing(
&merchant_context,
&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,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload.clone(),
)
.await?;
// todo: call surcharge manager for session token call.
Box::pin(call_multiple_connectors_service(
state,
&merchant_context,
connectors,
&operation,
payment_data,
&customer,
None,
&profile,
header_payload.clone(),
None,
))
.await?
}
};
Ok((payment_data, req, customer, None, None))
}
| crates/router/src/core/payments/session_operation.rs | router::src::core::payments::session_operation | 1,600 | true |
// File: crates/router/src/core/payments/customers.rs
// Module: router::src::core::payments::customers
pub use hyperswitch_domain_models::customer::update_connector_customer_in_customers;
use hyperswitch_interfaces::api::ConnectorSpecifications;
use router_env::{instrument, tracing};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
payments,
},
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,
) -> 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 = services::execute_connector_processing_step(
state,
connector_integration,
&customer_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.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");
}
}
}
| crates/router/src/core/payments/customers.rs | router::src::core::payments::customers | 944 | true |
// File: crates/router/src/core/payments/routing.rs
// Module: router::src::core::payments::routing
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,
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,
},
),
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 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,
},
),
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: None,
})
}
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 algorithm_id = if let Some(id) = algorithm_id {
id
} else {
let fallback_config = get_merchant_fallback_config().await?;
logger::debug!("euclid_routing: active algorithm isn't present, default falling back");
return Ok((fallback_config, None));
};
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
)
.await?;
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,
get_merchant_fallback_config().await?,
)
.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(),
prefix: state.tenant.redis_key_prefix.clone(),
},
)
.await;
let cgraph = if let Some(graph) = cached_cgraph {
graph
} else {
refresh_cgraph_cache(state, key_store, key.clone(), profile_id, transaction_type).await?
};
Ok(cgraph)
}
// #[cfg(feature = "v1")]
pub async fn refresh_cgraph_cache(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
key: String,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let mut merchant_connector_accounts = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
&key_store.merchant_id,
false,
key_store,
)
.await
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
match transaction_type {
api_enums::TransactionType::Payment => {
merchant_connector_accounts.retain(|mca| {
mca.connector_type != storage_enums::ConnectorType::PaymentVas
&& mca.connector_type != storage_enums::ConnectorType::PaymentMethodAuth
&& mca.connector_type != storage_enums::ConnectorType::PayoutProcessor
&& mca.connector_type != storage_enums::ConnectorType::AuthenticationProcessor
});
}
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
merchant_connector_accounts
.retain(|mca| mca.connector_type == storage_enums::ConnectorType::PayoutProcessor);
}
api_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
};
let connector_type = match transaction_type {
api_enums::TransactionType::Payment => common_enums::ConnectorType::PaymentProcessor,
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => common_enums::ConnectorType::PayoutProcessor,
api_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
};
let merchant_connector_accounts = merchant_connector_accounts
.filter_based_on_profile_and_connector_type(profile_id, connector_type);
let api_mcas = merchant_connector_accounts
.into_iter()
.map(admin_api::MerchantConnectorResponse::foreign_try_from)
.collect::<Result<Vec<_>, _>>()
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
let connector_configs = state
.conf
.pm_filters
.0
.clone()
.into_iter()
.filter(|(key, _)| key != "default")
.map(|(key, value)| {
let key = api_enums::RoutableConnectors::from_str(&key)
.map_err(|_| errors::RoutingError::InvalidConnectorName(key))?;
Ok((key, value.foreign_into()))
})
.collect::<Result<HashMap<_, _>, errors::RoutingError>>()?;
let default_configs = state
.conf
.pm_filters
.0
.get("default")
.cloned()
.map(ForeignFrom::foreign_from);
let config_pm_filters = CountryCurrencyFilter {
connector_configs,
default_configs,
};
let cgraph = Arc::new(
mca_graph::make_mca_graph(api_mcas, &config_pm_filters)
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)
.attach_printable("when construction cgraph")?,
);
CGRAPH_CACHE
.push(
CacheKey {
key,
prefix: state.tenant.redis_key_prefix.clone(),
},
Arc::clone(&cgraph),
)
.await;
Ok(cgraph)
}
#[allow(clippy::too_many_arguments)]
pub async fn perform_cgraph_filtering(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
backend_input: dsl_inputs::BackendInput,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let context = euclid_graph::AnalysisContext::from_dir_values(
backend_input
.into_context()
.change_context(errors::RoutingError::KgraphAnalysisError)?,
);
let cached_cgraph = get_merchant_cgraph(state, key_store, profile_id, transaction_type).await?;
let mut final_selection = Vec::<routing_types::RoutableConnectorChoice>::new();
for choice in chosen {
let routable_connector = choice.connector;
let euclid_choice: ast::ConnectorChoice = choice.clone().foreign_into();
let dir_val = euclid_choice
.into_dir_value()
.change_context(errors::RoutingError::KgraphAnalysisError)?;
let cgraph_eligible = cached_cgraph
.check_value_validity(
dir_val,
&context,
&mut hyperswitch_constraint_graph::Memoization::new(),
&mut hyperswitch_constraint_graph::CycleCheck::new(),
None,
)
.change_context(errors::RoutingError::KgraphAnalysisError)?;
let filter_eligible =
eligible_connectors.is_none_or(|list| list.contains(&routable_connector));
if cgraph_eligible && filter_eligible {
final_selection.push(choice);
}
}
Ok(final_selection)
}
pub async fn perform_eligibility_analysis(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
profile_id: &common_utils::id_type::ProfileId,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
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)?,
};
perform_cgraph_filtering(
state,
key_store,
chosen,
backend_input,
eligible_connectors,
profile_id,
&api_enums::TransactionType::from(transaction_data),
)
.await
}
pub async fn perform_fallback_routing(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
#[cfg(feature = "v1")]
let fallback_config = routing::helpers::get_merchant_default_config(
&*state.store,
match transaction_data {
routing::TransactionData::Payment(payment_data) => payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?
.get_string_repr(),
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => {
payout_data.payout_attempt.profile_id.get_string_repr()
}
},
&api_enums::TransactionType::from(transaction_data),
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
#[cfg(feature = "v2")]
let fallback_config = admin::ProfileWrapper::new(business_profile.clone())
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
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)?,
};
perform_cgraph_filtering(
state,
key_store,
fallback_config,
backend_input,
eligible_connectors,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
)
.await
}
pub async fn perform_eligibility_analysis_with_fallback(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
chosen: Vec<routing_types::RoutableConnectorChoice>,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
logger::debug!("euclid_routing: performing eligibility");
let mut final_selection = perform_eligibility_analysis(
state,
key_store,
chosen,
transaction_data,
eligible_connectors.as_ref(),
business_profile.get_id(),
)
.await?;
let fallback_selection = perform_fallback_routing(
state,
key_store,
transaction_data,
eligible_connectors.as_ref(),
business_profile,
)
.await;
final_selection.append(
&mut fallback_selection
.unwrap_or_default()
.iter()
.filter(|&routable_connector_choice| {
!final_selection.contains(routable_connector_choice)
})
.cloned()
.collect::<Vec<_>>(),
);
let final_selected_connectors = final_selection
.iter()
.map(|item| item.connector)
.collect::<Vec<_>>();
logger::debug!(final_selected_connectors_for_routing=?final_selected_connectors, "euclid_routing: List of final selected connectors for routing");
Ok(final_selection)
}
#[cfg(feature = "v2")]
pub async fn perform_session_flow_routing<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_input: SessionFlowRoutingInput<'_>,
business_profile: &domain::Profile,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>>
{
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
let profile_id = business_profile.get_id().clone();
let routing_algorithm =
MerchantAccountRoutingAlgorithm::V1(business_profile.routing_algorithm_id.clone());
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: session_input
.payment_intent
.amount_details
.calculate_net_amount(),
currency: session_input.payment_intent.amount_details.currency,
authentication_type: session_input.payment_intent.authentication_type,
card_bin: None,
capture_method: Option::<euclid_enums::CaptureMethod>::foreign_from(
session_input.payment_intent.capture_method,
),
// business_country not available in payment_intent anymore
business_country: None,
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
// business_label not available in payment_intent anymore
business_label: None,
setup_future_usage: Some(session_input.payment_intent.setup_future_usage),
};
let metadata = session_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);
let mut backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
for connector_data in session_input.chosen.iter() {
pm_type_map
.entry(connector_data.payment_method_sub_type)
.or_default()
.insert(
connector_data.connector.connector_name.to_string(),
connector_data.connector.get_token.clone(),
);
}
let mut result: FxHashMap<
api_enums::PaymentMethodType,
Vec<routing_types::SessionRoutingChoice>,
> = FxHashMap::default();
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();
backend_input.payment_method.payment_method = Some(euclid_pm);
backend_input.payment_method.payment_method_type = Some(euclid_pmt);
let session_pm_input = SessionRoutingPmTypeInput {
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
profile_id: &profile_id,
};
let routable_connector_choice_option = perform_session_routing_for_pm_type(
state,
key_store,
&session_pm_input,
transaction_type,
business_profile,
)
.await?;
if let Some(routable_connector_choice) = routable_connector_choice_option {
let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
for selection in routable_connector_choice {
let connector_name = selection.connector.to_string();
if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.clone().conf.connectors,
&connector_name,
get_token.clone(),
selection.merchant_connector_id,
)
.change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
session_routing_choice.push(routing_types::SessionRoutingChoice {
connector: connector_data,
payment_method_type: pm_type,
});
}
}
if !session_routing_choice.is_empty() {
result.insert(pm_type, session_routing_choice);
}
}
}
Ok(result)
}
#[cfg(feature = "v1")]
pub async fn perform_session_flow_routing(
session_input: SessionFlowRoutingInput<'_>,
business_profile: &domain::Profile,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<(
FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>,
Option<common_enums::RoutingApproach>,
)> {
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
let profile_id = session_input
.payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?;
let routing_algorithm: MerchantAccountRoutingAlgorithm = {
business_profile
.routing_algorithm
.clone()
.map(|val| val.parse_value("MerchantAccountRoutingAlgorithm"))
.transpose()
.change_context(errors::RoutingError::InvalidRoutingAlgorithmStructure)?
.unwrap_or_default()
};
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: session_input.payment_attempt.get_total_amount(),
currency: session_input
.payment_intent
.currency
.get_required_value("Currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: session_input.payment_attempt.authentication_type,
card_bin: None,
capture_method: session_input
.payment_attempt
.capture_method
.and_then(Option::<euclid_enums::CaptureMethod>::foreign_from),
business_country: session_input
.payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: session_input
.country
.map(storage_enums::Country::from_alpha2),
business_label: session_input.payment_intent.business_label.clone(),
setup_future_usage: session_input.payment_intent.setup_future_usage,
};
let metadata = session_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);
let mut backend_input = dsl_inputs::BackendInput {
metadata,
payment: payment_input,
payment_method: payment_method_input,
mandate: dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
};
for connector_data in session_input.chosen.iter() {
pm_type_map
.entry(connector_data.payment_method_sub_type)
.or_default()
.insert(
connector_data.connector.connector_name.to_string(),
connector_data.connector.get_token.clone(),
);
}
let mut result: FxHashMap<
api_enums::PaymentMethodType,
Vec<routing_types::SessionRoutingChoice>,
> = FxHashMap::default();
let mut final_routing_approach = None;
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
let euclid_pm: euclid_enums::PaymentMethod = euclid_pmt.into();
backend_input.payment_method.payment_method = Some(euclid_pm);
backend_input.payment_method.payment_method_type = Some(euclid_pmt);
let session_pm_input = SessionRoutingPmTypeInput {
state: session_input.state,
key_store: session_input.key_store,
attempt_id: session_input.payment_attempt.get_id(),
routing_algorithm: &routing_algorithm,
backend_input: backend_input.clone(),
allowed_connectors,
profile_id: &profile_id,
};
let (routable_connector_choice_option, routing_approach) =
perform_session_routing_for_pm_type(
&session_pm_input,
transaction_type,
business_profile,
)
.await?;
final_routing_approach = routing_approach;
if let Some(routable_connector_choice) = routable_connector_choice_option {
let mut session_routing_choice: Vec<routing_types::SessionRoutingChoice> = Vec::new();
for selection in routable_connector_choice {
let connector_name = selection.connector.to_string();
if let Some(get_token) = session_pm_input.allowed_connectors.get(&connector_name) {
let connector_data = api::ConnectorData::get_connector_by_name(
&session_pm_input.state.clone().conf.connectors,
&connector_name,
get_token.clone(),
selection.merchant_connector_id,
)
.change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
session_routing_choice.push(routing_types::SessionRoutingChoice {
connector: connector_data,
payment_method_type: pm_type,
});
}
}
if !session_routing_choice.is_empty() {
result.insert(pm_type, session_routing_choice);
}
}
}
Ok((result, final_routing_approach))
}
#[cfg(feature = "v1")]
async fn perform_session_routing_for_pm_type(
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
_business_profile: &domain::Profile,
) -> RoutingResult<(
Option<Vec<api_models::routing::RoutableConnectorChoice>>,
Option<common_enums::RoutingApproach>,
)> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let algorithm_id = match session_pm_input.routing_algorithm {
MerchantAccountRoutingAlgorithm::V1(algorithm_ref) => &algorithm_ref.algorithm_id,
};
let (chosen_connectors, routing_approach) = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
&session_pm_input.state.clone(),
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
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(
session_pm_input.backend_input.clone(),
interpreter,
)?,
Some(common_enums::RoutingApproach::RuleBasedRouting),
),
}
} else {
(
routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?,
None,
)
};
let mut final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.key_store,
chosen_connectors,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
if final_selection.is_empty() {
let fallback = routing::helpers::get_merchant_default_config(
&*session_pm_input.state.clone().store,
session_pm_input.profile_id.get_string_repr(),
transaction_type,
)
.await
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
&session_pm_input.state.clone(),
session_pm_input.key_store,
fallback,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
}
if final_selection.is_empty() {
Ok((None, routing_approach))
} else {
Ok((Some(final_selection), routing_approach))
}
}
#[cfg(feature = "v2")]
async fn get_chosen_connectors<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
profile_wrapper: &admin::ProfileWrapper,
) -> RoutingResult<Vec<api_models::routing::RoutableConnectorChoice>> {
let merchant_id = &key_store.merchant_id;
let MerchantAccountRoutingAlgorithm::V1(algorithm_id) = session_pm_input.routing_algorithm;
let chosen_connectors = if let Some(ref algorithm_id) = algorithm_id {
let cached_algorithm = ensure_algorithm_cached_v1(
state,
merchant_id,
algorithm_id,
session_pm_input.profile_id,
transaction_type,
)
.await?;
match cached_algorithm.as_ref() {
CachedAlgorithm::Single(conn) => vec![(**conn).clone()],
CachedAlgorithm::Priority(plist) => plist.clone(),
CachedAlgorithm::VolumeSplit(splits) => perform_volume_split(splits.to_vec())
.change_context(errors::RoutingError::ConnectorSelectionFailed)?,
CachedAlgorithm::Advanced(interpreter) => execute_dsl_and_get_connector_v1(
session_pm_input.backend_input.clone(),
interpreter,
)?,
}
} else {
profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?
};
Ok(chosen_connectors)
}
#[cfg(feature = "v2")]
async fn perform_session_routing_for_pm_type<'a>(
state: &'a SessionState,
key_store: &'a domain::MerchantKeyStore,
session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
business_profile: &domain::Profile,
) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let profile_wrapper = admin::ProfileWrapper::new(business_profile.clone());
let chosen_connectors = get_chosen_connectors(
state,
key_store,
session_pm_input,
transaction_type,
&profile_wrapper,
)
.await?;
let mut final_selection = perform_cgraph_filtering(
state,
key_store,
chosen_connectors,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
if final_selection.is_empty() {
let fallback = profile_wrapper
.get_default_fallback_list_of_connector_under_profile()
.change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
final_selection = perform_cgraph_filtering(
state,
key_store,
fallback,
session_pm_input.backend_input.clone(),
None,
session_pm_input.profile_id,
transaction_type,
)
.await?;
}
if final_selection.is_empty() {
Ok(None)
} else {
Ok(Some(final_selection))
}
}
#[cfg(feature = "v2")]
pub fn make_dsl_input_for_surcharge(
_payment_attempt: &oss_storage::PaymentAttempt,
_payment_intent: &oss_storage::PaymentIntent,
_billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
todo!()
}
#[cfg(feature = "v1")]
pub fn make_dsl_input_for_surcharge(
payment_attempt: &oss_storage::PaymentAttempt,
payment_intent: &oss_storage::PaymentIntent,
billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate_data = dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
};
let payment_input = dsl_inputs::PaymentInput {
amount: payment_attempt.get_total_amount(),
// currency is always populated in payment_attempt during payment create
currency: payment_attempt
.currency
.get_required_value("currency")
.change_context(errors::RoutingError::DslMissingRequiredField {
field_name: "currency".to_string(),
})?,
authentication_type: payment_attempt.authentication_type,
card_bin: None,
capture_method: payment_attempt.capture_method,
business_country: payment_intent
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: billing_address
.and_then(|bic| bic.address)
.and_then(|add| add.country)
.map(api_enums::Country::from_alpha2),
business_label: payment_intent.business_label.clone(),
setup_future_usage: payment_intent.setup_future_usage,
};
let metadata = 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);
let payment_method_input = dsl_inputs::PaymentMethodInput {
payment_method: None,
payment_method_type: None,
card_network: None,
};
let backend_input = 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,
};
Ok(backend_input)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_dynamic_routing_with_open_router<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile: &domain::Profile,
payment_data: oss_storage::PaymentAttempt,
old_payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::RoutingError::DeserializationError {
from: "JSON".to_string(),
to: "DynamicRoutingAlgorithmRef".to_string(),
})
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "dynamic_routing_algorithm".to_string(),
})?;
logger::debug!(
"performing dynamic_routing with open_router for profile {}",
profile.get_id().get_string_repr()
);
let is_success_rate_routing_enabled =
dynamic_routing_algo_ref.is_success_rate_routing_enabled();
let is_elimination_enabled = dynamic_routing_algo_ref.is_elimination_enabled();
// Since success_based and elimination routing is being done in 1 api call, we call decide_gateway when either of it enabled
let connectors = if is_success_rate_routing_enabled || is_elimination_enabled {
let connectors = perform_decide_gateway_call_with_open_router(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_data,
is_elimination_enabled,
old_payment_data,
)
.await?;
if is_elimination_enabled {
// This will initiate the elimination process for the connector.
// Penalize the elimination score of the connector before making a payment.
// Once the payment is made, we will update the score based on the payment status
if let Some(connector) = connectors.first() {
logger::debug!(
"penalizing the elimination score of the gateway with id {} in open_router for profile {}",
connector, profile.get_id().get_string_repr()
);
update_gateway_score_with_open_router(
state,
connector.clone(),
profile.get_id(),
&payment_data.merchant_id,
&payment_data.payment_id,
common_enums::AttemptStatus::AuthenticationPending,
)
.await?
}
}
connectors
} else {
routable_connectors
};
Ok(connectors)
}
#[cfg(feature = "v1")]
pub async fn perform_open_routing_for_debit_routing<F, D>(
state: &SessionState,
co_badged_card_request: or_types::CoBadgedCardRequest,
card_isin: Option<Secret<String>>,
old_payment_data: &mut D,
) -> RoutingResult<or_types::DebitRoutingOutput>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let payment_attempt = old_payment_data.get_payment_attempt().clone();
logger::debug!(
"performing debit routing with open_router for profile {}",
payment_attempt.profile_id.get_string_repr()
);
let metadata = Some(
serde_json::to_string(&co_badged_card_request)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode Vaulting data to string")
.change_context(errors::RoutingError::MetadataParsingError)?,
);
let open_router_req_body = OpenRouterDecideGatewayRequest::construct_debit_request(
&payment_attempt,
metadata,
card_isin,
Some(or_types::RankingAlgorithm::NtwBasedRouting),
);
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
payment_attempt.profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"DecisionEngine: Debit Routing".to_string(),
Some(open_router_req_body.clone()),
true,
true,
);
let response: RoutingResult<utils::RoutingEventsResponse<DecidedGateway>> =
utils::EuclidApiClient::send_decision_engine_request(
state,
services::Method::Post,
"decide-gateway",
Some(open_router_req_body),
None,
Some(routing_events_wrapper),
)
.await;
let output = match response {
Ok(events_response) => {
let response =
events_response
.response
.ok_or(errors::RoutingError::OpenRouterError(
"Response from decision engine API is empty".to_string(),
))?;
let debit_routing_output = response
.debit_routing_output
.get_required_value("debit_routing_output")
.change_context(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))
.attach_printable("debit_routing_output is missing in the open routing response")?;
old_payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::from_decision_engine_approach(
&response.routing_approach,
),
));
Ok(debit_routing_output)
}
Err(error_response) => {
logger::error!("open_router_error_response: {:?}", error_response);
Err(errors::RoutingError::OpenRouterError(
"Failed to perform debit routing in open router".into(),
))
}
}?;
Ok(output)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_dynamic_routing_with_intelligent_router<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile: &domain::Profile,
dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
let dynamic_routing_algo_ref: api_routing::DynamicRoutingAlgorithmRef = profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::RoutingError::DeserializationError {
from: "JSON".to_string(),
to: "DynamicRoutingAlgorithmRef".to_string(),
})
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "dynamic_routing_algorithm".to_string(),
})?;
logger::debug!(
"performing dynamic_routing for profile {}",
profile.get_id().get_string_repr()
);
let payment_attempt = payment_data.get_payment_attempt().clone();
let mut connector_list = match dynamic_routing_algo_ref
.success_based_algorithm
.as_ref()
.async_map(|algorithm| {
perform_success_based_routing(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
payment_data,
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
{
Some(success_based_list) => success_based_list,
None => {
// Only run contract based if success based returns None
dynamic_routing_algo_ref
.contract_based_routing
.as_ref()
.async_map(|algorithm| {
perform_contract_based_routing(
state,
routable_connectors.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
payment_data,
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
.unwrap_or(routable_connectors.clone())
}
};
connector_list = dynamic_routing_algo_ref
.elimination_routing_algorithm
.as_ref()
.async_map(|algorithm| {
perform_elimination_routing(
state,
connector_list.clone(),
profile.get_id(),
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
dynamic_routing_config_params_interpolator.clone(),
algorithm.clone(),
)
})
.await
.transpose()
.inspect_err(|e| logger::error!(dynamic_routing_error=?e))
.ok()
.flatten()
.unwrap_or(connector_list);
Ok(connector_list)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn perform_decide_gateway_call_with_open_router<F, D>(
state: &SessionState,
mut routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
payment_attempt: &oss_storage::PaymentAttempt,
is_elimination_enabled: bool,
old_payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
logger::debug!(
"performing decide_gateway call with open_router for profile {}",
profile_id.get_string_repr()
);
let open_router_req_body = OpenRouterDecideGatewayRequest::construct_sr_request(
payment_attempt,
routable_connectors.clone(),
Some(or_types::RankingAlgorithm::SrBasedRouting),
is_elimination_enabled,
);
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
payment_attempt.profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"DecisionEngine: SuccessRate decide_gateway".to_string(),
Some(open_router_req_body.clone()),
true,
false,
);
let response: RoutingResult<utils::RoutingEventsResponse<DecidedGateway>> =
utils::SRApiClient::send_decision_engine_request(
state,
services::Method::Post,
"decide-gateway",
Some(open_router_req_body),
None,
Some(routing_events_wrapper),
)
.await;
let sr_sorted_connectors = match response {
Ok(resp) => {
let decided_gateway: DecidedGateway =
resp.response.ok_or(errors::RoutingError::OpenRouterError(
"Empty response received from open_router".into(),
))?;
let mut routing_event = resp.event.ok_or(errors::RoutingError::RoutingEventsError {
message: "Decision-Engine: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
routing_event.set_response_body(&decided_gateway);
routing_event.set_routing_approach(
utils::RoutingApproach::from_decision_engine_approach(
&decided_gateway.routing_approach,
)
.to_string(),
);
old_payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::from_decision_engine_approach(
&decided_gateway.routing_approach,
),
));
if let Some(gateway_priority_map) = decided_gateway.gateway_priority_map {
logger::debug!(gateway_priority_map=?gateway_priority_map, routing_approach=decided_gateway.routing_approach, "open_router decide_gateway call response");
routable_connectors.sort_by(|connector_choice_a, connector_choice_b| {
let connector_choice_a_score = gateway_priority_map
.get(&connector_choice_a.to_string())
.copied()
.unwrap_or(0.0);
let connector_choice_b_score = gateway_priority_map
.get(&connector_choice_b.to_string())
.copied()
.unwrap_or(0.0);
connector_choice_b_score
.partial_cmp(&connector_choice_a_score)
.unwrap_or(std::cmp::Ordering::Equal)
});
}
routing_event.set_routable_connectors(routable_connectors.clone());
state.event_handler().log_event(&routing_event);
Ok(routable_connectors)
}
Err(err) => {
logger::error!("open_router_error_response: {:?}", err);
Err(errors::RoutingError::OpenRouterError(
"Failed to perform decide_gateway call in open_router".into(),
))
}
}?;
Ok(sr_sorted_connectors)
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
pub async fn update_gateway_score_with_open_router(
state: &SessionState,
payment_connector: api_routing::RoutableConnectorChoice,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
payment_status: common_enums::AttemptStatus,
) -> RoutingResult<()> {
let open_router_req_body = or_types::UpdateScorePayload {
merchant_id: profile_id.clone(),
gateway: payment_connector.to_string(),
status: payment_status.foreign_into(),
payment_id: payment_id.clone(),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"DecisionEngine: SuccessRate update_gateway_score".to_string(),
Some(open_router_req_body.clone()),
true,
false,
);
let response: RoutingResult<utils::RoutingEventsResponse<or_types::UpdateScoreResponse>> =
utils::SRApiClient::send_decision_engine_request(
state,
services::Method::Post,
"update-gateway-score",
Some(open_router_req_body),
None,
Some(routing_events_wrapper),
)
.await;
match response {
Ok(resp) => {
let update_score_resp = resp.response.ok_or(errors::RoutingError::OpenRouterError(
"Failed to parse the response from open_router".into(),
))?;
let mut routing_event = resp.event.ok_or(errors::RoutingError::RoutingEventsError {
message: "Decision-Engine: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
logger::debug!(
"open_router update_gateway_score response for gateway with id {}: {:?}",
payment_connector,
update_score_resp.message
);
routing_event.set_response_body(&update_score_resp);
routing_event.set_payment_connector(payment_connector.clone()); // check this in review
state.event_handler().log_event(&routing_event);
Ok(())
}
Err(err) => {
logger::error!("open_router_update_gateway_score_error: {:?}", err);
Err(errors::RoutingError::OpenRouterError(
"Failed to update gateway score in open_router".into(),
))
}
}?;
Ok(())
}
/// success based dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn perform_success_based_routing<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
success_based_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
success_based_algo_ref: api_routing::SuccessBasedAlgorithm,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
if success_based_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing success_based_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::SuccessRateClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.success_rate_client;
let success_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::SuccessBasedRoutingConfig,
>(
state,
profile_id,
success_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "success_based_routing_algorithm_id".to_string(),
})
.attach_printable("success_based_routing_algorithm_id not found in profile_id")?,
)
.await
.change_context(errors::RoutingError::SuccessBasedRoutingConfigError)
.attach_printable("unable to fetch success_rate based dynamic routing configs")?;
let success_based_routing_config_params = success_based_routing_config_params_interpolator
.get_string_val(
success_based_routing_configs
.params
.as_ref()
.ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?,
);
let event_request = utils::CalSuccessRateEventRequest {
id: profile_id.get_string_repr().to_string(),
params: success_based_routing_config_params.clone(),
labels: routable_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: success_based_routing_configs
.config
.as_ref()
.map(utils::CalSuccessRateConfigEventRequest::from),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: CalculateSuccessRate".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let success_based_connectors_result = client
.calculate_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs,
success_based_routing_config_params,
routable_connectors,
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::SuccessRateCalculationError)
.attach_printable(
"unable to calculate/fetch success rate from dynamic routing service",
);
match success_based_connectors_result {
Ok(success_response) => {
let updated_resp = utils::CalSuccessRateEventResponse::try_from(
&success_response,
)
.change_context(errors::RoutingError::RoutingEventsError { message: "unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse".to_string(), status_code: 500 })
.attach_printable(
"unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse",
)?;
Ok(Some(updated_resp))
}
Err(e) => {
logger::error!(
"unable to calculate/fetch success rate from dynamic routing service: {:?}",
e.current_context()
);
Err(error_stack::report!(
errors::RoutingError::SuccessRateCalculationError
))
}
}
};
let events_response = routing_events_wrapper
.construct_event_builder(
"SuccessRateCalculator.FetchSuccessRate".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let success_based_connectors: utils::CalSuccessRateEventResponse = events_response
.response
.ok_or(errors::RoutingError::SuccessRateCalculationError)?;
// Need to log error case
let mut routing_event =
events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
routing_event.set_routing_approach(success_based_connectors.routing_approach.to_string());
payment_data.set_routing_approach_in_attempt(Some(common_enums::RoutingApproach::from(
success_based_connectors.routing_approach,
)));
let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len());
for label_with_score in success_based_connectors.labels_with_score {
let (connector, merchant_connector_id) = label_with_score.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidSuccessBasedConnectorLabel(label_with_score.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
)?;
connectors.push(api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
});
}
logger::debug!(success_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
/// elimination dynamic routing
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn perform_elimination_routing(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
elimination_routing_configs_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
elimination_algo_ref: api_routing::EliminationRoutingAlgorithm,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {
if elimination_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing elimination_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::EliminationClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.elimination_based_client;
let elimination_routing_config = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::EliminationRoutingConfig,
>(
state,
profile_id,
elimination_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "elimination_routing_algorithm_id".to_string(),
})
.attach_printable(
"elimination_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::RoutingError::EliminationRoutingConfigError)
.attach_printable("unable to fetch elimination dynamic routing configs")?;
let elimination_routing_config_params = elimination_routing_configs_params_interpolator
.get_string_val(
elimination_routing_config
.params
.as_ref()
.ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)?,
);
let event_request = utils::EliminationRoutingEventRequest {
id: profile_id.get_string_repr().to_string(),
params: elimination_routing_config_params.clone(),
labels: routable_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: elimination_routing_config
.elimination_analyser_config
.as_ref()
.map(utils::EliminationRoutingEventBucketConfig::from),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: PerformEliminationRouting".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let elimination_based_connectors_result = client
.perform_elimination_routing(
profile_id.get_string_repr().to_string(),
elimination_routing_config_params,
routable_connectors.clone(),
elimination_routing_config.elimination_analyser_config,
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::EliminationRoutingCalculationError)
.attach_printable(
"unable to analyze/fetch elimination routing from dynamic routing service",
);
match elimination_based_connectors_result {
Ok(elimination_response) => Ok(Some(utils::EliminationEventResponse::from(
&elimination_response,
))),
Err(e) => {
logger::error!(
"unable to analyze/fetch elimination routing from dynamic routing service: {:?}",
e.current_context()
);
Err(error_stack::report!(
errors::RoutingError::EliminationRoutingCalculationError
))
}
}
};
let events_response = routing_events_wrapper
.construct_event_builder(
"EliminationAnalyser.GetEliminationStatus".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let elimination_based_connectors: utils::EliminationEventResponse = events_response
.response
.ok_or(errors::RoutingError::EliminationRoutingCalculationError)?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
routing_event.set_routing_approach(utils::RoutingApproach::Elimination.to_string());
let mut connectors =
Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
let mut eliminated_connectors =
Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
let mut non_eliminated_connectors =
Vec::with_capacity(elimination_based_connectors.labels_with_status.len());
for labels_with_status in elimination_based_connectors.labels_with_status {
let (connector, merchant_connector_id) = labels_with_status.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidEliminationBasedConnectorLabel(labels_with_status.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the elimination based dynamic routing service",
)?;
let routable_connector = api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
};
if labels_with_status
.elimination_information
.is_some_and(|elimination_info| {
elimination_info
.entity
.is_some_and(|entity_info| entity_info.is_eliminated)
})
{
eliminated_connectors.push(routable_connector);
} else {
non_eliminated_connectors.push(routable_connector);
}
connectors.extend(non_eliminated_connectors.clone());
connectors.extend(eliminated_connectors.clone());
}
logger::debug!(dynamic_eliminated_connectors=?eliminated_connectors);
logger::debug!(dynamic_elimination_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
#[allow(clippy::too_many_arguments)]
pub async fn perform_contract_based_routing<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
_dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
{
if contract_based_algo_ref.enabled_feature
== api_routing::DynamicRoutingFeatures::DynamicConnectorSelection
{
logger::debug!(
"performing contract_based_routing for profile {}",
profile_id.get_string_repr()
);
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::RoutingError::ContractRoutingClientInitializationError)
.attach_printable("dynamic routing gRPC client not found")?
.contract_based_client;
let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<
api_routing::ContractBasedRoutingConfig,
>(
state,
profile_id,
contract_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::RoutingError::GenericNotFoundError {
field: "contract_based_routing_algorithm_id".to_string(),
})
.attach_printable("contract_based_routing_algorithm_id not found in profile_id")?,
)
.await
.change_context(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("unable to fetch contract based dynamic routing configs")?;
let label_info = contract_based_routing_configs
.label_info
.clone()
.ok_or(errors::RoutingError::ContractBasedRoutingConfigError)
.attach_printable("Label information not found in contract routing configs")?;
let contract_based_connectors = routable_connectors
.clone()
.into_iter()
.filter(|conn| {
label_info
.iter()
.any(|info| Some(info.mca_id.clone()) == conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let mut other_connectors = routable_connectors
.into_iter()
.filter(|conn| {
label_info
.iter()
.all(|info| Some(info.mca_id.clone()) != conn.merchant_connector_id.clone())
})
.collect::<Vec<_>>();
let event_request = utils::CalContractScoreEventRequest {
id: profile_id.get_string_repr().to_string(),
params: "".to_string(),
labels: contract_based_connectors
.iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>(),
config: Some(contract_based_routing_configs.clone()),
};
let routing_events_wrapper = utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
merchant_id.to_owned(),
"IntelligentRouter: PerformContractRouting".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let contract_based_connectors_result = client
.calculate_contract_score(
profile_id.get_string_repr().into(),
contract_based_routing_configs.clone(),
"".to_string(),
contract_based_connectors,
state.get_grpc_headers(),
)
.await
.attach_printable(
"unable to calculate/fetch contract score from dynamic routing service",
);
let contract_based_connectors = match contract_based_connectors_result {
Ok(resp) => Some(utils::CalContractScoreEventResponse::from(&resp)),
Err(err) => match err.current_context() {
DynamicRoutingError::ContractNotFound => {
client
.update_contracts(
profile_id.get_string_repr().into(),
label_info,
"".to_string(),
vec![],
u64::default(),
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::ContractScoreUpdationError)
.attach_printable(
"unable to update contract based routing window in dynamic routing service",
)?;
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into());
}
_ => {
return Err((errors::RoutingError::ContractScoreCalculationError {
err: err.to_string(),
})
.into())
}
},
};
Ok(contract_based_connectors)
};
let events_response = routing_events_wrapper
.construct_event_builder(
"ContractScoreCalculator.FetchContractScore".to_string(),
RoutingEngine::IntelligentRouter,
ApiMethod::Grpc,
)?
.trigger_event(state, closure)
.await?;
let contract_based_connectors: utils::CalContractScoreEventResponse = events_response
.response
.ok_or(errors::RoutingError::ContractScoreCalculationError {
err: "CalContractScoreEventResponse not found".to_string(),
})?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})?;
payment_data.set_routing_approach_in_attempt(Some(
common_enums::RoutingApproach::ContractBasedRouting,
));
let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());
for label_with_score in contract_based_connectors.labels_with_score {
let (connector, merchant_connector_id) = label_with_score.label
.split_once(':')
.ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))
.attach_printable(
"unable to split connector_name and mca_id from the label obtained by the dynamic routing service",
)?;
connectors.push(api_routing::RoutableConnectorChoice {
choice_kind: api_routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(connector)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "RoutableConnectors".to_string(),
})
.attach_printable("unable to convert String to RoutableConnectors")?,
merchant_connector_id: Some(
common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.change_context(errors::RoutingError::GenericConversionError {
from: "String".to_string(),
to: "MerchantConnectorAccountId".to_string(),
})
.attach_printable("unable to convert MerchantConnectorAccountId from string")?,
),
});
}
connectors.append(&mut other_connectors);
logger::debug!(contract_based_routing_connectors=?connectors);
routing_event.set_status_code(200);
routing_event.set_routable_connectors(connectors.clone());
routing_event.set_routing_approach(api_routing::RoutingApproach::ContractBased.to_string());
state.event_handler().log_event(&routing_event);
Ok(connectors)
} else {
Ok(routable_connectors)
}
}
| crates/router/src/core/payments/routing.rs | router::src::core::payments::routing | 20,695 | true |
// File: crates/router/src/core/payments/flows.rs
// Module: router::src::core::payments::flows
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::{self, ExecutionMode};
use common_types::payments::CustomerAcceptance;
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, 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,
merchant_context: &domain::MerchantContext,
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,
_merchant_context: &domain::MerchantContext,
_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,
_merchant_context: &domain::MerchantContext,
_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>,
) -> 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,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>;
async fn add_session_token<'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 add_payment_method_token<'a>(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_tokenization_action: &payments::TokenizationAction,
_should_continue_payment: bool,
) -> 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 preprocessing_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 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,
) -> 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,
) -> 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,
) {
}
async fn call_unified_connector_service<'a>(
&mut self,
_state: &SessionState,
_header_payload: &domain_payments::HeaderPayload,
_lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] _merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")]
_merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
_merchant_context: &domain::MerchantContext,
_unified_connector_service_execution_mode: ExecutionMode,
) -> RouterResult<()>
where
F: Clone,
Self: Sized,
dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
{
Ok(())
}
#[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,
_merchant_context: &domain::MerchantContext,
_unified_connector_service_execution_mode: ExecutionMode,
) -> 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,
) -> 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,
)
.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,
))
}
}
}
}
}
| crates/router/src/core/payments/flows.rs | router::src::core::payments::flows | 2,670 | true |
// File: crates/router/src/core/payments/operations.rs
// Module: router::src::core::payments::operations
#[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,
merchant_context: &domain::MerchantContext,
) -> RouterResult<(BoxedOperation<'b, F, R, D>, ValidateResult)>;
}
#[cfg(feature = "v2")]
pub trait ValidateRequest<F, R, D> {
fn validate_request(
&self,
request: &R,
merchant_context: &domain::MerchantContext,
) -> 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,
merchant_context: &domain::MerchantContext,
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,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<GetTrackerResponse<D>>;
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 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>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> 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>;
#[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,
merchant_context: &domain::MerchantContext,
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,
merchant_context: &domain::MerchantContext,
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,
_merchant_context: &domain::MerchantContext,
_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,
_merchant_context: &domain::MerchantContext,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_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,
merchant_context: &domain::MerchantContext,
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,
merchant_context: &domain::MerchantContext,
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,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
/// 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,
// _merchant_context: &domain::MerchantContext,
// _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,
payment_data: D,
customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
updated_customer: Option<storage::CustomerUpdate>,
mechant_key_store: &domain::MerchantKeyStore,
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>,
_merchant_context: &domain::MerchantContext,
_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)]
#[cfg(feature = "v1")]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
_request: Option<CustomerDetails>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
let db = &*state.store;
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(
&state.into(),
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,
_merchant_context: &domain::MerchantContext,
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,
_merchant_context: &domain::MerchantContext,
_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)]
#[cfg(feature = "v1")]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
_request: Option<CustomerDetails>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
let db = &*state.store;
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(
&state.into(),
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,
_merchant_context: &domain::MerchantContext,
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,
_merchant_context: &domain::MerchantContext,
_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)]
#[cfg(feature = "v1")]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut D,
_request: Option<CustomerDetails>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCancelRequest, D>,
Option<domain::Customer>,
),
errors::StorageError,
> {
let db = &*state.store;
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(
&state.into(),
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,
_merchant_context: &domain::MerchantContext,
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,
_merchant_context: &domain::MerchantContext,
_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>,
{
#[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>,
_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))
}
#[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,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRejectRequest, D>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
_request: &api::PaymentsRejectRequest,
_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,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut D,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
/// Validate if a particular operation can be performed for the given intent status
pub trait ValidateStatusForOperation {
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse>;
}
/// Should the connector be called for this operation
pub trait ShouldCallConnector {
fn should_call_connector(
&self,
intent_status: common_enums::IntentStatus,
force_sync: Option<bool>,
) -> bool;
}
| crates/router/src/core/payments/operations.rs | router::src::core::payments::operations | 7,610 | true |
// File: crates/router/src/core/payments/retry.rs
// Module: router::src::core::payments::retry
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::{
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>,
merchant_context: &domain::MerchantContext,
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 + '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,
merchant_context.get_merchant_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,
merchant_context,
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,
merchant_context.get_merchant_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,
merchant_context,
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 flow = get_flow_name::<F>()?;
Ok(
payments::helpers::get_gsm_record(state, error_code, error_message, connector_name, flow)
.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>,
merchant_context: &domain::MerchantContext,
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 + '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,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
router_data,
is_step_up,
)
.await?;
let (merchant_connector_account, router_data, tokenization_action) =
payments::call_connector_service_prerequisites(
state,
merchant_context,
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,
merchant_context,
connector.clone(),
operation,
payment_data,
customer,
payments::CallConnectorAction::Trigger,
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 key_manager_state = &state.into();
let additional_payment_method_data =
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 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,
payment_method_data: additional_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,
};
#[cfg(feature = "v1")]
db.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
storage_scheme,
)
.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,
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,
)
.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)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting payment attempt")?;
#[cfg(feature = "v2")]
let payment_attempt = db
.insert_payment_attempt(
key_manager_state,
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(
key_manager_state,
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::PaymentAttemptNew {
let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
storage::PaymentAttemptNew {
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,
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(),
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,
}
}
#[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
| storage_enums::AttemptStatus::AutoRefunded
| storage_enums::AttemptStatus::CaptureFailed
| storage_enums::AttemptStatus::PartialCharged
| storage_enums::AttemptStatus::PartialChargedAndChargeable
| storage_enums::AttemptStatus::Pending
| storage_enums::AttemptStatus::PaymentMethodAwaited
| storage_enums::AttemptStatus::ConfirmationAwaited
| storage_enums::AttemptStatus::Unresolved
| storage_enums::AttemptStatus::DeviceDataCollectionPending
| storage_enums::AttemptStatus::IntegrityFailure
| storage_enums::AttemptStatus::Expired
| storage_enums::AttemptStatus::PartiallyAuthorized => false,
storage_enums::AttemptStatus::AuthenticationFailed
| storage_enums::AttemptStatus::AuthorizationFailed
| storage_enums::AttemptStatus::Failure => true,
}
}
}
}
| crates/router/src/core/payments/retry.rs | router::src::core::payments::retry | 6,474 | true |
// File: crates/router/src/core/payments/operations/payment_status.rs
// Module: router::src::core::payments::operations::payment_status
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState};
use error_stack::ResultExt;
use router_derive::PaymentOperation;
use router_env::{instrument, logger, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{
helpers, operations, types as payment_types, CustomerDetails, PaymentAddress,
PaymentData,
},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
api, domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "sync")]
pub struct PaymentStatus;
type PaymentStatusOperation<'b, F, R> = BoxedOperation<'b, F, R, PaymentData<F>>;
impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for PaymentStatus {
type Data = PaymentData<F>;
fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)>
{
Ok(self)
}
}
impl<F: Send + Clone + Sync> Operation<F, api::PaymentsRequest> for &PaymentStatus {
type Data = PaymentData<F>;
fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsRequest, PaymentData<F>>> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> + Send + Sync)>
{
Ok(*self)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentStatus {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
PaymentStatusOperation<'a, F, api::PaymentsRequest>,
Option<domain::Customer>,
),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentStatusOperation<'a, F, api::PaymentsRequest>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn add_task_to_process_tracker<'a>(
&'a self,
state: &'a SessionState,
payment_attempt: &storage::PaymentAttempt,
requeue: bool,
schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
helpers::add_domain_task_to_pt(self, state, payment_attempt, requeue, schedule_time).await
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, request.routing.clone()).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentStatus {
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentStatusOperation<'b, F, api::PaymentsRequest>,
PaymentData<F>,
)>
where
F: 'b + Send,
{
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentStatus))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest>
for PaymentStatus
{
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>,
PaymentData<F>,
)>
where
F: 'b + Send,
{
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentStatus))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest>
for PaymentStatus
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRetrieveRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>,
> {
Box::pin(get_tracker_for_sync(
payment_id,
&merchant_context.clone(),
state,
request,
self,
merchant_context.get_merchant_account().storage_scheme,
))
.await
}
}
#[cfg(feature = "v2")]
async fn get_tracker_for_sync<
'a,
F: Send + Clone,
Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync,
>(
_payment_id: &api::PaymentIdType,
_merchant_context: &domain::MerchantContext,
_state: &SessionState,
_request: &api::PaymentsRetrieveRequest,
_operation: Op,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>>
{
todo!()
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn get_tracker_for_sync<
'a,
F: Send + Clone,
Op: Operation<F, api::PaymentsRetrieveRequest, Data = PaymentData<F>> + 'a + Send + Sync,
>(
payment_id: &api::PaymentIdType,
merchant_context: &domain::MerchantContext,
state: &SessionState,
request: &api::PaymentsRetrieveRequest,
operation: Op,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>>
{
let (payment_intent, mut payment_attempt, currency, amount);
(payment_intent, payment_attempt) = get_payment_intent_payment_attempt(
state,
payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await?;
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let payment_id = payment_attempt.payment_id.clone();
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id.clone(),
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
payment_attempt.encoded_data.clone_from(&request.param);
let db = &*state.store;
let key_manager_state = &state.into();
let attempts = match request.expand_attempts {
Some(true) => {
Some(db
.find_attempts_by_merchant_id_payment_id(merchant_context.get_merchant_account().get_id(), &payment_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id:?}",merchant_context.get_merchant_account().get_id())
})?)
},
_ => None,
};
let multiple_capture_data = if payment_attempt.multiple_capture_count > Some(0) {
let captures = db
.find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
&payment_attempt.attempt_id,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id())
})?;
Some(payment_types::MultipleCaptureData::new_for_sync(
captures,
request.expand_captures,
)?)
} else {
None
};
let refunds = db
.find_refund_by_payment_id_merchant_id(
&payment_id,
merchant_context.get_merchant_account().get_id(),
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!(
"Failed while getting refund list for, payment_id: {:?}, merchant_id: {:?}",
&payment_id,
merchant_context.get_merchant_account().get_id()
)
})?;
let authorizations = db
.find_all_authorizations_by_merchant_id_payment_id(
merchant_context.get_merchant_account().get_id(),
&payment_id,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!(
"Failed while getting authorizations list for, payment_id: {:?}, merchant_id: {:?}",
&payment_id,
merchant_context.get_merchant_account().get_id()
)
})?;
let disputes = db
.find_disputes_by_merchant_id_payment_id(merchant_context.get_merchant_account().get_id(), &payment_id)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id())
})?;
let frm_response = if cfg!(feature = "frm") {
db.find_fraud_check_by_payment_id(payment_id.to_owned(), merchant_context.get_merchant_account().get_id().clone())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id:?}", merchant_context.get_merchant_account().get_id())
})
.ok()
} else {
None
};
let contains_encoded_data = payment_attempt.encoded_data.is_some();
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,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_method_info =
if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() {
match db
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
storage_scheme,
)
.await
{
Ok(payment_method) => Some(payment_method),
Err(error) => {
if error.current_context().is_db_not_found() {
logger::info!("Payment Method not found in db {:?}", error);
None
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error retrieving payment method from db")?
}
}
}
} else {
None
};
let merchant_id = payment_intent.merchant_id.clone();
let authentication_store = if let Some(ref authentication_id) =
payment_attempt.authentication_id
{
let authentication = db
.find_authentication_by_merchant_id_authentication_id(&merchant_id, authentication_id)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Error while fetching authentication record with authentication_id {}",
authentication_id.get_string_repr()
)
})?;
Some(
hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
authentication,
cavv: None, // marking this as None since we don't need authentication value in payment status flow
},
)
} else {
None
};
let payment_link_data = payment_intent
.payment_link_id
.as_ref()
.async_map(|id| crate::core::payments::get_payment_link_response_from_id(state, id))
.await
.transpose()?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
currency,
amount,
email: None,
mandate_id: payment_attempt
.mandate_id
.clone()
.map(|id| api_models::payments::MandateIds {
mandate_id: Some(id),
mandate_reference_id: None,
}),
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
address: PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
token_data: None,
confirm: Some(request.force_sync),
payment_method_data: None,
payment_method_token: None,
payment_method_info,
force_sync: Some(
request.force_sync
&& (helpers::check_force_psync_precondition(payment_attempt.status)
|| contains_encoded_data),
),
all_keys_required: request.all_keys_required,
payment_attempt,
refunds,
disputes,
attempts,
sessions_token: vec![],
card_cvc: None,
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data,
redirect_response: None,
payment_link_data,
surcharge_details: None,
frm_message: frm_response,
incremental_authorization_details: None,
authorizations,
authentication: authentication_store,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: business_profile.is_manual_retry_enabled,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(operation),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRetrieveRequest, PaymentData<F>>
for PaymentStatus
{
fn validate_request<'b>(
&'b self,
request: &api::PaymentsRetrieveRequest,
merchant_context: &domain::MerchantContext,
) -> RouterResult<(
PaymentStatusOperation<'b, F, api::PaymentsRetrieveRequest>,
operations::ValidateResult,
)> {
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: request.resource_id.clone(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
pub async fn get_payment_intent_payment_attempt(
state: &SessionState,
payment_id: &api::PaymentIdType,
merchant_id: &common_utils::id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> {
let key_manager_state: KeyManagerState = state.into();
let db = &*state.store;
let get_pi_pa = || async {
let (pi, pa);
match payment_id {
api_models::payments::PaymentIdType::PaymentIntentId(ref id) => {
pi = db
.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
id,
merchant_id,
key_store,
storage_scheme,
)
.await?;
pa = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&pi.payment_id,
merchant_id,
pi.active_attempt.get_id().as_str(),
storage_scheme,
)
.await?;
}
api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => {
pa = db
.find_payment_attempt_by_merchant_id_connector_txn_id(
merchant_id,
id,
storage_scheme,
)
.await?;
pi = db
.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
&pa.payment_id,
merchant_id,
key_store,
storage_scheme,
)
.await?;
}
api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => {
pa = db
.find_payment_attempt_by_attempt_id_merchant_id(id, merchant_id, storage_scheme)
.await?;
pi = db
.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
&pa.payment_id,
merchant_id,
key_store,
storage_scheme,
)
.await?;
}
api_models::payments::PaymentIdType::PreprocessingId(ref id) => {
pa = db
.find_payment_attempt_by_preprocessing_id_merchant_id(
id,
merchant_id,
storage_scheme,
)
.await?;
pi = db
.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
&pa.payment_id,
merchant_id,
key_store,
storage_scheme,
)
.await?;
}
}
error_stack::Result::<_, errors::StorageError>::Ok((pi, pa))
};
get_pi_pa()
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
// TODO (#7195): Add platform merchant account validation once client_secret auth is solved
}
| crates/router/src/core/payments/operations/payment_status.rs | router::src::core::payments::operations::payment_status | 5,033 | true |
// File: crates/router/src/core/payments/operations/tax_calculation.rs
// Module: router::src::core::payments::operations::tax_calculation
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState};
use error_stack::ResultExt;
use masking::PeekInterface;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, PaymentData, PaymentMethodChecker},
utils as core_utils,
},
db::errors::ConnectorErrorExt,
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "sdk_session_update")]
pub struct PaymentSessionUpdate;
type PaymentSessionUpdateOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsDynamicTaxCalculationRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync>
GetTracker<F, PaymentData<F>, api::PaymentsDynamicTaxCalculationRequest>
for PaymentSessionUpdate
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsDynamicTaxCalculationRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<
'a,
F,
api::PaymentsDynamicTaxCalculationRequest,
PaymentData<F>,
>,
> {
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let db = &*state.store;
let key_manager_state: &KeyManagerState = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Failed,
storage_enums::IntentStatus::Succeeded,
],
"create a session update for",
)?;
helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?;
let mut payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let currency = payment_intent.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
payment_attempt.payment_method_type = Some(request.payment_method_type);
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let tax_data = payments::TaxData {
shipping_details: request.shipping.clone().into(),
payment_method_type: request.payment_method_type,
};
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
customer_acceptance: None,
token: None,
token_data: None,
setup_mandate: None,
address: payments::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
None,
None,
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: Some(tax_data),
session_id: request.session_id.clone(),
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsDynamicTaxCalculationRequest, PaymentData<F>>
for PaymentSessionUpdate
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> errors::CustomResult<
(
PaymentSessionUpdateOperation<'a, F>,
Option<domain::Customer>,
),
errors::StorageError,
> {
Ok((Box::new(self), None))
}
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
merchant_context: &domain::MerchantContext,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
let skip_external_tax_calculation = payment_data
.payment_intent
.skip_external_tax_calculation
.unwrap_or(false);
if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
let merchant_connector_id = business_profile
.tax_connector_id
.as_ref()
.get_required_value("business_profile.tax_connector_id")?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&business_profile.merchant_id,
merchant_connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
#[cfg(feature = "v2")]
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
let connector_data =
api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?;
let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data(
state,
merchant_context,
payment_data,
&mca,
)
.await?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CalculateTax,
types::PaymentsTaxCalculationData,
types::TaxCalculationResponseData,
> = connector_data.connector.get_connector_integration();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()
.attach_printable("Tax connector Response Failed")?;
let tax_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
let payment_method_type = payment_data
.tax_data
.clone()
.map(|tax_data| tax_data.payment_method_type)
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing tax_data.payment_method_type")?;
payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails {
payment_method_type: Some(diesel_models::PaymentMethodTypeTax {
order_tax_amount: tax_response.order_tax_amount,
pmt: payment_method_type,
}),
default: None,
});
Ok(())
} else {
Ok(())
}
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentSessionUpdateOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
_request: &api::PaymentsDynamicTaxCalculationRequest,
_payment_intent: &storage::PaymentIntent,
) -> errors::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,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsDynamicTaxCalculationRequest>
for PaymentSessionUpdate
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentSessionUpdateOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
// For Google Pay and Apple Pay, we don’t need to call the connector again; we can directly confirm the payment after tax_calculation. So, we update the required fields in the database during the update_tracker call.
if payment_data.should_update_in_update_tracker() {
let shipping_address = payment_data
.tax_data
.clone()
.map(|tax_data| tax_data.shipping_details);
let key_manager_state = state.into();
let shipping_details = shipping_address
.clone()
.async_map(|shipping_details| {
create_encrypted_data(&key_manager_state, key_store, shipping_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt shipping details")?;
let shipping_address = helpers::create_or_update_address_for_payment_by_request(
state,
shipping_address.map(From::from).as_ref(),
payment_data.payment_intent.shipping_address_id.as_deref(),
&payment_data.payment_intent.merchant_id,
payment_data.payment_intent.customer_id.as_ref(),
key_store,
&payment_data.payment_intent.payment_id,
storage_scheme,
)
.await?;
let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SessionResponseUpdate {
tax_details: payment_data.payment_intent.tax_details.clone().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("payment_intent.tax_details not found")?,
shipping_address_id: shipping_address.map(|address| address.address_id),
updated_by: payment_data.payment_intent.updated_by.clone(),
shipping_details,
};
let db = &*state.store;
let payment_intent = payment_data.payment_intent.clone();
let updated_payment_intent = db
.update_payment_intent(
&state.into(),
payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_intent = updated_payment_intent;
Ok((Box::new(self), payment_data))
} else {
Ok((Box::new(self), payment_data))
}
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, api::PaymentsDynamicTaxCalculationRequest, PaymentData<F>>
for PaymentSessionUpdate
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsDynamicTaxCalculationRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
PaymentSessionUpdateOperation<'b, F>,
operations::ValidateResult,
)> {
//paymentid is already generated and should be sent in the request
let given_payment_id = request.payment_id.clone();
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| crates/router/src/core/payments/operations/tax_calculation.rs | router::src::core::payments::operations::tax_calculation | 3,528 | true |
// File: crates/router/src/core/payments/operations/payment_get.rs
// Module: router::src::core::payments::operations::payment_get
use api_models::{enums::FrmSuggestion, payments::PaymentsRetrieveRequest};
use async_trait::async_trait;
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::PaymentStatusData;
use router_env::{instrument, tracing};
use super::{Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{
helpers,
operations::{self, ValidateStatusForOperation},
},
},
routes::{app::ReqState, SessionState},
types::{
api::{self, ConnectorCallType},
domain::{self},
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentGet;
impl ValidateStatusForOperation for PaymentGet {
/// Validate if the current operation can be performed on the current status of the payment intent
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing
| common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::Conflicted
| common_enums::IntentStatus::Expired => Ok(()),
// These statuses are not valid for this operation
common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::RequiresPaymentMethod => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: [
common_enums::IntentStatus::RequiresCapture,
common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture,
common_enums::IntentStatus::RequiresCustomerAction,
common_enums::IntentStatus::RequiresMerchantAction,
common_enums::IntentStatus::Processing,
common_enums::IntentStatus::Succeeded,
common_enums::IntentStatus::Failed,
common_enums::IntentStatus::PartiallyCapturedAndCapturable,
common_enums::IntentStatus::PartiallyCaptured,
common_enums::IntentStatus::Cancelled,
]
.map(|enum_value| enum_value.to_string())
.join(", "),
})
}
}
}
}
type BoxedConfirmOperation<'b, F> =
super::BoxedOperation<'b, F, PaymentsRetrieveRequest, PaymentStatusData<F>>;
// TODO: change the macro to include changes for v2
// TODO: PaymentData in the macro should be an input
impl<F: Send + Clone + Sync> Operation<F, PaymentsRetrieveRequest> for &PaymentGet {
type Data = PaymentStatusData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentsRetrieveRequest, Self::Data> + Send + Sync)>
{
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsRetrieveRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)>
{
Ok(*self)
}
}
#[automatically_derived]
impl<F: Send + Clone + Sync> Operation<F, PaymentsRetrieveRequest> for PaymentGet {
type Data = PaymentStatusData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentsRetrieveRequest, Self::Data> + Send + Sync)>
{
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsRetrieveRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsRetrieveRequest> + Send + Sync)>
{
Ok(self)
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsRetrieveRequest, PaymentStatusData<F>>
for PaymentGet
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &PaymentsRetrieveRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
let validate_result = operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
};
Ok(validate_result)
}
}
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentStatusData<F>, PaymentsRetrieveRequest>
for PaymentGet
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &PaymentsRetrieveRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<PaymentStatusData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let active_attempt_id = payment_intent.active_attempt_id.as_ref().ok_or_else(|| {
errors::ApiErrorResponse::MissingRequiredField {
field_name: ("active_attempt_id"),
}
})?;
let mut payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
active_attempt_id,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not find payment attempt given the attempt id")?;
payment_attempt.encoded_data = request
.param
.as_ref()
.map(|val| masking::Secret::new(val.clone()));
let should_sync_with_connector =
request.force_sync && payment_intent.status.should_force_sync_with_connector();
// We need the address here to send it in the response
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
.shipping_address
.clone()
.map(|address| address.into_inner()),
payment_intent
.billing_address
.clone()
.map(|address| address.into_inner()),
payment_attempt
.payment_method_billing_address
.clone()
.map(|address| address.into_inner()),
Some(true),
);
let attempts = match request.expand_attempts {
true => payment_intent
.active_attempt_id
.as_ref()
.async_map(|active_attempt| async {
db.find_payment_attempts_by_payment_intent_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not find payment attempts for the given the intent id")
})
.await
.transpose()?,
false => None,
};
let merchant_connector_details = request.merchant_connector_details.clone();
let payment_data = PaymentStatusData {
flow: std::marker::PhantomData,
payment_intent,
payment_attempt,
payment_address,
attempts,
should_sync_with_connector,
merchant_connector_details,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, PaymentsRetrieveRequest, PaymentStatusData<F>>
for PaymentGet
{
async fn get_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentStatusData<F>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
match payment_data.payment_intent.customer_id.clone() {
Some(id) => {
let customer = state
.store
.find_customer_by_global_id(
&state.into(),
&id,
merchant_key_store,
storage_scheme,
)
.await?;
Ok((Box::new(self), Some(customer)))
}
None => Ok((Box::new(self), None)),
}
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut PaymentStatusData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedConfirmOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn perform_routing<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
state: &SessionState,
// TODO: do not take the whole payment data here
payment_data: &mut PaymentStatusData<F>,
) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> {
let payment_attempt = &payment_data.payment_attempt;
if payment_data.should_sync_with_connector {
let connector = payment_attempt
.connector
.as_ref()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector is none when constructing response")?;
let merchant_connector_id = payment_attempt
.merchant_connector_id
.as_ref()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector id is none when constructing response")?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
Some(merchant_connector_id.to_owned()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
Ok(ConnectorCallType::PreDetermined(
api::ConnectorRoutingData::from(connector_data),
))
} else {
Ok(ConnectorCallType::Skip)
}
}
#[cfg(feature = "v2")]
async fn get_connector_from_request<'a>(
&'a self,
state: &SessionState,
request: &PaymentsRetrieveRequest,
payment_data: &mut PaymentStatusData<F>,
) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> {
use crate::core::payments::OperationSessionSetters;
let connector_data = helpers::get_connector_data_from_request(
state,
request.merchant_connector_details.clone(),
)
.await?;
payment_data
.set_connector_in_payment_attempt(Some(connector_data.connector_name.to_string()));
Ok(connector_data)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentStatusData<F>, PaymentsRetrieveRequest>
for PaymentGet
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: PaymentStatusData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentStatusData<F>)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
| crates/router/src/core/payments/operations/payment_get.rs | router::src::core::payments::operations::payment_get | 2,988 | true |
// File: crates/router/src/core/payments/operations/payment_confirm_intent.rs
// Module: router::src::core::payments::operations::payment_confirm_intent
use api_models::{enums::FrmSuggestion, payments::PaymentsConfirmIntentRequest};
use async_trait::async_trait;
use common_utils::{ext_traits::Encode, fp_utils::when, id_type, types::keymanager::ToEncryptable};
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::PaymentConfirmData;
use hyperswitch_interfaces::api::ConnectorSpecifications;
use masking::{ExposeOptionInterface, PeekInterface};
use router_env::{instrument, tracing};
use super::{Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
admin,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payment_methods,
payments::{
self, call_decision_manager, helpers,
operations::{self, ValidateStatusForOperation},
populate_surcharge_details, CustomerDetails, OperationSessionSetters, PaymentAddress,
PaymentData,
},
utils as core_utils,
},
routes::{app::ReqState, SessionState},
services::{self, connector_integration_interface::ConnectorEnum},
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain::{self, types as domain_types},
storage::{self, enums as storage_enums},
},
utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentIntentConfirm;
impl ValidateStatusForOperation for PaymentIntentConfirm {
/// Validate if the current operation can be performed on the current status of the payment intent
fn validate_status_for_operation(
&self,
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
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: ["requires_payment_method".to_string()].join(", "),
})
}
}
}
}
type BoxedConfirmOperation<'b, F> =
super::BoxedOperation<'b, F, PaymentsConfirmIntentRequest, PaymentConfirmData<F>>;
// TODO: change the macro to include changes for v2
// TODO: PaymentData in the macro should be an input
impl<F: Send + Clone + Sync> Operation<F, PaymentsConfirmIntentRequest> for &PaymentIntentConfirm {
type Data = PaymentConfirmData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, PaymentsConfirmIntentRequest, Self::Data> + Send + Sync),
> {
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsConfirmIntentRequest> + Send + Sync)>
{
Ok(*self)
}
fn to_domain(
&self,
) -> RouterResult<&(dyn Domain<F, PaymentsConfirmIntentRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsConfirmIntentRequest> + Send + Sync)>
{
Ok(*self)
}
}
#[automatically_derived]
impl<F: Send + Clone + Sync> Operation<F, PaymentsConfirmIntentRequest> for PaymentIntentConfirm {
type Data = PaymentConfirmData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, PaymentsConfirmIntentRequest, Self::Data> + Send + Sync),
> {
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsConfirmIntentRequest> + Send + Sync)>
{
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsConfirmIntentRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsConfirmIntentRequest> + Send + Sync)>
{
Ok(self)
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsConfirmIntentRequest, PaymentConfirmData<F>>
for PaymentIntentConfirm
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &PaymentsConfirmIntentRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
let validate_result = operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
};
Ok(validate_result)
}
}
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, PaymentsConfirmIntentRequest>
for PaymentIntentConfirm
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &id_type::GlobalPaymentId,
request: &PaymentsConfirmIntentRequest,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
self.validate_status_for_operation(payment_intent.status)?;
let cell_id = state.conf.cell_information.id.clone();
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt {
payment_method_billing_address: request.payment_method_data.billing.as_ref().map(|address| address.clone().encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode payment_method_billing address")?.map(masking::Secret::new),
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let payment_attempt_domain_model =
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::create_domain_model(
&payment_intent,
cell_id,
storage_scheme,
request,
encrypted_data
)
.await?;
let payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt =
db.insert_payment_attempt(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_attempt_domain_model,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not insert payment attempt")?;
let payment_method_data = request
.payment_method_data
.payment_method_data
.clone()
.map(hyperswitch_domain_models::payment_method_data::PaymentMethodData::from);
if request.payment_token.is_some() {
when(
!matches!(
payment_method_data,
Some(domain::payment_method_data::PaymentMethodData::CardToken(_))
),
|| {
Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_method_data",
})
.attach_printable(
"payment_method_data should be card_token when a token is passed",
)
},
)?;
};
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
.shipping_address
.clone()
.map(|address| address.into_inner()),
payment_intent
.billing_address
.clone()
.map(|address| address.into_inner()),
payment_attempt
.payment_method_billing_address
.clone()
.map(|address| address.into_inner()),
Some(true),
);
let merchant_connector_details = request.merchant_connector_details.clone();
let payment_data = PaymentConfirmData {
flow: std::marker::PhantomData,
payment_intent,
payment_attempt,
payment_method_data,
payment_address,
mandate_data: None,
payment_method: None,
merchant_connector_details,
external_vault_pmd: None,
webhook_url: request
.webhook_url
.as_ref()
.map(|url| url.get_string_repr().to_string()),
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, PaymentsConfirmIntentRequest, PaymentConfirmData<F>>
for PaymentIntentConfirm
{
async fn get_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
match payment_data.payment_intent.customer_id.clone() {
Some(id) => {
let customer = state
.store
.find_customer_by_global_id(
&state.into(),
&id,
merchant_key_store,
storage_scheme,
)
.await?;
Ok((Box::new(self), Some(customer)))
}
None => Ok((Box::new(self), None)),
}
}
async fn run_decision_manager<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse> {
let authentication_type = payment_data.payment_intent.authentication_type;
let authentication_type = match business_profile.three_ds_decision_manager_config.as_ref() {
Some(three_ds_decision_manager_config) => call_decision_manager(
state,
three_ds_decision_manager_config.clone(),
payment_data,
)?,
None => authentication_type,
};
if let Some(auth_type) = authentication_type {
payment_data.payment_attempt.authentication_type = auth_type;
}
Ok(())
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentConfirmData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedConfirmOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[cfg(feature = "v2")]
async fn perform_routing<'a>(
&'a self,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> {
payments::connector_selection(
state,
merchant_context,
business_profile,
payment_data,
None,
)
.await
}
#[instrument(skip_all)]
async fn populate_payment_data<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
_merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
connector_data: &api::ConnectorData,
) -> CustomResult<(), errors::ApiErrorResponse> {
let connector_request_reference_id = connector_data
.connector
.generate_connector_request_reference_id(
&payment_data.payment_intent,
&payment_data.payment_attempt,
);
payment_data.set_connector_request_reference_id(Some(connector_request_reference_id));
Ok(())
}
#[cfg(feature = "v2")]
async fn create_or_fetch_payment_method<'a>(
&'a self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut PaymentConfirmData<F>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let (payment_method, payment_method_data) = match (
&payment_data.payment_attempt.payment_token,
&payment_data.payment_method_data,
&payment_data.payment_attempt.customer_acceptance,
) {
(
Some(payment_token),
Some(domain::payment_method_data::PaymentMethodData::CardToken(card_token)),
None,
) => {
let (card_cvc, card_holder_name) = {
(
card_token
.card_cvc
.clone()
.ok_or(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card_cvc",
})
.or(
payment_methods::vault::retrieve_and_delete_cvc_from_payment_token(
state,
payment_token,
payment_data.payment_attempt.payment_method_type,
merchant_context.get_merchant_key_store().key.get_inner(),
)
.await,
)
.attach_printable("card_cvc not provided")?,
card_token.card_holder_name.clone(),
)
};
let (payment_method, vault_data) =
payment_methods::vault::retrieve_payment_method_from_vault_using_payment_token(
state,
merchant_context,
business_profile,
payment_token,
&payment_data.payment_attempt.payment_method_type,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from vault")?;
match vault_data {
domain::vault::PaymentMethodVaultingData::Card(card_detail) => {
let pm_data_from_vault =
domain::payment_method_data::PaymentMethodData::Card(
domain::payment_method_data::Card::from((
card_detail,
card_cvc,
card_holder_name,
)),
);
(Some(payment_method), Some(pm_data_from_vault))
}
_ => Err(errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
"Non-card Tokenization not implemented".to_string(),
),
})?,
}
}
(Some(_payment_token), _, _) => Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_method_data",
})
.attach_printable("payment_method_data should be card_token when a token is passed")?,
(None, Some(domain::PaymentMethodData::Card(card)), Some(_customer_acceptance)) => {
let customer_id = match &payment_data.payment_intent.customer_id {
Some(customer_id) => customer_id.clone(),
None => {
return Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_id",
})
.attach_printable("customer_id not provided");
}
};
let pm_create_data =
api::PaymentMethodCreateData::Card(api::CardDetail::from(card.clone()));
let req = api::PaymentMethodCreate {
payment_method_type: payment_data.payment_attempt.payment_method_type,
payment_method_subtype: payment_data.payment_attempt.payment_method_subtype,
metadata: None,
customer_id,
payment_method_data: pm_create_data,
billing: None,
psp_tokenization: None,
network_tokenization: None,
};
let (_pm_response, payment_method) =
Box::pin(payment_methods::create_payment_method_core(
state,
&state.get_req_state(),
req,
merchant_context,
business_profile,
))
.await?;
// Don't modify payment_method_data in this case, only the payment_method and payment_method_id
(Some(payment_method), None)
}
_ => (None, None), // Pass payment_data unmodified for any other case
};
if let Some(pm_data) = payment_method_data {
payment_data.update_payment_method_data(pm_data);
}
if let Some(pm) = payment_method {
payment_data.update_payment_method_and_pm_id(pm.get_id().clone(), pm);
}
Ok(())
}
#[cfg(feature = "v2")]
async fn get_connector_from_request<'a>(
&'a self,
state: &SessionState,
request: &PaymentsConfirmIntentRequest,
payment_data: &mut PaymentConfirmData<F>,
) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> {
let connector_data = helpers::get_connector_data_from_request(
state,
request.merchant_connector_details.clone(),
)
.await?;
payment_data
.set_connector_in_payment_attempt(Some(connector_data.connector_name.to_string()));
Ok(connector_data)
}
async fn get_connector_tokenization_action<'a>(
&'a self,
state: &SessionState,
payment_data: &PaymentConfirmData<F>,
) -> RouterResult<payments::TokenizationAction> {
let connector = payment_data.payment_attempt.connector.to_owned();
let is_connector_mandate_flow = payment_data
.mandate_data
.as_ref()
.and_then(|mandate_details| mandate_details.mandate_reference_id.as_ref())
.map(|mandate_reference| match mandate_reference {
api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true,
api_models::payments::MandateReferenceId::NetworkMandateId(_)
| api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_) => false,
})
.unwrap_or(false);
let tokenization_action = match connector {
Some(_) if is_connector_mandate_flow => {
payments::TokenizationAction::SkipConnectorTokenization
}
Some(connector) => {
let payment_method = payment_data
.payment_attempt
.get_payment_method()
.ok_or_else(|| errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method not found")?;
let payment_method_type: Option<common_enums::PaymentMethodType> =
payment_data.payment_attempt.get_payment_method_type();
let mandate_flow_enabled = payment_data.payment_intent.setup_future_usage;
let is_connector_tokenization_enabled =
payments::is_payment_method_tokenization_enabled_for_connector(
state,
&connector,
payment_method,
payment_method_type,
mandate_flow_enabled,
)?;
if is_connector_tokenization_enabled {
payments::TokenizationAction::TokenizeInConnector
} else {
payments::TokenizationAction::SkipConnectorTokenization
}
}
None => payments::TokenizationAction::SkipConnectorTokenization,
};
Ok(tokenization_action)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, PaymentsConfirmIntentRequest>
for PaymentIntentConfirm
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentConfirmData<F>,
customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentConfirmData<F>)>
where
F: 'b + Send,
{
let db = &*state.store;
let key_manager_state = &state.into();
let intent_status = common_enums::IntentStatus::Processing;
let attempt_status = common_enums::AttemptStatus::Pending;
let connector = payment_data
.payment_attempt
.connector
.clone()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector is none when constructing response")?;
// If `merchant_connector_details` are present in the payment request, `merchant_connector_id` will not be populated.
let merchant_connector_id = match &payment_data.merchant_connector_details {
Some(_details) => None,
None => Some(
payment_data
.payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector id is none when constructing response")?,
),
};
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent {
status: intent_status,
updated_by: storage_scheme.to_string(),
active_attempt_id: Some(payment_data.payment_attempt.id.clone()),
};
let authentication_type = payment_data.payment_attempt.authentication_type;
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone();
// Updates payment_attempt for cases where authorize flow is not performed.
let connector_response_reference_id = payment_data
.payment_attempt
.connector_response_reference_id
.clone();
let payment_attempt_update = match &payment_data.payment_method {
// In the case of a tokenized payment method, we update the payment attempt with the tokenized payment method details.
Some(payment_method) => {
hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntentTokenized {
status: attempt_status,
updated_by: storage_scheme.to_string(),
connector,
merchant_connector_id: merchant_connector_id.ok_or_else( || {
error_stack::report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector id is none when constructing response")
})?,
authentication_type,
connector_request_reference_id,
payment_method_id : payment_method.get_id().clone()
}
}
None => {
hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent {
status: attempt_status,
updated_by: storage_scheme.to_string(),
connector,
merchant_connector_id,
authentication_type,
connector_request_reference_id,
connector_response_reference_id,
}
}
};
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent.clone(),
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
payment_data.payment_intent = updated_payment_intent;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_attempt = updated_payment_attempt;
if let Some((customer, updated_customer)) = customer.zip(updated_customer) {
let customer_id = customer.get_id().clone();
let customer_merchant_id = customer.merchant_id.clone();
let _updated_customer = db
.update_customer_by_global_id(
key_manager_state,
&customer_id,
customer,
updated_customer,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update customer during `update_trackers`")?;
}
Ok((Box::new(self), payment_data))
}
}
| crates/router/src/core/payments/operations/payment_confirm_intent.rs | router::src::core::payments::operations::payment_confirm_intent | 5,529 | true |
// File: crates/router/src/core/payments/operations/payments_incremental_authorization.rs
// Module: router::src::core::payments::operations::payments_incremental_authorization
use std::marker::PhantomData;
use api_models::{enums::FrmSuggestion, payments::PaymentsIncrementalAuthorizationRequest};
use async_trait::async_trait;
use common_utils::errors::CustomResult;
use diesel_models::authorization::AuthorizationNew;
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{
self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails,
PaymentAddress,
},
},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "incremental_authorization")]
pub struct PaymentIncrementalAuthorization;
type PaymentIncrementalAuthorizationOperation<'b, F> =
BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync>
GetTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest>
for PaymentIncrementalAuthorization
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &PaymentsIncrementalAuthorizationRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<
'a,
F,
PaymentsIncrementalAuthorizationRequest,
payments::PaymentData<F>,
>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[enums::IntentStatus::RequiresCapture],
"increment authorization",
)?;
if payment_intent.incremental_authorization_allowed != Some(true) {
Err(errors::ApiErrorResponse::PreconditionFailed {
message:
"You cannot increment authorization this payment because it is not allowed for incremental_authorization".to_owned(),
})?
}
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().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// Incremental authorization should be performed on an amount greater than the original authorized amount (in this case, greater than the net_amount which is sent for authorization)
// request.amount is the total amount that should be authorized in incremental authorization which should be greater than the original authorized amount
if payment_attempt.get_total_amount() >= request.amount {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Amount should be greater than original authorized amount".to_owned(),
})?
}
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount();
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = payments::PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount: amount.into(),
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: PaymentAddress::new(None, None, None, None),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: Some(IncrementalAuthorizationDetails {
additional_amount: request.amount - amount,
total_amount: request.amount,
reason: request.reason.clone(),
authorization_id: None,
}),
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync>
UpdateTracker<F, payments::PaymentData<F>, PaymentsIncrementalAuthorizationRequest>
for PaymentIncrementalAuthorization
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: payments::PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentIncrementalAuthorizationOperation<'b, F>,
payments::PaymentData<F>,
)>
where
F: 'b + Send,
{
let new_authorization_count = payment_data
.payment_intent
.authorization_count
.map(|count| count + 1)
.unwrap_or(1);
// Create new authorization record
let authorization_new = AuthorizationNew {
authorization_id: format!(
"{}_{}",
common_utils::generate_id_with_default_len("auth"),
new_authorization_count
),
merchant_id: payment_data.payment_intent.merchant_id.clone(),
payment_id: payment_data.payment_intent.payment_id.clone(),
amount: payment_data
.incremental_authorization_details
.clone()
.map(|details| details.total_amount)
.ok_or(
report!(errors::ApiErrorResponse::InternalServerError).attach_printable(
"missing incremental_authorization_details in payment_data",
),
)?,
status: common_enums::AuthorizationStatus::Processing,
error_code: None,
error_message: None,
connector_authorization_id: None,
previously_authorized_amount: payment_data.payment_attempt.get_total_amount(),
};
let authorization = state
.store
.insert_authorization(authorization_new.clone())
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: format!(
"Authorization with authorization_id {} already exists",
authorization_new.authorization_id
),
})
.attach_printable("failed while inserting new authorization")?;
// Update authorization_count in payment_intent
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent.clone(),
storage::PaymentIntentUpdate::AuthorizationCountUpdate {
authorization_count: new_authorization_count,
},
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Failed to update authorization_count in Payment Intent")?;
match &payment_data.incremental_authorization_details {
Some(details) => {
payment_data.incremental_authorization_details =
Some(IncrementalAuthorizationDetails {
authorization_id: Some(authorization.authorization_id),
..details.clone()
});
}
None => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing incremental_authorization_details in payment_data")?,
}
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>>
for PaymentIncrementalAuthorization
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &PaymentsIncrementalAuthorizationRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
PaymentIncrementalAuthorizationOperation<'b, F>,
operations::ValidateResult,
)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
#[async_trait]
impl<F: Clone + Send + Sync>
Domain<F, PaymentsIncrementalAuthorizationRequest, payments::PaymentData<F>>
for PaymentIncrementalAuthorization
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut payments::PaymentData<F>,
_request: Option<CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<
'a,
F,
PaymentsIncrementalAuthorizationRequest,
payments::PaymentData<F>,
>,
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 payments::PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentIncrementalAuthorizationOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
_request: &PaymentsIncrementalAuthorizationRequest,
_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,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut payments::PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
| crates/router/src/core/payments/operations/payments_incremental_authorization.rs | router::src::core::payments::operations::payments_incremental_authorization | 2,791 | true |
// File: crates/router/src/core/payments/operations/payment_reject.rs
// Module: router::src::core::payments::operations::payment_reject
use std::marker::PhantomData;
use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest};
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentAddress, PaymentData},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "cancel")]
pub struct PaymentReject;
type PaymentRejectOperation<'b, F> = BoxedOperation<'b, F, PaymentsCancelRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest>
for PaymentReject
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
_request: &PaymentsCancelRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>>
{
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::Cancelled,
enums::IntentStatus::Failed,
enums::IntentStatus::Succeeded,
enums::IntentStatus::Processing,
],
"reject",
)?;
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().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
let frm_response = if cfg!(feature = "frm") {
db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id().clone())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_context.get_merchant_account().get_id())
})
.ok()
} else {
None
};
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
address: PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
token_data: None,
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: frm_response,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_should_decline_transaction: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentRejectOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let intent_status_update = storage::PaymentIntentUpdate::RejectUpdate {
status: enums::IntentStatus::Failed,
merchant_decision: Some(enums::MerchantDecision::Rejected.to_string()),
updated_by: storage_scheme.to_string(),
};
let (error_code, error_message) =
payment_data
.frm_message
.clone()
.map_or((None, None), |fraud_check| {
(
Some(Some(fraud_check.frm_status.to_string())),
Some(fraud_check.frm_reason.map(|reason| reason.to_string())),
)
});
let attempt_status_update = storage::PaymentAttemptUpdate::RejectUpdate {
status: enums::AttemptStatus::Failure,
error_code,
error_message,
updated_by: storage_scheme.to_string(),
};
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
intent_status_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
attempt_status_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let error_code = payment_data.payment_attempt.error_code.clone();
let error_message = payment_data.payment_attempt.error_message.clone();
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentReject {
error_code,
error_message,
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsCancelRequest, PaymentData<F>>
for PaymentReject
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &PaymentsCancelRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentRejectOperation<'b, F>, operations::ValidateResult)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| crates/router/src/core/payments/operations/payment_reject.rs | router::src::core::payments::operations::payment_reject | 2,265 | true |
// File: crates/router/src/core/payments/operations/payment_capture_v2.rs
// Module: router::src::core::payments::operations::payment_capture_v2
use api_models::{enums::FrmSuggestion, payments::PaymentsCaptureRequest};
use async_trait::async_trait;
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::PaymentCaptureData;
use router_env::{instrument, tracing};
use super::{Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{
helpers,
operations::{self, ValidateStatusForOperation},
},
},
routes::{app::ReqState, SessionState},
types::{
api::{self, ConnectorCallType},
domain::{self},
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentsCapture;
impl ValidateStatusForOperation for PaymentsCapture {
/// Validate if the current operation can be performed on the current status of the payment intent
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => 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::RequiresPaymentMethod
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: [
common_enums::IntentStatus::RequiresCapture,
common_enums::IntentStatus::PartiallyCapturedAndCapturable,
]
.map(|enum_value| enum_value.to_string())
.join(", "),
})
}
}
}
}
type BoxedConfirmOperation<'b, F> =
super::BoxedOperation<'b, F, PaymentsCaptureRequest, PaymentCaptureData<F>>;
// TODO: change the macro to include changes for v2
// TODO: PaymentData in the macro should be an input
impl<F: Send + Clone> Operation<F, PaymentsCaptureRequest> for &PaymentsCapture {
type Data = PaymentCaptureData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentsCaptureRequest, Self::Data> + Send + Sync)>
{
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCaptureRequest> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsCaptureRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCaptureRequest> + Send + Sync)>
{
Ok(*self)
}
}
#[automatically_derived]
impl<F: Send + Clone> Operation<F, PaymentsCaptureRequest> for PaymentsCapture {
type Data = PaymentCaptureData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentsCaptureRequest, Self::Data> + Send + Sync)>
{
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCaptureRequest> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsCaptureRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCaptureRequest> + Send + Sync)>
{
Ok(self)
}
}
impl<F: Send + Clone> ValidateRequest<F, PaymentsCaptureRequest, PaymentCaptureData<F>>
for PaymentsCapture
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &PaymentsCaptureRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
let validate_result = operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
};
Ok(validate_result)
}
}
#[async_trait]
impl<F: Send + Clone> GetTracker<F, PaymentCaptureData<F>, PaymentsCaptureRequest>
for PaymentsCapture
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &PaymentsCaptureRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<PaymentCaptureData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let active_attempt_id = payment_intent
.active_attempt_id
.as_ref()
.get_required_value("active_attempt_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Active attempt id is none when capturing the payment")?;
let mut payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
active_attempt_id,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not find payment attempt given the attempt id")?;
if let Some(amount_to_capture) = request.amount_to_capture {
payment_attempt
.amount_details
.validate_amount_to_capture(amount_to_capture)
.change_context(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"`amount_to_capture` is greater than the net amount {}",
payment_attempt.amount_details.get_net_amount()
),
})?;
payment_attempt
.amount_details
.set_amount_to_capture(amount_to_capture);
}
let payment_data = PaymentCaptureData {
flow: std::marker::PhantomData,
payment_intent,
payment_attempt,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send> Domain<F, PaymentsCaptureRequest, PaymentCaptureData<F>> for PaymentsCapture {
async fn get_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentCaptureData<F>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
match payment_data.payment_intent.customer_id.clone() {
Some(id) => {
let customer = state
.store
.find_customer_by_global_id(
&state.into(),
&id,
merchant_key_store,
storage_scheme,
)
.await?;
Ok((Box::new(self), Some(customer)))
}
None => Ok((Box::new(self), None)),
}
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut PaymentCaptureData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedConfirmOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn perform_routing<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
state: &SessionState,
// TODO: do not take the whole payment data here
payment_data: &mut PaymentCaptureData<F>,
) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> {
let payment_attempt = &payment_data.payment_attempt;
let connector = payment_attempt
.connector
.as_ref()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector is none when constructing response")?;
let merchant_connector_id = payment_attempt
.merchant_connector_id
.as_ref()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector id is none when constructing response")?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
Some(merchant_connector_id.to_owned()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
Ok(ConnectorCallType::PreDetermined(connector_data.into()))
}
}
#[async_trait]
impl<F: Clone> UpdateTracker<F, PaymentCaptureData<F>, PaymentsCaptureRequest> for PaymentsCapture {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: PaymentCaptureData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentCaptureData<F>)>
where
F: 'b + Send,
{
let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::PreCaptureUpdate { amount_to_capture: payment_data.payment_attempt.amount_details.get_amount_to_capture(), updated_by: storage_scheme.to_string() };
let payment_attempt = state
.store
.update_payment_attempt(
&state.into(),
key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not update payment attempt")?;
payment_data.payment_attempt = payment_attempt;
Ok((Box::new(self), payment_data))
}
}
| crates/router/src/core/payments/operations/payment_capture_v2.rs | router::src::core::payments::operations::payment_capture_v2 | 2,618 | true |
// File: crates/router/src/core/payments/operations/payment_update_metadata.rs
// Module: router::src::core::payments::operations::payment_update_metadata
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::types::keymanager::KeyManagerState;
use error_stack::ResultExt;
use masking::ExposeInterface;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "update_metadata")]
pub struct PaymentUpdateMetadata;
type PaymentUpdateMetadataOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsUpdateMetadataRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMetadataRequest>
for PaymentUpdateMetadata
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsUpdateMetadataRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<'a, F, api::PaymentsUpdateMetadataRequest, PaymentData<F>>,
> {
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let db = &*state.store;
let key_manager_state: &KeyManagerState = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let mut payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Succeeded,
storage_enums::IntentStatus::Failed,
storage_enums::IntentStatus::PartiallyCaptured,
storage_enums::IntentStatus::PartiallyCapturedAndCapturable,
storage_enums::IntentStatus::RequiresCapture,
],
"update_metadata",
)?;
let payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let currency = payment_intent.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let merged_metadata = payment_intent
.merge_metadata(request.metadata.clone().expose())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Metadata should be an object and contain at least 1 key".to_owned(),
})?;
payment_intent.metadata = Some(merged_metadata);
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
customer_acceptance: None,
token: None,
token_data: None,
setup_mandate: None,
address: payments::PaymentAddress::new(None, None, None, None),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsUpdateMetadataRequest, PaymentData<F>>
for PaymentUpdateMetadata
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> errors::CustomResult<
(
PaymentUpdateMetadataOperation<'a, F>,
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 PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentUpdateMetadataOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
_request: &api::PaymentsUpdateMetadataRequest,
_payment_intent: &storage::PaymentIntent,
) -> errors::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,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsUpdateMetadataRequest>
for PaymentUpdateMetadata
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentUpdateMetadataOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsUpdateMetadataRequest, PaymentData<F>>
for PaymentUpdateMetadata
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsUpdateMetadataRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
PaymentUpdateMetadataOperation<'b, F>,
operations::ValidateResult,
)> {
//payment id is already generated and should be sent in the request
let given_payment_id = request.payment_id.clone();
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| crates/router/src/core/payments/operations/payment_update_metadata.rs | router::src::core::payments::operations::payment_update_metadata | 2,192 | true |
// File: crates/router/src/core/payments/operations/payment_approve.rs
// Module: router::src::core::payments::operations::payment_approve
use std::marker::PhantomData;
use api_models::enums::{AttemptStatus, FrmSuggestion, IntentStatus};
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentData},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
PaymentAddress,
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "capture")]
pub struct PaymentApprove;
type PaymentApproveOperation<'a, F> =
BoxedOperation<'a, F, api::PaymentsCaptureRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest>
for PaymentApprove
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
_request: &api::PaymentsCaptureRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest, PaymentData<F>>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let (mut payment_intent, payment_attempt, currency, amount);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[IntentStatus::Failed, IntentStatus::Succeeded],
"approve",
)?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let attempt_id = payment_intent.active_attempt.get_id().clone();
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
&attempt_id.clone(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
let frm_response = if cfg!(feature = "frm") {
db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id().clone())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", merchant_context.get_merchant_account().get_id().get_string_repr())
})
.ok()
} else {
None
};
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: frm_response,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest>
for PaymentApprove
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentApproveOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
if matches!(frm_suggestion, Some(FrmSuggestion::FrmAuthorizeTransaction)) {
payment_data.payment_intent.status = IntentStatus::RequiresCapture; // In Approve flow, payment which has payment_capture_method "manual" and attempt status as "Unresolved",
payment_data.payment_attempt.status = AttemptStatus::Authorized; // We shouldn't call the connector instead we need to update the payment attempt and payment intent.
}
let intent_status_update = storage::PaymentIntentUpdate::ApproveUpdate {
status: payment_data.payment_intent.status,
merchant_decision: Some(api_models::enums::MerchantDecision::Approved.to_string()),
updated_by: storage_scheme.to_string(),
};
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
intent_status_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
storage::PaymentAttemptUpdate::StatusUpdate {
status: payment_data.payment_attempt.status,
updated_by: storage_scheme.to_string(),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentApprove))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsCaptureRequest, PaymentData<F>>
for PaymentApprove
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCaptureRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentApproveOperation<'b, F>, operations::ValidateResult)> {
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.clone()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| crates/router/src/core/payments/operations/payment_approve.rs | router::src::core::payments::operations::payment_approve | 2,359 | true |
// File: crates/router/src/core/payments/operations/payment_response.rs
// Module: router::src::core::payments::operations::payment_response
use std::{collections::HashMap, ops::Deref};
use api_models::payments::{ConnectorMandateReferenceId, MandateReferenceId};
#[cfg(feature = "dynamic_routing")]
use api_models::routing::RoutableConnectorChoice;
use async_trait::async_trait;
use common_enums::AuthorizationStatus;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use common_utils::ext_traits::ValueExt;
use common_utils::{
ext_traits::{AsyncExt, Encode},
types::{keymanager::KeyManagerState, ConnectorTransactionId, MinorUnit},
};
use error_stack::{report, ResultExt};
use futures::FutureExt;
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::{
PaymentConfirmData, PaymentIntentData, PaymentStatusData,
};
use router_derive;
use router_env::{instrument, logger, tracing};
use storage_impl::DataModelExt;
use tracing_futures::Instrument;
use super::{Operation, OperationSessionSetters, PostUpdateTracker};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use crate::core::routing::helpers as routing_helpers;
#[cfg(feature = "v2")]
use crate::utils::OptionExt;
use crate::{
connector::utils::PaymentResponseRouterData,
consts,
core::{
card_testing_guard::utils as card_testing_guard_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate,
payment_methods::{self, cards::create_encrypted_data},
payments::{
helpers::{
self as payments_helpers,
update_additional_payment_data_with_connector_response_pm_data,
},
tokenization,
types::MultipleCaptureData,
PaymentData, PaymentMethodChecker,
},
utils as core_utils,
},
routes::{metrics, SessionState},
types::{
self, domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignTryFrom},
CaptureSyncResponse, ErrorResponse,
},
utils,
};
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(
operations = "post_update_tracker",
flow = "sync_data, cancel_data, authorize_data, capture_data, complete_authorize_data, approve_data, reject_data, setup_mandate_data, session_data,incremental_authorization_data, sdk_session_update_data, post_session_tokens_data, update_metadata_data, cancel_post_capture_data, extend_authorization_data"
)]
pub struct PaymentResponse;
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Copy)]
pub struct PaymentResponse;
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b,
{
payment_data.mandate_id = payment_data
.mandate_id
.or_else(|| router_data.request.mandate_id.clone());
// update setup_future_usage incase it is downgraded to on-session
payment_data.payment_attempt.setup_future_usage_applied =
router_data.request.setup_future_usage;
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
#[cfg(feature = "v2")]
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
resp: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
todo!()
}
#[cfg(feature = "v1")]
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
resp: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
let customer_id = payment_data.payment_intent.customer_id.clone();
let save_payment_data = tokenization::SavePaymentMethodData::from(resp);
let payment_method_billing_address = payment_data.address.get_payment_method_billing();
let connector_name = payment_data
.payment_attempt
.connector
.clone()
.ok_or_else(|| {
logger::error!("Missing required Param connector_name");
errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector_name",
}
})?;
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let billing_name = resp
.address
.get_payment_method_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|address| address.get_optional_full_name());
let mut should_avoid_saving = false;
let vault_operation = payment_data.vault_operation.clone();
let payment_method_info = payment_data.payment_method_info.clone();
if let Some(payment_method_info) = &payment_data.payment_method_info {
if payment_data.payment_intent.off_session.is_none() && resp.response.is_ok() {
should_avoid_saving = resp.request.payment_method_type
== Some(enums::PaymentMethodType::ApplePay)
|| resp.request.payment_method_type
== Some(enums::PaymentMethodType::GooglePay);
payment_methods::cards::update_last_used_at(
payment_method_info,
state,
merchant_context.get_merchant_account().storage_scheme,
merchant_context.get_merchant_key_store(),
)
.await
.map_err(|e| {
logger::error!("Failed to update last used at: {:?}", e);
})
.ok();
}
};
let connector_mandate_reference_id = payment_data
.payment_attempt
.connector_mandate_detail
.as_ref()
.map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone()));
let save_payment_call_future = Box::pin(tokenization::save_payment_method(
state,
connector_name.clone(),
save_payment_data,
customer_id.clone(),
merchant_context,
resp.request.payment_method_type,
billing_name.clone(),
payment_method_billing_address,
business_profile,
connector_mandate_reference_id.clone(),
merchant_connector_id.clone(),
vault_operation.clone(),
payment_method_info.clone(),
));
let is_connector_mandate = resp.request.customer_acceptance.is_some()
&& matches!(
resp.request.setup_future_usage,
Some(enums::FutureUsage::OffSession)
);
let is_legacy_mandate = resp.request.setup_mandate_details.is_some()
&& matches!(
resp.request.setup_future_usage,
Some(enums::FutureUsage::OffSession)
);
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
if is_legacy_mandate {
// Mandate is created on the application side and at the connector.
let tokenization::SavePaymentMethodDataResponse {
payment_method_id, ..
} = save_payment_call_future.await?;
let mandate_id = mandate::mandate_procedure(
state,
resp,
&customer_id.clone(),
payment_method_id.clone(),
merchant_connector_id.clone(),
merchant_context.get_merchant_account().storage_scheme,
payment_data.payment_intent.get_id(),
)
.await?;
payment_data.payment_attempt.payment_method_id = payment_method_id;
payment_data.payment_attempt.mandate_id = mandate_id;
Ok(())
} else if is_connector_mandate {
// The mandate is created on connector's end.
let tokenization::SavePaymentMethodDataResponse {
payment_method_id,
connector_mandate_reference_id,
..
} = save_payment_call_future.await?;
payment_data.payment_method_info = if let Some(payment_method_id) = &payment_method_id {
match state
.store
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
storage_scheme,
)
.await
{
Ok(payment_method) => Some(payment_method),
Err(error) => {
if error.current_context().is_db_not_found() {
logger::info!("Payment Method not found in db {:?}", error);
None
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error retrieving payment method from db")
.map_err(|err| logger::error!(payment_method_retrieve=?err))
.ok()
}
}
}
} else {
None
};
payment_data.payment_attempt.payment_method_id = payment_method_id;
payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
.clone()
.map(ForeignFrom::foreign_from);
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
MandateReferenceId::ConnectorMandateId(connector_mandate_id)
}),
});
Ok(())
} else if should_avoid_saving {
if let Some(pm_info) = &payment_data.payment_method_info {
payment_data.payment_attempt.payment_method_id = Some(pm_info.get_id().clone());
};
Ok(())
} else {
// Save card flow
let save_payment_data = tokenization::SavePaymentMethodData::from(resp);
let state = state.clone();
let customer_id = payment_data.payment_intent.customer_id.clone();
let payment_attempt = payment_data.payment_attempt.clone();
let business_profile = business_profile.clone();
let payment_method_type = resp.request.payment_method_type;
let payment_method_billing_address = payment_method_billing_address.cloned();
let cloned_merchant_context = merchant_context.clone();
logger::info!("Call to save_payment_method in locker");
let _task_handle = tokio::spawn(
async move {
logger::info!("Starting async call to save_payment_method in locker");
let result = Box::pin(tokenization::save_payment_method(
&state,
connector_name,
save_payment_data,
customer_id,
&cloned_merchant_context,
payment_method_type,
billing_name,
payment_method_billing_address.as_ref(),
&business_profile,
connector_mandate_reference_id,
merchant_connector_id.clone(),
vault_operation.clone(),
payment_method_info.clone(),
))
.await;
if let Err(err) = result {
logger::error!("Asynchronously saving card in locker failed : {:?}", err);
} else if let Ok(tokenization::SavePaymentMethodDataResponse {
payment_method_id,
..
}) = result
{
let payment_attempt_update =
storage::PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
updated_by: storage_scheme.clone().to_string(),
};
#[cfg(feature = "v1")]
let respond = state
.store
.update_payment_attempt_with_attempt_id(
payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await;
#[cfg(feature = "v2")]
let respond = state
.store
.update_payment_attempt_with_attempt_id(
&(&state).into(),
&key_store,
payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await;
if let Err(err) = respond {
logger::error!("Error updating payment attempt: {:?}", err);
};
}
}
.in_current_span(),
);
Ok(())
}
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsIncrementalAuthorizationData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::PaymentsIncrementalAuthorizationData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
_locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
_business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
let incremental_authorization_details = payment_data
.incremental_authorization_details
.clone()
.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing incremental_authorization_details in payment_data")
})?;
// Update payment_intent and payment_attempt 'amount' if incremental_authorization is successful
let (option_payment_attempt_update, option_payment_intent_update) = match router_data
.response
.clone()
{
Err(_) => (None, None),
Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse {
status, ..
}) => {
if status == AuthorizationStatus::Success {
(
Some(
storage::PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
// Internally, `NetAmount` is computed as (order_amount + additional_amount), so we subtract here to avoid double-counting.
incremental_authorization_details.total_amount - payment_data.payment_attempt.net_amount.get_additional_amount(),
None,
None,
None,
None,
),
amount_capturable: incremental_authorization_details.total_amount,
},
),
Some(
storage::PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate {
amount: incremental_authorization_details.total_amount - payment_data.payment_attempt.net_amount.get_additional_amount(),
},
),
)
} else {
(None, None)
}
}
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unexpected response in incremental_authorization flow")?,
};
//payment_attempt update
if let Some(payment_attempt_update) = option_payment_attempt_update {
#[cfg(feature = "v1")]
{
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
#[cfg(feature = "v2")]
{
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
&state.into(),
key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
}
// payment_intent update
if let Some(payment_intent_update) = option_payment_intent_update {
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent.clone(),
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
// Update the status of authorization record
let authorization_update = match &router_data.response {
Err(res) => Ok(storage::AuthorizationUpdate::StatusUpdate {
status: AuthorizationStatus::Failure,
error_code: Some(res.code.clone()),
error_message: Some(res.message.clone()),
connector_authorization_id: None,
}),
Ok(types::PaymentsResponseData::IncrementalAuthorizationResponse {
status,
error_code,
error_message,
connector_authorization_id,
}) => Ok(storage::AuthorizationUpdate::StatusUpdate {
status: status.clone(),
error_code: error_code.clone(),
error_message: error_message.clone(),
connector_authorization_id: connector_authorization_id.clone(),
}),
Ok(_) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unexpected response in incremental_authorization flow"),
}?;
let authorization_id = incremental_authorization_details
.authorization_id
.clone()
.ok_or(
report!(errors::ApiErrorResponse::InternalServerError).attach_printable(
"missing authorization_id in incremental_authorization_details in payment_data",
),
)?;
state
.store
.update_authorization_by_merchant_id_authorization_id(
router_data.merchant_id.clone(),
authorization_id,
authorization_update,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed while updating authorization")?;
//Fetch all the authorizations of the payment and send in incremental authorization response
let authorizations = state
.store
.find_all_authorizations_by_merchant_id_payment_id(
&router_data.merchant_id,
payment_data.payment_intent.get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed while retrieving authorizations")?;
payment_data.authorizations = authorizations;
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for PaymentResponse {
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
payment_data: PaymentData<F>,
router_data: types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await
}
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
resp: &types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
_business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = resp
.response
.clone()
.ok()
.and_then(|resp| {
if let types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
} = resp
{
mandate_reference.map(|mandate_ref| {
(
mandate_ref.connector_mandate_id.clone(),
mandate_ref.mandate_metadata.clone(),
mandate_ref.connector_mandate_request_reference_id.clone(),
)
})
} else {
None
}
})
.unwrap_or((None, None, None));
update_connector_mandate_details_for_the_flow(
connector_mandate_id,
mandate_metadata,
connector_mandate_request_reference_id,
payment_data,
)?;
update_payment_method_status_and_ntid(
state,
merchant_context.get_merchant_key_store(),
payment_data,
resp.status,
resp.response.clone(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
Ok(())
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSessionData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<F, types::PaymentsSessionData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SdkPaymentsSessionUpdateData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::SdkPaymentsSessionUpdateData,
types::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<PaymentData<F>>
where
F: 'b + Send,
{
let connector = payment_data
.payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("connector not found")?;
let key_manager_state = db.into();
// For PayPal, if we call TaxJar for tax calculation, we need to call the connector again to update the order amount so that we can confirm the updated amount and order details. Therefore, we will store the required changes in the database during the post_update_tracker call.
if payment_data.should_update_in_post_update_tracker() {
match router_data.response.clone() {
Ok(types::PaymentsResponseData::PaymentResourceUpdateResponse { status }) => {
if status.is_success() {
let shipping_address = payment_data
.tax_data
.clone()
.map(|tax_data| tax_data.shipping_details);
let shipping_details = shipping_address
.clone()
.async_map(|shipping_details| {
create_encrypted_data(
&key_manager_state,
key_store,
shipping_details,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt shipping details")?;
let shipping_address =
payments_helpers::create_or_update_address_for_payment_by_request(
db,
shipping_address.map(From::from).as_ref(),
payment_data.payment_intent.shipping_address_id.as_deref(),
&payment_data.payment_intent.merchant_id,
payment_data.payment_intent.customer_id.as_ref(),
key_store,
&payment_data.payment_intent.payment_id,
storage_scheme,
)
.await?;
let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::SessionResponseUpdate {
tax_details: payment_data.payment_intent.tax_details.clone().ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("payment_intent.tax_details not found")?,
shipping_address_id: shipping_address.map(|address| address.address_id),
updated_by: payment_data.payment_intent.updated_by.clone(),
shipping_details,
};
let m_db = db.clone().store;
let payment_intent = payment_data.payment_intent.clone();
let key_manager_state: KeyManagerState = db.into();
let updated_payment_intent = m_db
.update_payment_intent(
&key_manager_state,
payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_intent = updated_payment_intent;
} else {
router_data.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector,
status_code: err.status_code,
reason: err.reason,
}
})?;
}
}
Err(err) => {
Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector,
status_code: err.status_code,
reason: err.reason,
})?;
}
_ => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response in session_update flow")?;
}
}
}
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsPostSessionTokensData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::PaymentsPostSessionTokensData,
types::PaymentsResponseData,
>,
_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
_locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
_business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
match router_data.response.clone() {
Ok(types::PaymentsResponseData::TransactionResponse {
connector_metadata, ..
}) => {
let m_db = db.clone().store;
let payment_attempt_update =
storage::PaymentAttemptUpdate::PostSessionTokensUpdate {
updated_by: storage_scheme.clone().to_string(),
connector_metadata,
};
let updated_payment_attempt = m_db
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_attempt = updated_payment_attempt;
}
Err(err) => {
logger::error!("Invalid request sent to connector: {:?}", err);
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid request sent to connector".to_string(),
})?;
}
_ => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response in PostSessionTokens flow")?;
}
}
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsUpdateMetadataData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::PaymentsUpdateMetadataData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
_locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
_business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
let connector = payment_data
.payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("connector not found in payment_attempt")?;
match router_data.response.clone() {
Ok(types::PaymentsResponseData::PaymentResourceUpdateResponse { status, .. }) => {
if status.is_success() {
let m_db = db.clone().store;
let payment_intent = payment_data.payment_intent.clone();
let key_manager_state: KeyManagerState = db.into();
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::MetadataUpdate {
metadata: payment_data
.payment_intent
.metadata
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("payment_intent.metadata not found")?,
updated_by: payment_data.payment_intent.updated_by.clone(),
};
let updated_payment_intent = m_db
.update_payment_intent(
&key_manager_state,
payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_intent = updated_payment_intent;
} else {
router_data.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector,
status_code: err.status_code,
reason: err.reason,
}
})?;
}
}
Err(err) => {
Err(errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector,
status_code: err.status_code,
reason: err.reason,
})?;
}
_ => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unexpected response in Update Metadata flow")?;
}
}
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> for PaymentResponse {
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelPostCaptureData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::PaymentsCancelPostCaptureData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsExtendAuthorizationData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::PaymentsExtendAuthorizationData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsApproveData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<F, types::PaymentsApproveData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsRejectData> for PaymentResponse {
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<F, types::PaymentsRejectData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SetupMandateRequestData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<
F,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
payment_data.mandate_id = payment_data.mandate_id.or_else(|| {
router_data.request.mandate_id.clone()
// .map(api_models::payments::MandateIds::new)
});
payment_data = Box::pin(payment_response_update_tracker(
db,
payment_data,
router_data,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await?;
Ok(payment_data)
}
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
resp: &types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
let payment_method_billing_address = payment_data.address.get_payment_method_billing();
let billing_name = resp
.address
.get_payment_method_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|address| address.get_optional_full_name());
let save_payment_data = tokenization::SavePaymentMethodData::from(resp);
let customer_id = payment_data.payment_intent.customer_id.clone();
let connector_name = payment_data
.payment_attempt
.connector
.clone()
.ok_or_else(|| {
logger::error!("Missing required Param connector_name");
errors::ApiErrorResponse::MissingRequiredField {
field_name: "connector_name",
}
})?;
let connector_mandate_reference_id = payment_data
.payment_attempt
.connector_mandate_detail
.as_ref()
.map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone()));
let vault_operation = payment_data.vault_operation.clone();
let payment_method_info = payment_data.payment_method_info.clone();
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let tokenization::SavePaymentMethodDataResponse {
payment_method_id,
connector_mandate_reference_id,
..
} = Box::pin(tokenization::save_payment_method(
state,
connector_name,
save_payment_data,
customer_id.clone(),
merchant_context,
resp.request.payment_method_type,
billing_name,
payment_method_billing_address,
business_profile,
connector_mandate_reference_id,
merchant_connector_id.clone(),
vault_operation,
payment_method_info,
))
.await?;
payment_data.payment_method_info = if let Some(payment_method_id) = &payment_method_id {
match state
.store
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
{
Ok(payment_method) => Some(payment_method),
Err(error) => {
if error.current_context().is_db_not_found() {
logger::info!("Payment Method not found in db {:?}", error);
None
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error retrieving payment method from db")
.map_err(|err| logger::error!(payment_method_retrieve=?err))
.ok()
}
}
}
} else {
None
};
let mandate_id = mandate::mandate_procedure(
state,
resp,
&customer_id,
payment_method_id.clone(),
merchant_connector_id.clone(),
merchant_context.get_merchant_account().storage_scheme,
payment_data.payment_intent.get_id(),
)
.await?;
payment_data.payment_attempt.payment_method_id = payment_method_id;
payment_data.payment_attempt.mandate_id = mandate_id;
payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
.clone()
.map(ForeignFrom::foreign_from);
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
MandateReferenceId::ConnectorMandateId(connector_mandate_id)
}),
});
Ok(())
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::CompleteAuthorizeData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
db: &'b SessionState,
payment_data: PaymentData<F>,
response: types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connector: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
Box::pin(payment_response_update_tracker(
db,
payment_data,
response,
key_store,
storage_scheme,
locale,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
routable_connector,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
business_profile,
))
.await
}
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
resp: &types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
_business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
let (connector_mandate_id, mandate_metadata, connector_mandate_request_reference_id) = resp
.response
.clone()
.ok()
.and_then(|resp| {
if let types::PaymentsResponseData::TransactionResponse {
mandate_reference, ..
} = resp
{
mandate_reference.map(|mandate_ref| {
(
mandate_ref.connector_mandate_id.clone(),
mandate_ref.mandate_metadata.clone(),
mandate_ref.connector_mandate_request_reference_id.clone(),
)
})
} else {
None
}
})
.unwrap_or((None, None, None));
update_connector_mandate_details_for_the_flow(
connector_mandate_id,
mandate_metadata,
connector_mandate_request_reference_id,
payment_data,
)?;
update_payment_method_status_and_ntid(
state,
merchant_context.get_merchant_key_store(),
payment_data,
resp.status,
resp.response.clone(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
Ok(())
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
state: &SessionState,
mut payment_data: PaymentData<F>,
router_data: types::RouterData<F, T, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
locale: &Option<String>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] routable_connectors: Vec<
RoutableConnectorChoice,
>,
#[cfg(all(feature = "v1", feature = "dynamic_routing"))] business_profile: &domain::Profile,
) -> RouterResult<PaymentData<F>> {
// Update additional payment data with the payment method response that we received from connector
// This is for details like whether 3ds was upgraded and which version of 3ds was used
// also some connectors might send card network details in the response, which is captured and stored
let additional_payment_data = payment_data.payment_attempt.get_payment_method_data();
let additional_payment_method_data = match payment_data.payment_method_data.clone() {
Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::NetworkToken(_))
| Some(hyperswitch_domain_models::payment_method_data::PaymentMethodData::CardDetailsForNetworkTransactionId(_)) => {
payment_data.payment_attempt.payment_method_data.clone()
}
_ => {
additional_payment_data
.map(|_| {
update_additional_payment_data_with_connector_response_pm_data(
payment_data.payment_attempt.payment_method_data.clone(),
router_data
.connector_response
.as_ref()
.and_then(|connector_response| {
connector_response.additional_payment_method_data.clone()
}),
)
})
.transpose()?
.flatten()
}
};
router_data.payment_method_status.and_then(|status| {
payment_data
.payment_method_info
.as_mut()
.map(|info| info.status = status)
});
payment_data.whole_connector_response = router_data.raw_connector_response.clone();
// TODO: refactor of gsm_error_category with respective feature flag
#[allow(unused_variables)]
let (capture_update, mut payment_attempt_update, gsm_error_category) = match router_data
.response
.clone()
{
Err(err) => {
let auth_update = if Some(router_data.auth_type)
!= payment_data.payment_attempt.authentication_type
{
Some(router_data.auth_type)
} else {
None
};
let (capture_update, attempt_update, gsm_error_category) =
match payment_data.multiple_capture_data {
Some(multiple_capture_data) => {
let capture_update = storage::CaptureUpdate::ErrorUpdate {
status: match err.status_code {
500..=511 => enums::CaptureStatus::Pending,
_ => enums::CaptureStatus::Failed,
},
error_code: Some(err.code),
error_message: Some(err.message),
error_reason: err.reason,
};
let capture_update_list = vec![(
multiple_capture_data.get_latest_capture().clone(),
capture_update,
)];
(
Some((multiple_capture_data, capture_update_list)),
auth_update.map(|auth_type| {
storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type: auth_type,
updated_by: storage_scheme.to_string(),
}
}),
None,
)
}
None => {
let connector_name = router_data.connector.to_string();
let flow_name = core_utils::get_flow_name::<F>()?;
let option_gsm = payments_helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector_name,
flow_name.clone(),
)
.await;
let gsm_unified_code =
option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());
let gsm_unified_message =
option_gsm.clone().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(),
)
};
let unified_translated_message = locale
.as_ref()
.async_and_then(|locale_str| async {
payments_helpers::get_unified_translation(
state,
unified_code.to_owned(),
unified_message.to_owned(),
locale_str.to_owned(),
)
.await
})
.await
.or(Some(unified_message));
let status = match err.attempt_status {
// Use the status sent by connector in error_response if it's present
Some(status) => status,
None =>
// mark previous attempt status for technical failures in PSync and ExtendAuthorization flow
{
if flow_name == "PSync" || flow_name == "ExtendAuthorization" {
match err.status_code {
// marking failure for 2xx because this is genuine payment failure
200..=299 => enums::AttemptStatus::Failure,
_ => router_data.status,
}
} else if flow_name == "Capture" {
match err.status_code {
500..=511 => enums::AttemptStatus::Pending,
// don't update the status for 429 error status
429 => router_data.status,
_ => enums::AttemptStatus::Failure,
}
} else {
match err.status_code {
500..=511 => enums::AttemptStatus::Pending,
_ => enums::AttemptStatus::Failure,
}
}
}
};
(
None,
Some(storage::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
status,
error_message: Some(Some(err.message.clone())),
error_code: Some(Some(err.code.clone())),
error_reason: Some(err.reason.clone()),
amount_capturable: router_data
.request
.get_amount_capturable(
&payment_data,
router_data
.minor_amount_capturable
.map(MinorUnit::get_amount_as_i64),
status,
)
.map(MinorUnit::new),
updated_by: storage_scheme.to_string(),
unified_code: Some(Some(unified_code)),
unified_message: Some(unified_translated_message),
connector_transaction_id: err.connector_transaction_id.clone(),
payment_method_data: additional_payment_method_data,
authentication_type: auth_update,
issuer_error_code: err.network_decline_code.clone(),
issuer_error_message: err.network_error_message.clone(),
network_details: Some(ForeignFrom::foreign_from(&err)),
}),
option_gsm.and_then(|option_gsm| option_gsm.error_category),
)
}
};
(capture_update, attempt_update, gsm_error_category)
}
Ok(payments_response) => {
// match on connector integrity check
match router_data.integrity_check.clone() {
Err(err) => {
let auth_update = if Some(router_data.auth_type)
!= payment_data.payment_attempt.authentication_type
{
Some(router_data.auth_type)
} else {
None
};
let field_name = err.field_names;
let connector_transaction_id = err.connector_transaction_id;
(
None,
Some(storage::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
status: enums::AttemptStatus::IntegrityFailure,
error_message: Some(Some("Integrity Check Failed!".to_string())),
error_code: Some(Some("IE".to_string())),
error_reason: Some(Some(format!(
"Integrity Check Failed! Value mismatched for fields {field_name}"
))),
amount_capturable: None,
updated_by: storage_scheme.to_string(),
unified_code: None,
unified_message: None,
connector_transaction_id,
payment_method_data: None,
authentication_type: auth_update,
issuer_error_code: None,
issuer_error_message: None,
network_details: None,
}),
None,
)
}
Ok(()) => {
let attempt_status = payment_data.payment_attempt.status.to_owned();
let connector_status = router_data.status.to_owned();
let updated_attempt_status = match (
connector_status,
attempt_status,
payment_data.frm_message.to_owned(),
) {
(
enums::AttemptStatus::Authorized,
enums::AttemptStatus::Unresolved,
Some(frm_message),
) => match frm_message.frm_status {
enums::FraudCheckStatus::Fraud
| enums::FraudCheckStatus::ManualReview => attempt_status,
_ => router_data.get_attempt_status_for_db_update(
&payment_data,
router_data.amount_captured,
router_data
.minor_amount_capturable
.map(MinorUnit::get_amount_as_i64),
)?,
},
_ => router_data.get_attempt_status_for_db_update(
&payment_data,
router_data.amount_captured,
router_data
.minor_amount_capturable
.map(MinorUnit::get_amount_as_i64),
)?,
};
match payments_response {
types::PaymentsResponseData::PreProcessingResponse {
pre_processing_id,
connector_metadata,
connector_response_reference_id,
..
} => {
let connector_transaction_id = match pre_processing_id.to_owned() {
types::PreprocessingResponseId::PreProcessingId(_) => None,
types::PreprocessingResponseId::ConnectorTransactionId(
connector_txn_id,
) => Some(connector_txn_id),
};
let preprocessing_step_id = match pre_processing_id {
types::PreprocessingResponseId::PreProcessingId(
pre_processing_id,
) => Some(pre_processing_id),
types::PreprocessingResponseId::ConnectorTransactionId(_) => None,
};
let payment_attempt_update =
storage::PaymentAttemptUpdate::PreprocessingUpdate {
status: updated_attempt_status,
payment_method_id: payment_data
.payment_attempt
.payment_method_id
.clone(),
connector_metadata,
preprocessing_step_id,
connector_transaction_id,
connector_response_reference_id,
updated_by: storage_scheme.to_string(),
};
(None, Some(payment_attempt_update), None)
}
types::PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
connector_metadata,
connector_response_reference_id,
incremental_authorization_allowed,
charges,
..
} => {
payment_data
.payment_intent
.incremental_authorization_allowed =
core_utils::get_incremental_authorization_allowed_value(
incremental_authorization_allowed,
payment_data
.payment_intent
.request_incremental_authorization,
);
let connector_transaction_id = match resource_id {
types::ResponseId::NoResponseId => None,
types::ResponseId::ConnectorTransactionId(ref id)
| types::ResponseId::EncodedData(ref id) => Some(id),
};
let resp_network_transaction_id = router_data.response.as_ref()
.map_err(|err| {
logger::error!(error = ?err, "Failed to obtain the network_transaction_id from payment response");
})
.ok()
.and_then(|resp| resp.get_network_transaction_id());
let encoded_data = payment_data.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 auth_update = if Some(router_data.auth_type)
!= payment_data.payment_attempt.authentication_type
{
Some(router_data.auth_type)
} else {
None
};
// incase of success, update error code and error message
let error_status =
if router_data.status == enums::AttemptStatus::Charged {
Some(None)
} else {
None
};
// update connector_mandate_details in case of Authorized/Charged Payment Status
if matches!(
router_data.status,
enums::AttemptStatus::Charged
| enums::AttemptStatus::Authorized
| enums::AttemptStatus::PartiallyAuthorized
) {
payment_data
.payment_intent
.fingerprint_id
.clone_from(&payment_data.payment_attempt.fingerprint_id);
if let Some(payment_method) =
payment_data.payment_method_info.clone()
{
// Parse value to check for mandates' existence
let mandate_details = payment_method
.get_common_mandate_reference()
.change_context(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable(
"Failed to deserialize to Payment Mandate Reference ",
)?;
if let Some(mca_id) =
payment_data.payment_attempt.merchant_connector_id.clone()
{
// check if the mandate has not already been set to active
if !mandate_details.payments
.as_ref()
.and_then(|payments| payments.0.get(&mca_id))
.map(|payment_mandate_reference_record| payment_mandate_reference_record.connector_mandate_status == Some(common_enums::ConnectorMandateStatus::Active))
.unwrap_or(false)
{
let (connector_mandate_id, mandate_metadata,connector_mandate_request_reference_id) = payment_data.payment_attempt.connector_mandate_detail.clone()
.map(|cmr| (cmr.connector_mandate_id, cmr.mandate_metadata,cmr.connector_mandate_request_reference_id))
.unwrap_or((None, None,None));
// Update the connector mandate details with the payment attempt connector mandate id
let connector_mandate_details =
tokenization::update_connector_mandate_details(
Some(mandate_details),
payment_data.payment_attempt.payment_method_type,
Some(
payment_data
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
),
payment_data.payment_attempt.currency,
payment_data.payment_attempt.merchant_connector_id.clone(),
connector_mandate_id,
mandate_metadata,
connector_mandate_request_reference_id
)?;
// Update the payment method table with the active mandate record
payment_methods::cards::update_payment_method_connector_mandate_details(
state,
key_store,
&*state.store,
payment_method,
connector_mandate_details,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
}
}
}
metrics::SUCCESSFUL_PAYMENT.add(1, &[]);
}
let payment_method_id =
payment_data.payment_attempt.payment_method_id.clone();
let debit_routing_savings =
payment_data.payment_method_data.as_ref().and_then(|data| {
payments_helpers::get_debit_routing_savings_amount(
data,
&payment_data.payment_attempt,
)
});
utils::add_apple_pay_payment_status_metrics(
router_data.status,
router_data.apple_pay_flow.clone(),
payment_data.payment_attempt.connector.clone(),
payment_data.payment_attempt.merchant_id.clone(),
);
let is_overcapture_enabled = router_data
.connector_response
.as_ref()
.and_then(|connector_response| {
connector_response.is_overcapture_enabled()
}).or_else(|| {
payment_data.payment_intent
.enable_overcapture
.as_ref()
.map(|enable_overcapture| common_types::primitive_wrappers::OvercaptureEnabledBool::new(*enable_overcapture.deref()))
});
let (capture_before, extended_authorization_applied) = router_data
.connector_response
.as_ref()
.and_then(|connector_response| {
connector_response.get_extended_authorization_response_data()
})
.map(|extended_auth_resp| {
(
extended_auth_resp.capture_before,
extended_auth_resp.extended_authentication_applied,
)
})
.unwrap_or((None, None));
let (capture_updates, payment_attempt_update) = match payment_data
.multiple_capture_data
{
Some(multiple_capture_data) => {
let (connector_capture_id, processor_capture_data) =
match resource_id {
types::ResponseId::NoResponseId => (None, None),
types::ResponseId::ConnectorTransactionId(id)
| types::ResponseId::EncodedData(id) => {
let (txn_id, txn_data) =
ConnectorTransactionId::form_id_and_data(id);
(Some(txn_id), txn_data)
}
};
let capture_update = storage::CaptureUpdate::ResponseUpdate {
status: enums::CaptureStatus::foreign_try_from(
router_data.status,
)?,
connector_capture_id: connector_capture_id.clone(),
connector_response_reference_id,
processor_capture_data: processor_capture_data.clone(),
};
let capture_update_list = vec![(
multiple_capture_data.get_latest_capture().clone(),
capture_update,
)];
(Some((multiple_capture_data, capture_update_list)), auth_update.map(|auth_type| {
storage::PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type: auth_type,
updated_by: storage_scheme.to_string(),
}
}))
}
None => (
None,
Some(storage::PaymentAttemptUpdate::ResponseUpdate {
status: updated_attempt_status,
connector: None,
connector_transaction_id: connector_transaction_id.cloned(),
authentication_type: auth_update,
amount_capturable: router_data
.request
.get_amount_capturable(
&payment_data,
router_data
.minor_amount_capturable
.map(MinorUnit::get_amount_as_i64),
updated_attempt_status,
)
.map(MinorUnit::new),
payment_method_id,
mandate_id: payment_data.payment_attempt.mandate_id.clone(),
connector_metadata,
payment_token: None,
error_code: error_status.clone(),
error_message: error_status.clone(),
error_reason: error_status.clone(),
unified_code: error_status.clone(),
unified_message: error_status,
connector_response_reference_id,
updated_by: storage_scheme.to_string(),
authentication_data,
encoded_data,
payment_method_data: additional_payment_method_data,
capture_before,
extended_authorization_applied,
connector_mandate_detail: payment_data
.payment_attempt
.connector_mandate_detail
.clone(),
charges,
setup_future_usage_applied: payment_data
.payment_attempt
.setup_future_usage_applied,
debit_routing_savings,
network_transaction_id: resp_network_transaction_id,
is_overcapture_enabled,
authorized_amount: router_data.authorized_amount,
}),
),
};
(capture_updates, payment_attempt_update, None)
}
types::PaymentsResponseData::TransactionUnresolvedResponse {
resource_id,
reason,
connector_response_reference_id,
} => {
let connector_transaction_id = match resource_id {
types::ResponseId::NoResponseId => None,
types::ResponseId::ConnectorTransactionId(id)
| types::ResponseId::EncodedData(id) => Some(id),
};
(
None,
Some(storage::PaymentAttemptUpdate::UnresolvedResponseUpdate {
status: updated_attempt_status,
connector: None,
connector_transaction_id,
payment_method_id: payment_data
.payment_attempt
.payment_method_id
.clone(),
error_code: Some(reason.clone().map(|cd| cd.code)),
error_message: Some(reason.clone().map(|cd| cd.message)),
error_reason: Some(reason.map(|cd| cd.message)),
connector_response_reference_id,
updated_by: storage_scheme.to_string(),
}),
None,
)
}
types::PaymentsResponseData::SessionResponse { .. } => (None, None, None),
types::PaymentsResponseData::SessionTokenResponse { .. } => {
(None, None, None)
}
types::PaymentsResponseData::TokenizationResponse { .. } => {
(None, None, None)
}
types::PaymentsResponseData::ConnectorCustomerResponse(..) => {
(None, None, None)
}
types::PaymentsResponseData::ThreeDSEnrollmentResponse { .. } => {
(None, None, None)
}
types::PaymentsResponseData::PostProcessingResponse { .. } => {
(None, None, None)
}
types::PaymentsResponseData::IncrementalAuthorizationResponse {
..
} => (None, None, None),
types::PaymentsResponseData::PaymentResourceUpdateResponse { .. } => {
(None, None, None)
}
types::PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
} => match payment_data.multiple_capture_data {
Some(multiple_capture_data) => {
let capture_update_list = response_to_capture_update(
&multiple_capture_data,
capture_sync_response_list,
)?;
(
Some((multiple_capture_data, capture_update_list)),
None,
None,
)
}
None => (None, None, None),
},
types::PaymentsResponseData::PaymentsCreateOrderResponse { .. } => {
(None, None, None)
}
}
}
}
}
};
payment_data.multiple_capture_data = match capture_update {
Some((mut multiple_capture_data, capture_updates)) => {
for (capture, capture_update) in capture_updates {
let updated_capture = state
.store
.update_capture_with_capture_id(capture, capture_update, storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
multiple_capture_data.update_capture(updated_capture);
}
let authorized_amount = payment_data
.payment_attempt
.authorized_amount
.unwrap_or_else(|| payment_data.payment_attempt.get_total_amount());
payment_attempt_update = Some(storage::PaymentAttemptUpdate::AmountToCaptureUpdate {
status: multiple_capture_data.get_attempt_status(authorized_amount),
amount_capturable: authorized_amount
- multiple_capture_data.get_total_blocked_amount(),
updated_by: storage_scheme.to_string(),
});
Some(multiple_capture_data)
}
None => None,
};
// Stage 1
let payment_attempt = payment_data.payment_attempt.clone();
let m_db = state.clone().store;
let m_payment_attempt_update = payment_attempt_update.clone();
let m_payment_attempt = payment_attempt.clone();
let payment_attempt = payment_attempt_update
.map(|payment_attempt_update| {
PaymentAttempt::from_storage_model(
payment_attempt_update
.to_storage_model()
.apply_changeset(payment_attempt.clone().to_storage_model()),
)
})
.unwrap_or_else(|| payment_attempt);
let payment_attempt_fut = tokio::spawn(
async move {
Box::pin(async move {
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(
match m_payment_attempt_update {
Some(payment_attempt_update) => m_db
.update_payment_attempt_with_attempt_id(
m_payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,
None => m_payment_attempt,
},
)
})
.await
}
.in_current_span(),
);
payment_data.payment_attempt = payment_attempt;
payment_data.authentication = match payment_data.authentication {
Some(mut authentication_store) => {
let authentication_update = storage::AuthenticationUpdate::PostAuthorizationUpdate {
authentication_lifecycle_status: enums::AuthenticationLifecycleStatus::Used,
};
let updated_authentication = state
.store
.update_authentication_by_merchant_id_authentication_id(
authentication_store.authentication,
authentication_update,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
authentication_store.authentication = updated_authentication;
Some(authentication_store)
}
None => None,
};
let amount_captured = get_total_amount_captured(
&router_data.request,
router_data.amount_captured.map(MinorUnit::new),
router_data.status,
&payment_data,
);
let payment_intent_update = match &router_data.response {
Err(_) => storage::PaymentIntentUpdate::PGStatusUpdate {
status: api_models::enums::IntentStatus::foreign_from(
payment_data.payment_attempt.status,
),
updated_by: storage_scheme.to_string(),
// make this false only if initial payment fails, if incremental authorization call fails don't make it false
incremental_authorization_allowed: Some(false),
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
},
Ok(_) => storage::PaymentIntentUpdate::ResponseUpdate {
status: api_models::enums::IntentStatus::foreign_from(
payment_data.payment_attempt.status,
),
amount_captured,
updated_by: storage_scheme.to_string(),
fingerprint_id: payment_data.payment_attempt.fingerprint_id.clone(),
incremental_authorization_allowed: payment_data
.payment_intent
.incremental_authorization_allowed,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
},
};
let m_db = state.clone().store;
let m_key_store = key_store.clone();
let m_payment_data_payment_intent = payment_data.payment_intent.clone();
let m_payment_intent_update = payment_intent_update.clone();
let key_manager_state: KeyManagerState = state.into();
let payment_intent_fut = tokio::spawn(
async move {
m_db.update_payment_intent(
&key_manager_state,
m_payment_data_payment_intent,
m_payment_intent_update,
&m_key_store,
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
// When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize
let m_db = state.clone().store;
let m_router_data_merchant_id = router_data.merchant_id.clone();
let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
let m_payment_data_mandate_id =
payment_data
.payment_attempt
.mandate_id
.clone()
.or(payment_data
.mandate_id
.clone()
.and_then(|mandate_ids| mandate_ids.mandate_id));
let m_router_data_response = router_data.response.clone();
let mandate_update_fut = tokio::spawn(
async move {
mandate::update_connector_mandate_id(
m_db.as_ref(),
&m_router_data_merchant_id,
m_payment_data_mandate_id,
m_payment_method_id,
m_router_data_response,
storage_scheme,
)
.await
}
.in_current_span(),
);
let (payment_intent, _, payment_attempt) = futures::try_join!(
utils::flatten_join_error(payment_intent_fut),
utils::flatten_join_error(mandate_update_fut),
utils::flatten_join_error(payment_attempt_fut)
)?;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
{
if payment_intent.status.is_in_terminal_state()
&& business_profile.dynamic_routing_algorithm.is_some()
{
let dynamic_routing_algo_ref: api_models::routing::DynamicRoutingAlgorithmRef =
business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize DynamicRoutingAlgorithmRef from JSON")?
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("DynamicRoutingAlgorithmRef not found in profile")?;
let state = state.clone();
let profile_id = business_profile.get_id().to_owned();
let payment_attempt = payment_attempt.clone();
let dynamic_routing_config_params_interpolator =
routing_helpers::DynamicRoutingConfigParamsInterpolator::new(
payment_attempt.payment_method,
payment_attempt.payment_method_type,
payment_attempt.authentication_type,
payment_attempt.currency,
payment_data
.address
.get_payment_billing()
.and_then(|address| address.clone().address)
.and_then(|address| address.country),
payment_attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
payment_attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_isin"))
.and_then(|card_isin| card_isin.as_str())
.map(|card_isin| card_isin.to_string()),
);
tokio::spawn(
async move {
let should_route_to_open_router =
state.conf.open_router.dynamic_routing_enabled;
let is_success_rate_based = matches!(
payment_attempt.routing_approach,
Some(enums::RoutingApproach::SuccessRateExploitation)
| Some(enums::RoutingApproach::SuccessRateExploration)
);
if should_route_to_open_router && is_success_rate_based {
routing_helpers::update_gateway_score_helper_with_open_router(
&state,
&payment_attempt,
&profile_id,
dynamic_routing_algo_ref.clone(),
)
.await
.map_err(|e| logger::error!(open_router_update_gateway_score_err=?e))
.ok();
} else {
routing_helpers::push_metrics_with_update_window_for_success_based_routing(
&state,
&payment_attempt,
routable_connectors.clone(),
&profile_id,
dynamic_routing_algo_ref.clone(),
dynamic_routing_config_params_interpolator.clone(),
)
.await
.map_err(|e| logger::error!(success_based_routing_metrics_error=?e))
.ok();
if let Some(gsm_error_category) = gsm_error_category {
if gsm_error_category.should_perform_elimination_routing() {
logger::info!("Performing update window for elimination routing");
routing_helpers::update_window_for_elimination_routing(
&state,
&payment_attempt,
&profile_id,
dynamic_routing_algo_ref.clone(),
dynamic_routing_config_params_interpolator.clone(),
gsm_error_category,
)
.await
.map_err(|e| logger::error!(dynamic_routing_metrics_error=?e))
.ok();
};
};
routing_helpers::push_metrics_with_update_window_for_contract_based_routing(
&state,
&payment_attempt,
routable_connectors,
&profile_id,
dynamic_routing_algo_ref,
dynamic_routing_config_params_interpolator,
)
.await
.map_err(|e| logger::error!(contract_based_routing_metrics_error=?e))
.ok();
}
}
.in_current_span(),
);
}
}
payment_data.payment_intent = payment_intent;
payment_data.payment_attempt = payment_attempt;
router_data.payment_method_status.and_then(|status| {
payment_data
.payment_method_info
.as_mut()
.map(|info| info.status = status)
});
if payment_data.payment_attempt.status == enums::AttemptStatus::Failure {
let _ = card_testing_guard_utils::increment_blocked_count_in_cache(
state,
payment_data.card_testing_guard_data.clone(),
)
.await;
}
match router_data.integrity_check {
Ok(()) => Ok(payment_data),
Err(err) => {
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
(
"connector",
payment_data
.payment_attempt
.connector
.clone()
.unwrap_or_default(),
),
(
"merchant_id",
payment_data.payment_attempt.merchant_id.clone(),
)
),
);
Err(error_stack::Report::new(
errors::ApiErrorResponse::IntegrityCheckFailed {
connector_transaction_id: payment_data
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
reason: payment_data
.payment_attempt
.error_message
.unwrap_or_default(),
field_names: err.field_names,
},
))
}
}
}
#[cfg(feature = "v2")]
async fn update_payment_method_status_and_ntid<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
payment_response: Result<types::PaymentsResponseData, ErrorResponse>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<()> {
todo!()
}
#[cfg(feature = "v1")]
async fn update_payment_method_status_and_ntid<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
payment_data: &mut PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
payment_response: Result<types::PaymentsResponseData, ErrorResponse>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<()> {
// If the payment_method is deleted then ignore the error related to retrieving payment method
// This should be handled when the payment method is soft deleted
if let Some(id) = &payment_data.payment_attempt.payment_method_id {
let payment_method = match state
.store
.find_payment_method(&(state.into()), key_store, id, storage_scheme)
.await
{
Ok(payment_method) => payment_method,
Err(error) => {
if error.current_context().is_db_not_found() {
logger::info!(
"Payment Method not found in db and skipping payment method update {:?}",
error
);
return Ok(());
} else {
Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error retrieving payment method from db in update_payment_method_status_and_ntid")?
}
}
};
let pm_resp_network_transaction_id = payment_response
.map(|resp| if let types::PaymentsResponseData::TransactionResponse { network_txn_id: network_transaction_id, .. } = resp {
network_transaction_id
} else {None})
.map_err(|err| {
logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response");
})
.ok()
.flatten();
let network_transaction_id = if payment_data.payment_intent.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
{
if pm_resp_network_transaction_id.is_some() {
pm_resp_network_transaction_id
} else {
logger::info!("Skip storing network transaction id");
None
}
} else {
None
};
let pm_update = if payment_method.status != common_enums::PaymentMethodStatus::Active
&& payment_method.status != attempt_status.into()
{
let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status);
payment_data
.payment_method_info
.as_mut()
.map(|info| info.status = updated_pm_status);
storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status: Some(updated_pm_status),
}
} else {
storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
status: None,
}
};
state
.store
.update_payment_method(
&(state.into()),
key_store,
payment_method,
pm_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
};
Ok(())
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::PaymentsAuthorizeData> for &PaymentResponse {
type Data = PaymentConfirmData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsAuthorizeData> + Send + Sync),
> {
Ok(*self)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::PaymentsAuthorizeData> for PaymentResponse {
type Data = PaymentConfirmData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsAuthorizeData> + Send + Sync),
> {
Ok(self)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::PaymentsCaptureData> for PaymentResponse {
type Data = hyperswitch_domain_models::payments::PaymentCaptureData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsCaptureData> + Send + Sync),
> {
Ok(self)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone>
PostUpdateTracker<
F,
hyperswitch_domain_models::payments::PaymentCaptureData<F>,
types::PaymentsCaptureData,
> for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: hyperswitch_domain_models::payments::PaymentCaptureData<F>,
response: types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<hyperswitch_domain_models::payments::PaymentCaptureData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsCaptureData,
hyperswitch_domain_models::payments::PaymentCaptureData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
Ok(payment_data)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<F>,
response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentConfirmData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsAuthorizeData,
PaymentConfirmData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
let attempt_status = updated_payment_attempt.status;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
if let Some(payment_method) = &payment_data.payment_method {
match attempt_status {
common_enums::AttemptStatus::AuthenticationFailed
| common_enums::AttemptStatus::RouterDeclined
| common_enums::AttemptStatus::AuthorizationFailed
| common_enums::AttemptStatus::Voided
| common_enums::AttemptStatus::VoidedPostCharge
| common_enums::AttemptStatus::VoidInitiated
| common_enums::AttemptStatus::CaptureFailed
| common_enums::AttemptStatus::VoidFailed
| common_enums::AttemptStatus::AutoRefunded
| common_enums::AttemptStatus::Unresolved
| common_enums::AttemptStatus::Pending
| common_enums::AttemptStatus::Failure
| common_enums::AttemptStatus::Expired => (),
common_enums::AttemptStatus::Started
| common_enums::AttemptStatus::AuthenticationPending
| common_enums::AttemptStatus::AuthenticationSuccessful
| common_enums::AttemptStatus::Authorized
| common_enums::AttemptStatus::PartiallyAuthorized
| common_enums::AttemptStatus::Charged
| common_enums::AttemptStatus::Authorizing
| common_enums::AttemptStatus::CodInitiated
| common_enums::AttemptStatus::PartialCharged
| common_enums::AttemptStatus::PartialChargedAndChargeable
| common_enums::AttemptStatus::CaptureInitiated
| common_enums::AttemptStatus::PaymentMethodAwaited
| common_enums::AttemptStatus::ConfirmationAwaited
| common_enums::AttemptStatus::DeviceDataCollectionPending
| common_enums::AttemptStatus::IntegrityFailure => {
let pm_update_status = enums::PaymentMethodStatus::Active;
// payment_methods microservice call
payment_methods::update_payment_method_status_internal(
state,
key_store,
storage_scheme,
pm_update_status,
payment_method.get_id(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method status")?;
}
}
}
Ok(payment_data)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::PaymentsSyncData> for PaymentResponse {
type Data = PaymentStatusData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsSyncData> + Send + Sync)>
{
Ok(self)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentStatusData<F>, types::PaymentsSyncData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentStatusData<F>,
response: types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentStatusData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsSyncData,
PaymentStatusData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let payment_attempt = payment_data.payment_attempt;
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
Ok(payment_data)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for &PaymentResponse {
type Data = PaymentConfirmData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::SetupMandateRequestData> + Send + Sync),
> {
Ok(*self)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone> Operation<F, types::SetupMandateRequestData> for PaymentResponse {
type Data = PaymentConfirmData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::SetupMandateRequestData> + Send + Sync),
> {
Ok(self)
}
}
#[cfg(feature = "v2")]
impl
Operation<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> for PaymentResponse
{
type Data =
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
Self::Data,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> + Send
+ Sync),
> {
Ok(self)
}
}
#[cfg(feature = "v2")]
impl
Operation<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> for &PaymentResponse
{
type Data =
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
Self::Data,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> + Send
+ Sync),
> {
Ok(*self)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl
PostUpdateTracker<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
> for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
>,
response: types::RouterData<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
>
where
types::RouterData<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
types::PaymentsResponseData,
>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
hyperswitch_domain_models::router_flow_types::ExternalVaultProxy,
hyperswitch_domain_models::router_request_types::ExternalVaultProxyPaymentsData,
PaymentConfirmData<hyperswitch_domain_models::router_flow_types::ExternalVaultProxy>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
// TODO: Add external vault specific post-update logic if needed
Ok(payment_data)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::SetupMandateRequestData>
for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<F>,
response: types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentConfirmData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::SetupMandateRequestData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::SetupMandateRequestData,
PaymentConfirmData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
Ok(payment_data)
}
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
router_data: &types::RouterData<
F,
types::SetupMandateRequestData,
types::PaymentsResponseData,
>,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentConfirmData<F>,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse>
where
F: 'b + Clone + Send + Sync,
{
// If we received a payment_method_id from connector in the router data response
// Then we either update the payment method or create a new payment method
// The case for updating the payment method is when the payment is created from the payment method service
let Ok(payments_response) = &router_data.response else {
// In case there was an error response from the connector
// We do not take any action related to the payment method
return Ok(());
};
let connector_request_reference_id = payment_data
.payment_attempt
.connector_token_details
.as_ref()
.and_then(|token_details| token_details.get_connector_token_request_reference_id());
let connector_token =
payments_response.get_updated_connector_token_details(connector_request_reference_id);
let payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
// TODO: check what all conditions we will need to see if card need to be saved
match (
connector_token
.as_ref()
.and_then(|connector_token| connector_token.connector_mandate_id.clone()),
payment_method_id,
) {
(Some(token), Some(payment_method_id)) => {
if !matches!(
router_data.status,
enums::AttemptStatus::Charged | enums::AttemptStatus::Authorized
) {
return Ok(());
}
let connector_id = payment_data
.payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("missing connector id")?;
let net_amount = payment_data.payment_attempt.amount_details.get_net_amount();
let currency = payment_data.payment_intent.amount_details.currency;
let connector_token_details_for_payment_method_update =
api_models::payment_methods::ConnectorTokenDetails {
connector_id,
status: common_enums::ConnectorTokenStatus::Active,
connector_token_request_reference_id: connector_token
.and_then(|details| details.connector_token_request_reference_id),
original_payment_authorized_amount: Some(net_amount),
original_payment_authorized_currency: Some(currency),
metadata: None,
token: masking::Secret::new(token),
token_type: common_enums::TokenizationType::MultiUse,
};
let payment_method_update_request =
api_models::payment_methods::PaymentMethodUpdate {
payment_method_data: None,
connector_token_details: Some(
connector_token_details_for_payment_method_update,
),
};
payment_methods::update_payment_method_core(
state,
merchant_context,
business_profile,
payment_method_update_request,
&payment_method_id,
)
.await
.attach_printable("Failed to update payment method")?;
}
(Some(_), None) => {
// TODO: create a new payment method
}
(None, Some(_)) | (None, None) => {}
}
Ok(())
}
}
#[cfg(feature = "v1")]
fn update_connector_mandate_details_for_the_flow<F: Clone>(
connector_mandate_id: Option<String>,
mandate_metadata: Option<masking::Secret<serde_json::Value>>,
connector_mandate_request_reference_id: Option<String>,
payment_data: &mut PaymentData<F>,
) -> RouterResult<()> {
let mut original_connector_mandate_reference_id = payment_data
.payment_attempt
.connector_mandate_detail
.as_ref()
.map(|detail| ConnectorMandateReferenceId::foreign_from(detail.clone()));
let connector_mandate_reference_id = if connector_mandate_id.is_some() {
if let Some(ref mut record) = original_connector_mandate_reference_id {
record.update(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
);
Some(record.clone())
} else {
Some(ConnectorMandateReferenceId::new(
connector_mandate_id,
None,
None,
mandate_metadata,
connector_mandate_request_reference_id,
))
}
} else {
original_connector_mandate_reference_id
};
payment_data.payment_attempt.connector_mandate_detail = connector_mandate_reference_id
.clone()
.map(ForeignFrom::foreign_from);
payment_data.set_mandate_id(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: connector_mandate_reference_id.map(|connector_mandate_id| {
MandateReferenceId::ConnectorMandateId(connector_mandate_id)
}),
});
Ok(())
}
fn response_to_capture_update(
multiple_capture_data: &MultipleCaptureData,
response_list: HashMap<String, CaptureSyncResponse>,
) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> {
let mut capture_update_list = vec![];
let mut unmapped_captures = vec![];
for (connector_capture_id, capture_sync_response) in response_list {
let capture =
multiple_capture_data.get_capture_by_connector_capture_id(&connector_capture_id);
if let Some(capture) = capture {
capture_update_list.push((
capture.clone(),
storage::CaptureUpdate::foreign_try_from(capture_sync_response)?,
))
} else {
// connector_capture_id may not be populated in the captures table in some case
// if so, we try to map the unmapped capture response and captures in DB.
unmapped_captures.push(capture_sync_response)
}
}
capture_update_list.extend(get_capture_update_for_unmapped_capture_responses(
unmapped_captures,
multiple_capture_data,
)?);
Ok(capture_update_list)
}
fn get_capture_update_for_unmapped_capture_responses(
unmapped_capture_sync_response_list: Vec<CaptureSyncResponse>,
multiple_capture_data: &MultipleCaptureData,
) -> RouterResult<Vec<(storage::Capture, storage::CaptureUpdate)>> {
let mut result = Vec::new();
let captures_without_connector_capture_id: Vec<_> = multiple_capture_data
.get_pending_captures_without_connector_capture_id()
.into_iter()
.cloned()
.collect();
for capture_sync_response in unmapped_capture_sync_response_list {
if let Some(capture) = captures_without_connector_capture_id
.iter()
.find(|capture| {
capture_sync_response.get_connector_response_reference_id()
== Some(capture.capture_id.clone())
|| capture_sync_response.get_amount_captured() == Some(capture.amount)
})
{
result.push((
capture.clone(),
storage::CaptureUpdate::foreign_try_from(capture_sync_response)?,
))
}
}
Ok(result)
}
fn get_total_amount_captured<F: Clone, T: types::Capturable>(
request: &T,
amount_captured: Option<MinorUnit>,
router_data_status: enums::AttemptStatus,
payment_data: &PaymentData<F>,
) -> Option<MinorUnit> {
match &payment_data.multiple_capture_data {
Some(multiple_capture_data) => {
//multiple capture
Some(multiple_capture_data.get_total_blocked_amount())
}
None => {
//Non multiple capture
let amount = request
.get_captured_amount(
amount_captured.map(MinorUnit::get_amount_as_i64),
payment_data,
)
.map(MinorUnit::new);
amount_captured.or_else(|| {
if router_data_status == enums::AttemptStatus::Charged {
amount
} else {
None
}
})
}
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone + Sync> Operation<F, types::PaymentsCancelData> for PaymentResponse {
type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>;
fn to_post_update_tracker(
&self,
) -> RouterResult<
&(dyn PostUpdateTracker<F, Self::Data, types::PaymentsCancelData> + Send + Sync),
> {
Ok(self)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone + Send + Sync>
PostUpdateTracker<
F,
hyperswitch_domain_models::payments::PaymentCancelData<F>,
types::PaymentsCancelData,
> for PaymentResponse
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: hyperswitch_domain_models::payments::PaymentCancelData<F>,
router_data: types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<hyperswitch_domain_models::payments::PaymentCancelData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsCancelData,
hyperswitch_domain_models::payments::PaymentCancelData<F>,
>,
{
let db = &*state.store;
let key_manager_state = &state.into();
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let payment_intent_update =
router_data.get_payment_intent_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent.clone(),
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Error while updating the payment_intent")?;
let payment_attempt_update =
router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Error while updating the payment_attempt")?;
payment_data.set_payment_intent(updated_payment_intent);
payment_data.set_payment_attempt(updated_payment_attempt);
Ok(payment_data)
}
}
| crates/router/src/core/payments/operations/payment_response.rs | router::src::core::payments::operations::payment_response | 24,278 | true |
// File: crates/router/src/core/payments/operations/payment_get_intent.rs
// Module: router::src::core::payments::operations::payment_get_intent
use std::marker::PhantomData;
use api_models::{enums::FrmSuggestion, payments::PaymentsGetIntentRequest};
use async_trait::async_trait;
use common_utils::errors::CustomResult;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult},
payments::{self, helpers, operations},
},
db::errors::StorageErrorExt,
routes::{app::ReqState, SessionState},
types::{
api, domain,
storage::{self, enums},
},
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentGetIntent;
impl<F: Send + Clone + Sync> Operation<F, PaymentsGetIntentRequest> for &PaymentGetIntent {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentsGetIntentRequest, Self::Data> + Send + Sync)>
{
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)>
{
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsGetIntentRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)>
{
Ok(*self)
}
}
impl<F: Send + Clone + Sync> Operation<F, PaymentsGetIntentRequest> for PaymentGetIntent {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentsGetIntentRequest, Self::Data> + Send + Sync)>
{
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)>
{
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsGetIntentRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsGetIntentRequest> + Send + Sync)>
{
Ok(self)
}
}
type PaymentsGetIntentOperation<'b, F> =
BoxedOperation<'b, F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, PaymentsGetIntentRequest>
for PaymentGetIntent
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
_payment_id: &common_utils::id_type::GlobalPaymentId,
request: &PaymentsGetIntentRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
&request.id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
// todo : add a way to fetch client secret if required
client_secret: None,
sessions_token: vec![],
vault_session_details: None,
connector_customer_id: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsGetIntentRequest>
for PaymentGetIntent
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: payments::PaymentIntentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentsGetIntentOperation<'b, F>,
payments::PaymentIntentData<F>,
)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>
for PaymentGetIntent
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &PaymentsGetIntentRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
Ok(operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
})
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>
for PaymentGetIntent
{
#[instrument(skip_all)]
async fn get_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut payments::PaymentIntentData<F>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, PaymentsGetIntentRequest, payments::PaymentIntentData<F>>,
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 payments::PaymentIntentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentsGetIntentOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn perform_routing<'a>(
&'a self,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
state: &SessionState,
// TODO: do not take the whole payment data here
payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
Ok(api::ConnectorCallType::Skip)
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
| crates/router/src/core/payments/operations/payment_get_intent.rs | router::src::core::payments::operations::payment_get_intent | 1,767 | true |
// File: crates/router/src/core/payments/operations/payment_session.rs
// Module: router::src::core::payments::operations::payment_session
use std::marker::PhantomData;
use api_models::{admin::PaymentMethodsEnabled, enums::FrmSuggestion};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, ValueExt};
use error_stack::ResultExt;
use router_derive::PaymentOperation;
use router_env::{instrument, logger, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "session")]
pub struct PaymentSession;
type PaymentSessionOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsSessionRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
for PaymentSession
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsSessionRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<'a, F, api::PaymentsSessionRequest, PaymentData<F>>,
> {
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let mut payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Failed,
storage_enums::IntentStatus::Succeeded,
],
"create a session token for",
)?;
helpers::authenticate_client_secret(Some(&request.client_secret), &payment_intent)?;
let mut payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let currency = payment_intent.currency.get_required_value("currency")?;
payment_attempt.payment_method = Some(storage_enums::PaymentMethod::Wallet);
let amount = payment_attempt.get_total_amount().into();
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id);
let customer_details = payments::CustomerDetails {
customer_id: payment_intent.customer_id.clone(),
name: None,
email: None,
phone: None,
phone_country_code: None,
tax_registration_id: None,
};
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,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
customer_acceptance: None,
token: None,
token_data: None,
setup_mandate: None,
address: payments::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
for PaymentSession
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentSessionOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let metadata = payment_data.payment_intent.metadata.clone();
payment_data.payment_intent = match metadata {
Some(metadata) => state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
storage::PaymentIntentUpdate::MetadataUpdate {
metadata,
updated_by: storage_scheme.to_string(),
},
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,
None => payment_data.payment_intent,
};
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsSessionRequest, PaymentData<F>>
for PaymentSession
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsSessionRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentSessionOperation<'b, F>, operations::ValidateResult)> {
//paymentid is already generated and should be sent in the request
let given_payment_id = request.payment_id.clone();
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
#[async_trait]
impl<
F: Clone + Send,
Op: Send + Sync + Operation<F, api::PaymentsSessionRequest, Data = PaymentData<F>>,
> Domain<F, api::PaymentsSessionRequest, PaymentData<F>> for Op
where
for<'a> &'a Op: Operation<F, api::PaymentsSessionRequest, Data = PaymentData<F>>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<payments::CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> errors::CustomResult<
(PaymentSessionOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
#[instrument(skip_all)]
async fn make_pm_data<'b>(
&'b self,
_state: &'b SessionState,
_payment_data: &mut PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentSessionOperation<'b, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
//No payment method data for this operation
Ok((Box::new(self), None, None))
}
/// Returns `SessionConnectorDatas`
/// Steps carried out in this function
/// Get all the `merchant_connector_accounts` which are not disabled
/// Filter out connectors which have `invoke_sdk_client` enabled in `payment_method_types`
/// If session token is requested for certain wallets only, then return them, else
/// return all eligible connectors
///
/// `GetToken` parameter specifies whether to get the session token from connector integration
/// or from separate implementation ( for googlepay - from metadata and applepay - from metadata and call connector)
async fn get_connector<'a>(
&'a self,
merchant_context: &domain::MerchantContext,
state: &SessionState,
request: &api::PaymentsSessionRequest,
payment_intent: &storage::PaymentIntent,
) -> RouterResult<api::ConnectorChoice> {
let db = &state.store;
let all_connector_accounts = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_context.get_merchant_account().get_id(),
false,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Database error when querying for merchant connector accounts")?;
let profile_id = payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?;
let filtered_connector_accounts = all_connector_accounts
.filter_based_on_profile_and_connector_type(
&profile_id,
common_enums::ConnectorType::PaymentProcessor,
);
let requested_payment_method_types = request.wallets.clone();
let mut connector_and_supporting_payment_method_type = Vec::new();
filtered_connector_accounts
.iter()
.for_each(|connector_account| {
let res = connector_account
.payment_methods_enabled
.clone()
.unwrap_or_default()
.into_iter()
.map(|payment_methods_enabled| {
payment_methods_enabled
.parse_value::<PaymentMethodsEnabled>("payment_methods_enabled")
})
.filter_map(|parsed_payment_method_result| {
parsed_payment_method_result
.inspect_err(|err| {
logger::error!(session_token_parsing_error=?err);
})
.ok()
})
.flat_map(|parsed_payment_methods_enabled| {
parsed_payment_methods_enabled
.payment_method_types
.unwrap_or_default()
.into_iter()
.filter(|payment_method_type| {
let is_invoke_sdk_client = matches!(
payment_method_type.payment_experience,
Some(api_models::enums::PaymentExperience::InvokeSdkClient)
);
// If session token is requested for the payment method type,
// filter it out
// if not, then create all sessions tokens
let is_sent_in_request = requested_payment_method_types
.contains(&payment_method_type.payment_method_type)
|| requested_payment_method_types.is_empty();
is_invoke_sdk_client && is_sent_in_request
})
.map(|payment_method_type| {
(
connector_account,
payment_method_type.payment_method_type,
parsed_payment_methods_enabled.payment_method,
)
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>();
connector_and_supporting_payment_method_type.extend(res);
});
let mut session_connector_data = api::SessionConnectorDatas::with_capacity(
connector_and_supporting_payment_method_type.len(),
);
for (merchant_connector_account, payment_method_type, payment_method) in
connector_and_supporting_payment_method_type
{
if let Ok(connector_data) = helpers::get_connector_data_with_token(
state,
merchant_connector_account.connector_name.to_string(),
Some(merchant_connector_account.get_id()),
payment_method_type,
) {
#[cfg(feature = "v1")]
{
let new_session_connector_data = api::SessionConnectorData::new(
payment_method_type,
connector_data,
merchant_connector_account.business_sub_label.clone(),
payment_method,
);
session_connector_data.push(new_session_connector_data)
}
#[cfg(feature = "v2")]
{
let new_session_connector_data =
api::SessionConnectorData::new(payment_method_type, connector_data, None);
session_connector_data.push(new_session_connector_data)
}
};
}
Ok(api::ConnectorChoice::SessionMultiple(
session_connector_data,
))
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
| crates/router/src/core/payments/operations/payment_session.rs | router::src::core::payments::operations::payment_session | 3,608 | true |
// File: crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs
// Module: router::src::core::payments::operations::external_vault_proxy_payment_intent
use api_models::payments::ExternalVaultProxyPaymentsRequest;
use async_trait::async_trait;
use common_enums::enums;
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, ValueExt},
types::keymanager::ToEncryptable,
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData, payments::PaymentConfirmData,
};
use hyperswitch_interfaces::api::ConnectorSpecifications;
use masking::PeekInterface;
use router_env::{instrument, tracing};
use super::{Domain, GetTracker, Operation, PostUpdateTracker, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payment_methods::{self, PaymentMethodExt},
payments::{
self,
operations::{self, ValidateStatusForOperation},
OperationSessionGetters, OperationSessionSetters,
},
},
routes::{app::ReqState, SessionState},
types::{
self,
api::{self, ConnectorCallType},
domain::{self, types as domain_types},
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy)]
pub struct ExternalVaultProxyPaymentIntent;
impl ValidateStatusForOperation for ExternalVaultProxyPaymentIntent {
/// Validate if the current operation can be performed on the current status of the payment intent
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Processing => Ok(()),
common_enums::IntentStatus::Conflicted
| common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: ["requires_payment_method", "failed", "processing"].join(", "),
})
}
}
}
}
type BoxedConfirmOperation<'b, F> =
super::BoxedOperation<'b, F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>>;
impl<F: Send + Clone + Sync> Operation<F, ExternalVaultProxyPaymentsRequest>
for &ExternalVaultProxyPaymentIntent
{
type Data = PaymentConfirmData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, ExternalVaultProxyPaymentsRequest, Self::Data> + Send + Sync),
> {
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<
&(dyn GetTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync),
> {
Ok(*self)
}
fn to_domain(
&self,
) -> RouterResult<&(dyn Domain<F, ExternalVaultProxyPaymentsRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<
&(dyn UpdateTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync),
> {
Ok(*self)
}
}
#[automatically_derived]
impl<F: Send + Clone + Sync> Operation<F, ExternalVaultProxyPaymentsRequest>
for ExternalVaultProxyPaymentIntent
{
type Data = PaymentConfirmData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, ExternalVaultProxyPaymentsRequest, Self::Data> + Send + Sync),
> {
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<
&(dyn GetTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync),
> {
Ok(self)
}
fn to_domain(
&self,
) -> RouterResult<&dyn Domain<F, ExternalVaultProxyPaymentsRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<
&(dyn UpdateTracker<F, Self::Data, ExternalVaultProxyPaymentsRequest> + Send + Sync),
> {
Ok(self)
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>>
for ExternalVaultProxyPaymentIntent
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &ExternalVaultProxyPaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
let validate_result = operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
};
Ok(validate_result)
}
}
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ExternalVaultProxyPaymentsRequest>
for ExternalVaultProxyPaymentIntent
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &ExternalVaultProxyPaymentsRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let cell_id = state.conf.cell_information.id.clone();
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt {
payment_method_billing_address: None,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let payment_attempt = match payment_intent.active_attempt_id.clone() {
Some(ref active_attempt_id) => db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
active_attempt_id,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Could not find payment attempt")?,
None => {
// TODO: Implement external vault specific payment attempt creation logic
let payment_attempt_domain_model: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt =
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::external_vault_proxy_create_domain_model(
&payment_intent,
cell_id,
storage_scheme,
request,
encrypted_data
)
.await?;
db.insert_payment_attempt(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_attempt_domain_model,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not insert payment attempt")?
}
};
// TODO: Extract external vault specific token/credentials from request
let processor_payment_token = None; // request.external_vault_details.processor_payment_token.clone();
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
.shipping_address
.clone()
.map(|address| address.into_inner()),
payment_intent
.billing_address
.clone()
.map(|address| address.into_inner()),
payment_attempt
.payment_method_billing_address
.clone()
.map(|address| address.into_inner()),
Some(true),
);
// TODO: Implement external vault specific mandate data handling
let mandate_data_input = api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: processor_payment_token.map(|token| {
api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
Some(token),
None,
None,
None,
None,
),
)
}),
};
let payment_method_data = request.payment_method_data.payment_method_data.clone().map(
hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::from,
);
let payment_data = PaymentConfirmData {
flow: std::marker::PhantomData,
payment_intent,
payment_attempt,
payment_method_data: None, // TODO: Review for external vault
payment_address,
mandate_data: Some(mandate_data_input),
payment_method: None,
merchant_connector_details: None,
external_vault_pmd: payment_method_data,
webhook_url: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, ExternalVaultProxyPaymentsRequest, PaymentConfirmData<F>>
for ExternalVaultProxyPaymentIntent
{
async fn get_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<(BoxedConfirmOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
match payment_data.payment_intent.customer_id.clone() {
Some(id) => {
let customer = state
.store
.find_customer_by_global_id(
&state.into(),
&id,
merchant_key_store,
storage_scheme,
)
.await?;
Ok((Box::new(self), Some(customer)))
}
None => Ok((Box::new(self), None)),
}
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut PaymentConfirmData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedConfirmOperation<'a, F>,
Option<PaymentMethodData>,
Option<String>,
)> {
// TODO: Implement external vault specific payment method data creation
Ok((Box::new(self), None, None))
}
async fn create_or_fetch_payment_method<'a>(
&'a self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
payment_data: &mut PaymentConfirmData<F>,
) -> CustomResult<(), errors::ApiErrorResponse> {
match (
payment_data.payment_intent.customer_id.clone(),
payment_data.external_vault_pmd.clone(),
payment_data.payment_attempt.customer_acceptance.clone(),
payment_data.payment_attempt.payment_token.clone(),
) {
(Some(customer_id), Some(hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::Card(card_details)), Some(_), None) => {
let payment_method_data =
api::PaymentMethodCreateData::ProxyCard(api::ProxyCardDetails::from(*card_details));
let billing = payment_data
.payment_address
.get_payment_method_billing()
.cloned()
.map(From::from);
let req = api::PaymentMethodCreate {
payment_method_type: payment_data.payment_attempt.payment_method_type,
payment_method_subtype: payment_data.payment_attempt.payment_method_subtype,
metadata: None,
customer_id,
payment_method_data,
billing,
psp_tokenization: None,
network_tokenization: None,
};
let (_pm_response, payment_method) = Box::pin(payment_methods::create_payment_method_core(
state,
&state.get_req_state(),
req,
merchant_context,
business_profile,
))
.await?;
payment_data.payment_method = Some(payment_method);
}
(_, Some(hyperswitch_domain_models::payment_method_data::ExternalVaultPaymentMethodData::VaultToken(vault_token)), None, Some(payment_token)) => {
payment_data.external_vault_pmd = Some(payment_methods::get_external_vault_token(
state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
payment_token.clone(),
vault_token.clone(),
&payment_data.payment_attempt.payment_method_type
)
.await?);
}
_ => {
router_env::logger::debug!(
"No payment method to create or fetch for external vault proxy payment intent"
);
}
}
Ok(())
}
#[cfg(feature = "v2")]
async fn update_payment_method<'a>(
&'a self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentConfirmData<F>,
) {
if let (true, Some(payment_method)) = (
payment_data.payment_attempt.customer_acceptance.is_some(),
payment_data.payment_method.as_ref(),
) {
payment_methods::update_payment_method_status_internal(
state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
common_enums::PaymentMethodStatus::Active,
payment_method.get_id(),
)
.await
.map_err(|err| router_env::logger::error!(err=?err));
};
}
#[instrument(skip_all)]
async fn populate_payment_data<'a>(
&'a self,
_state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
connector_data: &api::ConnectorData,
) -> CustomResult<(), errors::ApiErrorResponse> {
let connector_request_reference_id = connector_data
.connector
.generate_connector_request_reference_id(
&payment_data.payment_intent,
&payment_data.payment_attempt,
);
payment_data.set_connector_request_reference_id(Some(connector_request_reference_id));
Ok(())
}
async fn perform_routing<'a>(
&'a self,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> {
payments::connector_selection(
state,
merchant_context,
business_profile,
payment_data,
None,
)
.await
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, ExternalVaultProxyPaymentsRequest>
for ExternalVaultProxyPaymentIntent
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: PaymentConfirmData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<api_models::enums::FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentConfirmData<F>)>
where
F: 'b + Send,
{
let db = &*state.store;
let key_manager_state = &state.into();
let intent_status = common_enums::IntentStatus::Processing;
let attempt_status = common_enums::AttemptStatus::Pending;
let connector = payment_data
.payment_attempt
.connector
.clone()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector is none when constructing response")?;
let merchant_connector_id = Some(
payment_data
.payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector id is none when constructing response")?,
);
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent {
status: intent_status,
updated_by: storage_scheme.to_string(),
active_attempt_id: Some(payment_data.payment_attempt.id.clone()),
};
let authentication_type = payment_data
.payment_intent
.authentication_type
.unwrap_or_default();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone();
let connector_response_reference_id = payment_data
.payment_attempt
.connector_response_reference_id
.clone();
let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent {
status: attempt_status,
updated_by: storage_scheme.to_string(),
connector,
merchant_connector_id,
authentication_type,
connector_request_reference_id,
connector_response_reference_id,
};
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent.clone(),
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
payment_data.payment_intent = updated_payment_intent;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_attempt = updated_payment_attempt;
Ok((Box::new(self), payment_data))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData>
for ExternalVaultProxyPaymentIntent
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<F>,
response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentConfirmData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsAuthorizeData,
PaymentConfirmData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
// TODO: Add external vault specific post-update logic
Ok(payment_data)
}
}
| crates/router/src/core/payments/operations/external_vault_proxy_payment_intent.rs | router::src::core::payments::operations::external_vault_proxy_payment_intent | 4,804 | true |
// File: crates/router/src/core/payments/operations/payment_post_session_tokens.rs
// Module: router::src::core::payments::operations::payment_post_session_tokens
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::types::keymanager::KeyManagerState;
use error_stack::ResultExt;
use masking::PeekInterface;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "post_session_tokens")]
pub struct PaymentPostSessionTokens;
type PaymentPostSessionTokensOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsPostSessionTokensRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSessionTokensRequest>
for PaymentPostSessionTokens
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsPostSessionTokensRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<
'a,
F,
api::PaymentsPostSessionTokensRequest,
PaymentData<F>,
>,
> {
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let db = &*state.store;
let key_manager_state: &KeyManagerState = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?;
let mut payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let currency = payment_intent.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
payment_attempt.payment_method = Some(request.payment_method);
payment_attempt.payment_method_type = Some(request.payment_method_type);
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
customer_acceptance: None,
token: None,
token_data: None,
setup_mandate: None,
address: payments::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
None,
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsPostSessionTokensRequest, PaymentData<F>>
for PaymentPostSessionTokens
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> errors::CustomResult<
(
PaymentPostSessionTokensOperation<'a, F>,
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 PaymentData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentPostSessionTokensOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
_request: &api::PaymentsPostSessionTokensRequest,
_payment_intent: &storage::PaymentIntent,
) -> errors::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,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsPostSessionTokensRequest>
for PaymentPostSessionTokens
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentPostSessionTokensOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, api::PaymentsPostSessionTokensRequest, PaymentData<F>>
for PaymentPostSessionTokens
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsPostSessionTokensRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
PaymentPostSessionTokensOperation<'b, F>,
operations::ValidateResult,
)> {
//payment id is already generated and should be sent in the request
let given_payment_id = request.payment_id.clone();
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| crates/router/src/core/payments/operations/payment_post_session_tokens.rs | router::src::core::payments::operations::payment_post_session_tokens | 2,285 | true |
// File: crates/router/src/core/payments/operations/payment_start.rs
// Module: router::src::core::payments::operations::payment_start
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "start")]
pub struct PaymentStart;
type PaymentSessionOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsStartRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest>
for PaymentStart
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
_request: &api::PaymentsStartRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<'a, F, api::PaymentsStartRequest, PaymentData<F>>,
> {
let (mut payment_intent, payment_attempt, currency, amount);
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once Merchant ID auth is solved
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Failed,
storage_enums::IntentStatus::Succeeded,
],
"update",
)?;
helpers::authenticate_client_secret(
payment_intent.client_secret.as_ref(),
&payment_intent,
)?;
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let token_data = if let Some(token) = payment_attempt.payment_token.clone() {
Some(
helpers::retrieve_payment_token_data(state, token, payment_attempt.payment_method)
.await?,
)
} else {
None
};
payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
let customer_details = CustomerDetails {
customer_id: payment_intent.customer_id.clone(),
..CustomerDetails::default()
};
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: payment_attempt.payment_token.clone(),
address: PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
token_data,
confirm: Some(payment_attempt.confirm),
payment_attempt,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for PaymentStart {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_mechant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentSessionOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsStartRequest, PaymentData<F>>
for PaymentStart
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsStartRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentSessionOperation<'b, F>, operations::ValidateResult)> {
let request_merchant_id = Some(&request.merchant_id);
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
let payment_id = request.payment_id.clone();
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
#[async_trait]
impl<
F: Clone + Send,
Op: Send + Sync + Operation<F, api::PaymentsStartRequest, Data = PaymentData<F>>,
> Domain<F, api::PaymentsStartRequest, PaymentData<F>> for Op
where
for<'a> &'a Op: Operation<F, api::PaymentsStartRequest, Data = PaymentData<F>>,
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(PaymentSessionOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentSessionOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
if payment_data
.payment_attempt
.connector
.clone()
.map(|connector_name| connector_name == *"bluesnap".to_string())
.unwrap_or(false)
{
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
} else {
Ok((Box::new(self), None, None))
}
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
_request: &api::PaymentsStartRequest,
_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,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
| crates/router/src/core/payments/operations/payment_start.rs | router::src::core::payments::operations::payment_start | 2,674 | true |
// File: crates/router/src/core/payments/operations/payment_session_intent.rs
// Module: router::src::core::payments::operations::payment_session_intent
use std::{collections::HashMap, marker::PhantomData};
use api_models::payments::PaymentsSessionRequest;
use async_trait::async_trait;
use common_utils::{errors::CustomResult, ext_traits::Encode};
use error_stack::ResultExt;
use hyperswitch_domain_models::customer;
use router_env::{instrument, logger, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, operations::ValidateStatusForOperation},
},
routes::{app::ReqState, SessionState},
types::{api, domain, storage, storage::enums},
utils::ext_traits::OptionExt,
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentSessionIntent;
type PaymentSessionOperation<'b, F> =
BoxedOperation<'b, F, PaymentsSessionRequest, payments::PaymentIntentData<F>>;
impl ValidateStatusForOperation for PaymentSessionIntent {
/// Validate if the current operation can be performed on the current status of the payment intent
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
common_enums::IntentStatus::RequiresPaymentMethod => Ok(()),
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
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Failed | common_enums::IntentStatus::Conflicted | common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"You cannot create session token for this payment because it has status {intent_status}. Expected status is requires_payment_method.",
),
})
}
}
}
}
impl<F: Send + Clone + Sync> Operation<F, PaymentsSessionRequest> for &PaymentSessionIntent {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentsSessionRequest, Self::Data> + Send + Sync)>
{
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsSessionRequest> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsSessionRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<
&(dyn UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsSessionRequest>
+ Send
+ Sync),
> {
Ok(*self)
}
}
impl<F: Send + Clone + Sync> Operation<F, PaymentsSessionRequest> for PaymentSessionIntent {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentsSessionRequest, Self::Data> + Send + Sync)>
{
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsSessionRequest> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsSessionRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<
&(dyn UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsSessionRequest>
+ Send
+ Sync),
> {
Ok(self)
}
}
type PaymentsCreateIntentOperation<'b, F> =
BoxedOperation<'b, F, PaymentsSessionRequest, payments::PaymentIntentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentIntentData<F>, PaymentsSessionRequest>
for PaymentSessionIntent
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
_request: &PaymentsSessionRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once publishable key auth is solved
self.validate_status_for_operation(payment_intent.status)?;
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
client_secret: None,
sessions_token: vec![],
vault_session_details: None,
connector_customer_id: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsSessionRequest>
for PaymentSessionIntent
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: payments::PaymentIntentData<F>,
customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
updated_customer: Option<customer::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<common_enums::FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentSessionOperation<'b, F>,
payments::PaymentIntentData<F>,
)>
where
F: 'b + Send,
{
let prerouting_algorithm = payment_data.payment_intent.prerouting_algorithm.clone();
payment_data.payment_intent = match prerouting_algorithm {
Some(prerouting_algorithm) => state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
storage::PaymentIntentUpdate::SessionIntentUpdate {
prerouting_algorithm,
updated_by: storage_scheme.to_string(),
},
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?,
None => payment_data.payment_intent,
};
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone> ValidateRequest<F, PaymentsSessionRequest, payments::PaymentIntentData<F>>
for PaymentSessionIntent
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &PaymentsSessionRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
Ok(operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
})
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, PaymentsSessionRequest, payments::PaymentIntentData<F>>
for PaymentSessionIntent
{
#[instrument(skip_all)]
async fn get_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut payments::PaymentIntentData<F>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, PaymentsSessionRequest, payments::PaymentIntentData<F>>,
Option<domain::Customer>,
),
errors::StorageError,
> {
match payment_data.payment_intent.customer_id.clone() {
Some(id) => {
let customer = state
.store
.find_customer_by_global_id(
&state.into(),
&id,
merchant_key_store,
storage_scheme,
)
.await?;
Ok((Box::new(self), Some(customer)))
}
None => Ok((Box::new(self), None)),
}
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut payments::PaymentIntentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentsCreateIntentOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn perform_routing<'a>(
&'a self,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
state: &SessionState,
payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
let db = &state.store;
let all_connector_accounts = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
merchant_context.get_merchant_account().get_id(),
false,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Database error when querying for merchant connector accounts")?;
let profile_id = business_profile.get_id();
let filtered_connector_accounts = all_connector_accounts
.filter_based_on_profile_and_connector_type(
profile_id,
common_enums::ConnectorType::PaymentProcessor,
);
let connector_and_supporting_payment_method_type = filtered_connector_accounts
.get_connector_and_supporting_payment_method_type_for_session_call();
let session_connector_data: api::SessionConnectorDatas =
connector_and_supporting_payment_method_type
.into_iter()
.filter_map(
|(merchant_connector_account, payment_method_type, payment_method)| {
match helpers::get_connector_data_with_token(
state,
merchant_connector_account.connector_name.to_string(),
Some(merchant_connector_account.get_id()),
payment_method_type,
) {
Ok(connector_data) => Some(api::SessionConnectorData::new(
payment_method_type,
connector_data,
None,
payment_method,
)),
Err(err) => {
logger::error!(session_token_error=?err);
None
}
}
},
)
.collect();
let session_token_routing_result = payments::perform_session_token_routing(
state.clone(),
business_profile,
merchant_context.clone(),
payment_data,
session_connector_data,
)
.await?;
let pre_routing = storage::PaymentRoutingInfo {
algorithm: None,
pre_routing_results: Some((|| {
let mut pre_routing_results: HashMap<
common_enums::PaymentMethodType,
storage::PreRoutingConnectorChoice,
> = HashMap::new();
for (pm_type, routing_choice) in session_token_routing_result.routing_result {
let mut routable_choice_list = vec![];
for choice in routing_choice {
let routable_choice = api::routing::RoutableConnectorChoice {
choice_kind: api::routing::RoutableChoiceKind::FullStruct,
connector: choice
.connector
.connector_name
.to_string()
.parse::<common_enums::RoutableConnectors>()
.change_context(errors::ApiErrorResponse::InternalServerError)?,
merchant_connector_id: choice.connector.merchant_connector_id.clone(),
};
routable_choice_list.push(routable_choice);
}
pre_routing_results.insert(
pm_type,
storage::PreRoutingConnectorChoice::Multiple(routable_choice_list),
);
}
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(pre_routing_results)
})()?),
};
// Store the routing results in payment intent
payment_data.payment_intent.prerouting_algorithm = Some(pre_routing);
Ok(api::ConnectorCallType::SessionMultiple(
session_token_routing_result.final_result,
))
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
| crates/router/src/core/payments/operations/payment_session_intent.rs | router::src::core::payments::operations::payment_session_intent | 2,968 | true |
// File: crates/router/src/core/payments/operations/payment_attempt_record.rs
// Module: router::src::core::payments::operations::payment_attempt_record
use std::marker::PhantomData;
use api_models::{enums::FrmSuggestion, payments::PaymentsAttemptRecordRequest};
use async_trait::async_trait;
use common_utils::{
errors::CustomResult,
ext_traits::{AsyncExt, Encode, ValueExt},
types::keymanager::ToEncryptable,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::payments::PaymentAttemptRecordData;
use masking::PeekInterface;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, StorageErrorExt},
payments::{
self,
cards::create_encrypted_data,
helpers,
operations::{self, ValidateStatusForOperation},
},
},
db::{domain::types, errors::RouterResult},
routes::{app::ReqState, SessionState},
services,
types::{
api,
domain::{self, types as domain_types},
storage::{self, enums},
},
utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentAttemptRecord;
type PaymentsAttemptRecordOperation<'b, F> =
BoxedOperation<'b, F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>>;
impl<F: Send + Clone + Sync> Operation<F, PaymentsAttemptRecordRequest> for &PaymentAttemptRecord {
type Data = PaymentAttemptRecordData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, PaymentsAttemptRecordRequest, Self::Data> + Send + Sync),
> {
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsAttemptRecordRequest> + Send + Sync)>
{
Ok(*self)
}
fn to_domain(
&self,
) -> RouterResult<&(dyn Domain<F, PaymentsAttemptRecordRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsAttemptRecordRequest> + Send + Sync)>
{
Ok(*self)
}
}
impl ValidateStatusForOperation for PaymentAttemptRecord {
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
// need to verify this?
match intent_status {
// Payment attempt can be recorded for failed payment as well in revenue recovery flow.
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::Failed => Ok(()),
common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::Processing
| common_enums::IntentStatus::Conflicted
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: [
common_enums::IntentStatus::RequiresPaymentMethod,
common_enums::IntentStatus::Failed,
]
.map(|enum_value| enum_value.to_string())
.join(", "),
})
}
}
}
}
#[async_trait]
impl<F: Send + Clone + Sync>
GetTracker<F, PaymentAttemptRecordData<F>, PaymentsAttemptRecordRequest>
for PaymentAttemptRecord
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &PaymentsAttemptRecordRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<PaymentAttemptRecordData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let payment_method_billing_address = request
.payment_method_data
.as_ref()
.and_then(|data| {
data.billing
.as_ref()
.map(|address| address.clone().encode_to_value())
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode payment_method_billing address")?
.map(masking::Secret::new);
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt {
payment_method_billing_address,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let cell_id = state.conf.cell_information.id.clone();
let payment_attempt_domain_model =
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::create_domain_model_using_record_request(
&payment_intent,
cell_id,
storage_scheme,
request,
encrypted_data,
)
.await?;
let payment_attempt = db
.insert_payment_attempt(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_attempt_domain_model,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not insert payment attempt")?;
let revenue_recovery_data = hyperswitch_domain_models::payments::RevenueRecoveryData {
billing_connector_id: request.billing_connector_id.clone(),
processor_payment_method_token: request.processor_payment_method_token.clone(),
connector_customer_id: request.connector_customer_id.clone(),
retry_count: request.retry_count,
invoice_next_billing_time: request.invoice_next_billing_time,
triggered_by: request.triggered_by,
card_network: request.card_network.clone(),
card_issuer: request.card_issuer.clone(),
};
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
.shipping_address
.clone()
.map(|address| address.into_inner()),
payment_intent
.billing_address
.clone()
.map(|address| address.into_inner()),
payment_attempt
.payment_method_billing_address
.clone()
.map(|address| address.into_inner()),
Some(true),
);
let payment_data = PaymentAttemptRecordData {
flow: PhantomData,
payment_intent,
payment_attempt,
payment_address,
revenue_recovery_data,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentAttemptRecordData<F>, PaymentsAttemptRecordRequest>
for PaymentAttemptRecord
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: PaymentAttemptRecordData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentsAttemptRecordOperation<'b, F>,
PaymentAttemptRecordData<F>,
)>
where
F: 'b + Send,
{
let feature_metadata = payment_data.get_updated_feature_metadata()?;
let active_attempt_id = match payment_data.revenue_recovery_data.triggered_by {
common_enums::TriggeredBy::Internal => Some(payment_data.payment_attempt.id.clone()),
common_enums::TriggeredBy::External => None,
};
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::RecordUpdate
{
status: common_enums::IntentStatus::from(payment_data.payment_attempt.status),
feature_metadata: Box::new(feature_metadata),
updated_by: storage_scheme.to_string(),
active_attempt_id
}
;
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone> ValidateRequest<F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>>
for PaymentAttemptRecord
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &PaymentsAttemptRecordRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
Ok(operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
})
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>>
for PaymentAttemptRecord
{
#[instrument(skip_all)]
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentAttemptRecordData<F>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, PaymentsAttemptRecordRequest, PaymentAttemptRecordData<F>>,
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 PaymentAttemptRecordData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentsAttemptRecordOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn perform_routing<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
_state: &SessionState,
_payment_data: &mut PaymentAttemptRecordData<F>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
Ok(api::ConnectorCallType::Skip)
}
}
| crates/router/src/core/payments/operations/payment_attempt_record.rs | router::src::core::payments::operations::payment_attempt_record | 2,774 | true |
// File: crates/router/src/core/payments/operations/payment_cancel_v2.rs
// Module: router::src::core::payments::operations::payment_cancel_v2
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_enums;
use common_utils::{ext_traits::AsyncExt, id_type::GlobalPaymentId};
use error_stack::ResultExt;
use router_env::{instrument, tracing};
use super::{
BoxedOperation, Domain, GetTracker, Operation, OperationSessionSetters, UpdateTracker,
ValidateRequest, ValidateStatusForOperation,
};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::operations,
},
routes::{app::ReqState, SessionState},
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{self, enums},
PaymentsCancelData,
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentsCancel;
type BoxedCancelOperation<'b, F> = BoxedOperation<
'b,
F,
api::PaymentsCancelRequest,
hyperswitch_domain_models::payments::PaymentCancelData<F>,
>;
// Manual Operation trait implementation for V2
impl<F: Send + Clone + Sync> Operation<F, api::PaymentsCancelRequest> for &PaymentsCancel {
type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, api::PaymentsCancelRequest, Self::Data> + Send + Sync)>
{
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)>
{
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, api::PaymentsCancelRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)>
{
Ok(*self)
}
}
#[automatically_derived]
impl<F: Send + Clone + Sync> Operation<F, api::PaymentsCancelRequest> for PaymentsCancel {
type Data = hyperswitch_domain_models::payments::PaymentCancelData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, api::PaymentsCancelRequest, Self::Data> + Send + Sync)>
{
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)>
{
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, api::PaymentsCancelRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, api::PaymentsCancelRequest> + Send + Sync)>
{
Ok(self)
}
}
#[cfg(feature = "v2")]
impl<F: Send + Clone + Sync>
ValidateRequest<
F,
api::PaymentsCancelRequest,
hyperswitch_domain_models::payments::PaymentCancelData<F>,
> for PaymentsCancel
{
#[instrument(skip_all)]
fn validate_request(
&self,
_request: &api::PaymentsCancelRequest,
merchant_context: &domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
Ok(operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
})
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Send + Clone + Sync>
GetTracker<
F,
hyperswitch_domain_models::payments::PaymentCancelData<F>,
api::PaymentsCancelRequest,
> for PaymentsCancel
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &api::PaymentsCancelRequest,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<hyperswitch_domain_models::payments::PaymentCancelData<F>>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Failed to find payment intent for cancellation")?;
self.validate_status_for_operation(payment_intent.status)?;
let active_attempt_id = payment_intent.active_attempt_id.as_ref().ok_or_else(|| {
errors::ApiErrorResponse::InvalidRequestData {
message: "Payment cancellation not possible - no active payment attempt found"
.to_string(),
}
})?;
let payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
active_attempt_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Failed to find payment attempt for cancellation")?;
let mut payment_data = hyperswitch_domain_models::payments::PaymentCancelData {
flow: PhantomData,
payment_intent,
payment_attempt,
};
payment_data.set_cancellation_reason(request.cancellation_reason.clone());
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone + Send + Sync>
UpdateTracker<
F,
hyperswitch_domain_models::payments::PaymentCancelData<F>,
api::PaymentsCancelRequest,
> for PaymentsCancel
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: hyperswitch_domain_models::payments::PaymentCancelData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
merchant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
BoxedCancelOperation<'b, F>,
hyperswitch_domain_models::payments::PaymentCancelData<F>,
)>
where
F: 'b + Send,
{
let db = &*state.store;
let key_manager_state = &state.into();
let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::VoidUpdate {
status: enums::AttemptStatus::VoidInitiated,
cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(),
updated_by: storage_scheme.to_string(),
};
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
merchant_key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Failed to update payment attempt for cancellation")?;
payment_data.set_payment_attempt(updated_payment_attempt);
Ok((Box::new(self), payment_data))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Send + Clone + Sync>
Domain<F, api::PaymentsCancelRequest, hyperswitch_domain_models::payments::PaymentCancelData<F>>
for PaymentsCancel
{
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut hyperswitch_domain_models::payments::PaymentCancelData<F>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<(BoxedCancelOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
Ok((Box::new(*self), None))
}
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut hyperswitch_domain_models::payments::PaymentCancelData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedCancelOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(*self), None, None))
}
async fn perform_routing<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
state: &SessionState,
payment_data: &mut hyperswitch_domain_models::payments::PaymentCancelData<F>,
) -> RouterResult<api::ConnectorCallType> {
let payment_attempt = &payment_data.payment_attempt;
let connector = payment_attempt
.connector
.as_ref()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector not found for payment cancellation")?;
let merchant_connector_id = payment_attempt
.merchant_connector_id
.as_ref()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector ID not found for payment cancellation")?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
Some(merchant_connector_id.to_owned()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
Ok(api::ConnectorCallType::PreDetermined(connector_data.into()))
}
}
impl ValidateStatusForOperation for PaymentsCancel {
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::RequiresCapture => Ok(()),
common_enums::IntentStatus::Succeeded
| 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::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::Conflicted
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: [
common_enums::IntentStatus::RequiresCapture,
common_enums::IntentStatus::PartiallyCapturedAndCapturable,
common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture,
]
.map(|enum_value| enum_value.to_string())
.join(", "),
})
}
}
}
}
| crates/router/src/core/payments/operations/payment_cancel_v2.rs | router::src::core::payments::operations::payment_cancel_v2 | 2,687 | true |
// File: crates/router/src/core/payments/operations/payment_attempt_list.rs
// Module: router::src::core::payments::operations::payment_attempt_list
use std::marker::PhantomData;
#[cfg(feature = "v2")]
use api_models::{enums::FrmSuggestion, payments::PaymentAttemptListRequest};
use async_trait::async_trait;
use common_utils::errors::CustomResult;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult},
payments::{self, operations},
},
db::errors::StorageErrorExt,
routes::{app::ReqState, SessionState},
types::{
api, domain,
storage::{self, enums},
},
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentGetListAttempts;
impl<F: Send + Clone + Sync> Operation<F, PaymentAttemptListRequest> for &PaymentGetListAttempts {
type Data = payments::PaymentAttemptListData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentAttemptListRequest, Self::Data> + Send + Sync)>
{
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentAttemptListRequest> + Send + Sync)>
{
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentAttemptListRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentAttemptListRequest> + Send + Sync)>
{
Ok(*self)
}
}
impl<F: Send + Clone + Sync> Operation<F, PaymentAttemptListRequest> for PaymentGetListAttempts {
type Data = payments::PaymentAttemptListData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, PaymentAttemptListRequest, Self::Data> + Send + Sync)>
{
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentAttemptListRequest> + Send + Sync)>
{
Ok(self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentAttemptListRequest, Self::Data>)> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentAttemptListRequest> + Send + Sync)>
{
Ok(self)
}
}
type PaymentAttemptsListOperation<'b, F> =
BoxedOperation<'b, F, PaymentAttemptListRequest, payments::PaymentAttemptListData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync>
GetTracker<F, payments::PaymentAttemptListData<F>, PaymentAttemptListRequest>
for PaymentGetListAttempts
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
_payment_id: &common_utils::id_type::GlobalPaymentId,
request: &PaymentAttemptListRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<payments::PaymentAttemptListData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_attempt_list = db
.find_payment_attempts_by_payment_intent_id(
key_manager_state,
&request.payment_intent_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_data = payments::PaymentAttemptListData {
flow: PhantomData,
payment_attempt_list,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync>
UpdateTracker<F, payments::PaymentAttemptListData<F>, PaymentAttemptListRequest>
for PaymentGetListAttempts
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: payments::PaymentAttemptListData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentAttemptsListOperation<'b, F>,
payments::PaymentAttemptListData<F>,
)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, PaymentAttemptListRequest, payments::PaymentAttemptListData<F>>
for PaymentGetListAttempts
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &PaymentAttemptListRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
Ok(operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
})
}
}
#[async_trait]
impl<F: Clone + Send + Sync>
Domain<F, PaymentAttemptListRequest, payments::PaymentAttemptListData<F>>
for PaymentGetListAttempts
{
#[instrument(skip_all)]
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut payments::PaymentAttemptListData<F>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, PaymentAttemptListRequest, payments::PaymentAttemptListData<F>>,
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 payments::PaymentAttemptListData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentAttemptsListOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn perform_routing<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
_state: &SessionState,
_payment_data: &mut payments::PaymentAttemptListData<F>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
Ok(api::ConnectorCallType::Skip)
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut payments::PaymentAttemptListData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
| crates/router/src/core/payments/operations/payment_attempt_list.rs | router::src::core::payments::operations::payment_attempt_list | 1,761 | true |
// File: crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
// Module: router::src::core::payments::operations::payment_cancel_post_capture
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
routes::{app::ReqState, SessionState},
services,
types::{
self as core_types,
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "cancel_post_capture")]
pub struct PaymentCancelPostCapture;
type PaymentCancelPostCaptureOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelPostCaptureRequest>
for PaymentCancelPostCapture
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsCancelPostCaptureRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<
'a,
F,
api::PaymentsCancelPostCaptureRequest,
PaymentData<F>,
>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::Succeeded,
enums::IntentStatus::PartiallyCaptured,
enums::IntentStatus::PartiallyCapturedAndCapturable,
],
"cancel_post_capture",
)?;
let mut payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
payment_attempt
.cancellation_reason
.clone_from(&request.cancellation_reason);
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>>
for PaymentCancelPostCapture
{
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> errors::CustomResult<
(
PaymentCancelPostCaptureOperation<'a, F>,
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 PaymentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentCancelPostCaptureOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
_request: &api::PaymentsCancelPostCaptureRequest,
_payment_intent: &storage::PaymentIntent,
) -> errors::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,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelPostCaptureRequest>
for PaymentCancelPostCapture
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCancelPostCaptureOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, api::PaymentsCancelPostCaptureRequest, PaymentData<F>>
for PaymentCancelPostCapture
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCancelPostCaptureRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
PaymentCancelPostCaptureOperation<'b, F>,
operations::ValidateResult,
)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| crates/router/src/core/payments/operations/payment_cancel_post_capture.rs | router::src::core::payments::operations::payment_cancel_post_capture | 2,328 | true |
// File: crates/router/src/core/payments/operations/payment_create_intent.rs
// Module: router::src::core::payments::operations::payment_create_intent
use std::marker::PhantomData;
use api_models::{enums::FrmSuggestion, payments::PaymentsCreateIntentRequest};
use async_trait::async_trait;
use common_utils::{
errors::CustomResult,
ext_traits::Encode,
types::{authentication, keymanager::ToEncryptable},
};
use error_stack::ResultExt;
use masking::PeekInterface;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations},
},
routes::{app::ReqState, SessionState},
types::{
api,
domain::{self, types as domain_types},
storage::{self, enums},
},
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentIntentCreate;
impl<F: Send + Clone + Sync> Operation<F, PaymentsCreateIntentRequest> for &PaymentIntentCreate {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, PaymentsCreateIntentRequest, Self::Data> + Send + Sync),
> {
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)>
{
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsCreateIntentRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)>
{
Ok(*self)
}
}
impl<F: Send + Clone + Sync> Operation<F, PaymentsCreateIntentRequest> for PaymentIntentCreate {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, PaymentsCreateIntentRequest, Self::Data> + Send + Sync),
> {
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)>
{
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsCreateIntentRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsCreateIntentRequest> + Send + Sync)>
{
Ok(self)
}
}
type PaymentsCreateIntentOperation<'b, F> =
BoxedOperation<'b, F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync>
GetTracker<F, payments::PaymentIntentData<F>, PaymentsCreateIntentRequest>
for PaymentIntentCreate
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &PaymentsCreateIntentRequest,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> {
let db = &*state.store;
if let Some(routing_algorithm_id) = request.routing_algorithm_id.as_ref() {
helpers::validate_routing_id_with_profile_id(
db,
routing_algorithm_id,
profile.get_id(),
)
.await?;
}
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::PaymentIntent),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::to_encryptable(
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent {
shipping_address: request.shipping.clone().map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode shipping address")?.map(masking::Secret::new),
billing_address: request.billing.clone().map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode billing address")?.map(masking::Secret::new),
customer_details: None,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let payment_intent_domain =
hyperswitch_domain_models::payments::PaymentIntent::create_domain_model_from_request(
payment_id,
merchant_context,
profile,
request.clone(),
encrypted_data,
)
.await?;
let payment_intent = db
.insert_payment_intent(
key_manager_state,
payment_intent_domain,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: format!(
"Payment Intent with payment_id {} already exists",
payment_id.get_string_repr()
),
})
.attach_printable("failed while inserting new payment intent")?;
let client_secret = helpers::create_client_secret(
state,
merchant_context.get_merchant_account().get_id(),
authentication::ResourceId::Payment(payment_id.clone()),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create client secret")?;
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
client_secret: Some(client_secret.secret),
sessions_token: vec![],
vault_session_details: None,
connector_customer_id: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsCreateIntentRequest>
for PaymentIntentCreate
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
payment_data: payments::PaymentIntentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentsCreateIntentOperation<'b, F>,
payments::PaymentIntentData<F>,
)>
where
F: 'b + Send,
{
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone>
ValidateRequest<F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>>
for PaymentIntentCreate
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &PaymentsCreateIntentRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
Ok(operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
})
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>>
for PaymentIntentCreate
{
#[instrument(skip_all)]
async fn get_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut payments::PaymentIntentData<F>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, PaymentsCreateIntentRequest, payments::PaymentIntentData<F>>,
Option<domain::Customer>,
),
errors::StorageError,
> {
// validate customer_id if sent in the request
if let Some(id) = payment_data.payment_intent.customer_id.clone() {
state
.store
.find_customer_by_global_id(&state.into(), &id, merchant_key_store, storage_scheme)
.await?;
}
Ok((Box::new(self), None))
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
_state: &'a SessionState,
_payment_data: &mut payments::PaymentIntentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentsCreateIntentOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn perform_routing<'a>(
&'a self,
merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
state: &SessionState,
// TODO: do not take the whole payment data here
payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
Ok(api::ConnectorCallType::Skip)
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
| crates/router/src/core/payments/operations/payment_create_intent.rs | router::src::core::payments::operations::payment_create_intent | 2,384 | true |
// File: crates/router/src/core/payments/operations/payment_complete_authorize.rs
// Module: router::src::core::payments::operations::payment_complete_authorize
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use error_stack::{report, ResultExt};
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, CustomerAcceptance, PaymentIdTypeExt},
domain,
storage::{self, enums as storage_enums},
},
utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "authorize")]
pub struct CompleteAuthorize;
type CompleteAuthorizeOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
for CompleteAuthorize
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>
{
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let (mut payment_intent, mut payment_attempt, currency, amount);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once client_secret auth is solved
payment_intent.setup_future_usage = request
.setup_future_usage
.or(payment_intent.setup_future_usage);
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Failed,
storage_enums::IntentStatus::Succeeded,
],
"confirm",
)?;
let browser_info = request
.browser_info
.clone()
.as_ref()
.map(utils::Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let recurring_details = request.recurring_details.clone();
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
&payment_intent.active_attempt.get_id(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let mandate_type = m_helpers::get_mandate_type(
request.mandate_data.clone(),
request.off_session,
payment_intent.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
payment_attempt.payment_method,
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
})?;
let m_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data,
mandate_connector,
payment_method_info,
} = Box::pin(helpers::get_token_pm_type_mandate_details(
state,
request,
mandate_type.to_owned(),
merchant_context,
payment_attempt.payment_method_id.clone(),
payment_intent.customer_id.as_ref(),
))
.await?;
let customer_acceptance: Option<CustomerAcceptance> =
request.customer_acceptance.clone().or(payment_method_info
.clone()
.map(|pm| {
pm.customer_acceptance
.parse_value::<CustomerAcceptance>("CustomerAcceptance")
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to CustomerAcceptance")?);
let token = token.or_else(|| payment_attempt.payment_token.clone());
if let Some(payment_method) = payment_method {
let should_validate_pm_or_token_given =
//this validation should happen if data was stored in the vault
helpers::should_store_payment_method_data_in_vault(
&state.conf.temp_locker_enable_config,
payment_attempt.connector.clone(),
payment_method,
);
if should_validate_pm_or_token_given {
helpers::validate_pm_or_token_given(
&request.payment_method,
&request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
&request.payment_method_type,
&mandate_type,
&token,
&request.ctp_service_details,
)?;
}
}
let token_data = if let Some((token, payment_method)) = token
.as_ref()
.zip(payment_method.or(payment_attempt.payment_method))
{
Some(
helpers::retrieve_payment_token_data(state, token.clone(), Some(payment_method))
.await?,
)
} else {
None
};
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.browser_info = browser_info.or(payment_attempt.browser_info);
payment_attempt.payment_method_type =
payment_method_type.or(payment_attempt.payment_method_type);
payment_attempt.payment_experience = request
.payment_experience
.or(payment_attempt.payment_experience);
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
let customer_id = payment_intent
.customer_id
.as_ref()
.or(request.customer_id.as_ref())
.cloned();
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
customer_id.as_ref(),
)?;
let shipping_address = helpers::create_or_update_address_for_payment_by_request(
state,
request.shipping.as_ref(),
payment_intent.shipping_address_id.clone().as_deref(),
merchant_id,
payment_intent.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
storage_scheme,
)
.await?;
payment_intent.shipping_address_id = shipping_address
.as_ref()
.map(|shipping_address| shipping_address.address_id.clone());
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let redirect_response = request
.feature_metadata
.as_ref()
.and_then(|fm| fm.redirect_response.clone());
payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
payment_intent.return_url = request
.return_url
.as_ref()
.map(|a| a.to_string())
.or(payment_intent.return_url);
payment_intent.allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting allowed_payment_types to Value")?
.or(payment_intent.allowed_payment_method_types);
payment_intent.connector_metadata = request
.get_connector_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting connector_metadata to Value")?
.or(payment_intent.connector_metadata);
payment_intent.feature_metadata = request
.get_feature_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting feature_metadata to Value")?
.or(payment_intent.feature_metadata);
payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata);
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data;
let mandate_details_present =
payment_attempt.mandate_details.is_some() || request.mandate_data.is_some();
helpers::validate_mandate_data_and_future_usage(
payment_intent.setup_future_usage,
mandate_details_present,
)?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let creds_identifier =
request
.merchant_connector_details
.as_ref()
.map(|merchant_connector_details| {
merchant_connector_details.creds_identifier.to_owned()
});
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id: None,
mandate_connector,
setup_mandate,
customer_acceptance,
token,
token_data,
address: PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: request.confirm,
payment_method_data: request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)),
payment_method_token: None,
payment_method_info,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: request.card_cvc.clone(),
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: request.threeds_method_comp_ind.clone(),
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let customer_details = Some(CustomerDetails {
customer_id,
name: request.name.clone(),
email: request.email.clone(),
phone: request.phone.clone(),
phone_country_code: request.phone_country_code.clone(),
tax_registration_id: None,
});
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details,
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for CompleteAuthorize {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(CompleteAuthorizeOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
CompleteAuthorizeOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
let (op, payment_method_data, pm_id) = Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await?;
Ok((op, payment_method_data, pm_id))
}
#[instrument(skip_all)]
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a SessionState,
_payment_attempt: &storage::PaymentAttempt,
_requeue: bool,
_schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
// Use a new connector in the confirm call or use the same one which was passed when
// creating the payment or if none is passed then use the routing algorithm
helpers::get_connector_default(state, request.routing.clone()).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(CompleteAuthorizeOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::CompleteAuthorizeUpdate {
shipping_address_id: payment_data.payment_intent.shipping_address_id.clone()
};
let db = &*state.store;
let payment_intent = payment_data.payment_intent.clone();
let updated_payment_intent = db
.update_payment_intent(
&state.into(),
payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCompleteAuthorize))
.with(payment_data.to_event())
.emit();
payment_data.payment_intent = updated_payment_intent;
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
for CompleteAuthorize
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(
CompleteAuthorizeOperation<'b, F>,
operations::ValidateResult,
)> {
let payment_id = request
.payment_id
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
helpers::validate_payment_method_fields_present(request)?;
let _mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
}
| crates/router/src/core/payments/operations/payment_complete_authorize.rs | router::src::core::payments::operations::payment_complete_authorize | 4,104 | true |
// File: crates/router/src/core/payments/operations/payment_capture.rs
// Module: router::src::core::payments::operations::payment_capture
use std::{marker::PhantomData, ops::Deref};
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, types::MultipleCaptureData},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self as core_types,
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums, payment_attempt::PaymentAttemptExt},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "capture")]
pub struct PaymentCapture;
type PaymentCaptureOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsCaptureRequest, payments::PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest>
for PaymentCapture
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsCaptureRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<
'a,
F,
api::PaymentsCaptureRequest,
payments::PaymentData<F>,
>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let (payment_intent, mut payment_attempt, currency, amount);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_attempt
.amount_to_capture
.update_value(request.amount_to_capture);
let capture_method = payment_attempt
.capture_method
.get_required_value("capture_method")?;
helpers::validate_status_with_capture_method(payment_intent.status, capture_method)?;
if !*payment_attempt
.is_overcapture_enabled
.unwrap_or_default()
.deref()
{
helpers::validate_amount_to_capture(
payment_attempt.amount_capturable.get_amount_as_i64(),
request
.amount_to_capture
.map(|capture_amount| capture_amount.get_amount_as_i64()),
)?;
}
helpers::validate_capture_method(capture_method)?;
let multiple_capture_data = if capture_method == enums::CaptureMethod::ManualMultiple {
let amount_to_capture = request
.amount_to_capture
.get_required_value("amount_to_capture")?;
helpers::validate_amount_to_capture(
payment_attempt.amount_capturable.get_amount_as_i64(),
Some(amount_to_capture.get_amount_as_i64()),
)?;
let previous_captures = db
.find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&payment_attempt.merchant_id,
&payment_attempt.payment_id,
&payment_attempt.attempt_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let capture = db
.insert_capture(
payment_attempt
.make_new_capture(amount_to_capture, enums::CaptureStatus::Started)?,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
Some(MultipleCaptureData::new_for_create(
previous_captures,
capture,
))
} else {
None
};
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
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,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = payments::PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
force_sync: None,
all_keys_required: None,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRequest>
for PaymentCapture
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
db: &'b SessionState,
req_state: ReqState,
mut payment_data: payments::PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_mechant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCaptureOperation<'b, F>, payments::PaymentData<F>)>
where
F: 'b + Send,
{
payment_data.payment_attempt = if payment_data.multiple_capture_data.is_some()
|| payment_data.payment_attempt.amount_to_capture.is_some()
{
let multiple_capture_count = payment_data
.multiple_capture_data
.as_ref()
.map(|multiple_capture_data| multiple_capture_data.get_captures_count())
.transpose()?;
let amount_to_capture = payment_data.payment_attempt.amount_to_capture;
db.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
storage::PaymentAttemptUpdate::CaptureUpdate {
amount_to_capture,
multiple_capture_count,
updated_by: storage_scheme.to_string(),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?
} else {
payment_data.payment_attempt
};
let capture_amount = payment_data.payment_attempt.amount_to_capture;
let multiple_capture_count = payment_data.payment_attempt.multiple_capture_count;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCapture {
capture_amount,
multiple_capture_count,
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync>
ValidateRequest<F, api::PaymentsCaptureRequest, payments::PaymentData<F>> for PaymentCapture
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCaptureRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentCaptureOperation<'b, F>, operations::ValidateResult)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| crates/router/src/core/payments/operations/payment_capture.rs | router::src::core::payments::operations::payment_capture | 2,533 | true |
// File: crates/router/src/core/payments/operations/payment_create.rs
// Module: router::src::core::payments::operations::payment_create
use std::marker::PhantomData;
use api_models::{
enums::FrmSuggestion, mandates::RecurringDetails, payment_methods::PaymentMethodsData,
payments::GetAddressFromPaymentMethodData,
};
use async_trait::async_trait;
use common_types::payments as common_payments_types;
use common_utils::{
ext_traits::{AsyncExt, Encode, ValueExt},
type_name,
types::{
keymanager::{Identifier, KeyManagerState, ToEncryptable},
MinorUnit,
},
};
use diesel_models::{
ephemeral_key,
payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId,
};
use error_stack::{self, ResultExt};
use hyperswitch_domain_models::{
mandates::MandateDetails,
payments::{
payment_attempt::PaymentAttempt, payment_intent::CustomerData,
FromRequestEncryptablePaymentIntent,
},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use router_derive::PaymentOperation;
use router_env::{instrument, logger, tracing};
use time::PrimitiveDateTime;
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_link,
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
db::StorageInterface,
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain,
storage::{
self,
enums::{self, IntentStatus},
},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "authorize")]
pub struct PaymentCreate;
type PaymentCreateOperation<'a, F> = BoxedOperation<'a, F, api::PaymentsRequest, PaymentData<F>>;
/// The `get_trackers` function for `PaymentsCreate` is an entrypoint for new payments
/// This will create all the entities required for a new payment from the request
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate {
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>
{
let db = &*state.store;
let key_manager_state = &state.into();
let ephemeral_key = Self::get_ephemeral_key(request, state, merchant_context).await;
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let money @ (amount, currency) = payments_create_request_validation(request)?;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v1")]
helpers::validate_business_details(
request.business_country,
request.business_label.as_ref(),
merchant_context,
)?;
// If profile id is not passed, get it from the business_country and business_label
#[cfg(feature = "v1")]
let profile_id = core_utils::get_profile_id_from_business_details(
key_manager_state,
request.business_country,
request.business_label.as_ref(),
merchant_context,
request.profile_id.as_ref(),
&*state.store,
true,
)
.await?;
// Profile id will be mandatory in v2 in the request / headers
#[cfg(feature = "v2")]
let profile_id = request
.profile_id
.clone()
.get_required_value("profile_id")
.attach_printable("Profile id is a mandatory parameter")?;
// TODO: eliminate a redundant db call to fetch the business profile
// Validate whether profile_id passed in request is valid and is linked to the merchant
let business_profile = if let Some(business_profile) =
core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_id,
)
.await?
{
business_profile
} else {
db.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?
};
let customer_acceptance = request.customer_acceptance.clone();
let recurring_details = request.recurring_details.clone();
let mandate_type = m_helpers::get_mandate_type(
request.mandate_data.clone(),
request.off_session,
request.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
request.payment_method,
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
})?;
let m_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data,
mandate_connector,
payment_method_info,
} = helpers::get_token_pm_type_mandate_details(
state,
request,
mandate_type,
merchant_context,
None,
None,
)
.await?;
helpers::validate_allowed_payment_method_types_request(
state,
&profile_id,
merchant_context,
request.allowed_payment_method_types.clone(),
)
.await?;
let customer_details = helpers::get_customer_details_from_request(request);
let shipping_address = helpers::create_or_find_address_for_payment_by_request(
state,
request.shipping.as_ref(),
None,
merchant_id,
customer_details.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::create_or_find_address_for_payment_by_request(
state,
request.billing.as_ref(),
None,
merchant_id,
customer_details.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing_address =
helpers::create_or_find_address_for_payment_by_request(
state,
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.billing.as_ref()),
None,
merchant_id,
customer_details.customer_id.as_ref(),
merchant_context.get_merchant_key_store(),
&payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let browser_info = request
.browser_info
.clone()
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let attempt_id = if core_utils::is_merchant_enabled_for_payment_id_as_connector_request_id(
&state.conf,
merchant_id,
) {
payment_id.get_string_repr().to_string()
} else {
payment_id.get_attempt_id(1)
};
let session_expiry =
common_utils::date_time::now().saturating_add(time::Duration::seconds(
request.session_expiry.map(i64::from).unwrap_or(
business_profile
.session_expiry
.unwrap_or(consts::DEFAULT_SESSION_EXPIRY),
),
));
let payment_link_data = match request.payment_link {
Some(true) => {
let merchant_name = merchant_context
.get_merchant_account()
.merchant_name
.clone()
.map(|name| name.into_inner().peek().to_owned())
.unwrap_or_default();
let default_domain_name = state.base_url.clone();
let (payment_link_config, domain_name) =
payment_link::get_payment_link_config_based_on_priority(
request.payment_link_config.clone(),
business_profile.payment_link_config.clone(),
merchant_name,
default_domain_name,
request.payment_link_config_id.clone(),
)?;
create_payment_link(
request,
payment_link_config,
merchant_id,
payment_id.clone(),
db,
amount,
request.description.clone(),
profile_id.clone(),
domain_name,
session_expiry,
header_payload.locale.clone(),
)
.await?
}
_ => None,
};
let payment_intent_new = Self::make_payment_intent(
state,
&payment_id,
merchant_context,
money,
request,
shipping_address
.as_ref()
.map(|address| address.address_id.clone()),
payment_link_data.clone(),
billing_address
.as_ref()
.map(|address| address.address_id.clone()),
attempt_id,
profile_id.clone(),
session_expiry,
&business_profile,
request.is_payment_id_from_merchant,
)
.await?;
let (payment_attempt_new, additional_payment_data) = Self::make_payment_attempt(
&payment_id,
merchant_id,
&merchant_context.get_merchant_account().organization_id,
money,
payment_method,
payment_method_type,
request,
browser_info,
state,
payment_method_billing_address
.as_ref()
.map(|address| address.address_id.clone()),
&payment_method_info,
merchant_context.get_merchant_key_store(),
profile_id,
&customer_acceptance,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_intent = db
.insert_payment_intent(
key_manager_state,
payment_intent_new,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
order_details.to_owned(),
payment_intent.amount,
false,
)?;
}
#[cfg(feature = "v1")]
let mut payment_attempt = db
.insert_payment_attempt(payment_attempt_new, storage_scheme)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
#[cfg(feature = "v2")]
let payment_attempt = db
.insert_payment_attempt(
key_manager_state,
merchant_key_store,
payment_attempt_new,
storage_scheme,
)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
payment_id: payment_id.clone(),
})?;
let mandate_details_present = payment_attempt.mandate_details.is_some();
helpers::validate_mandate_data_and_future_usage(
request.setup_future_usage,
mandate_details_present,
)?;
// connector mandate reference update history
let mandate_id = request
.mandate_id
.as_ref()
.or_else(|| {
request.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
RecurringDetails::MandateId(id) => Some(id),
_ => None,
})
})
.async_and_then(|mandate_id| async {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound);
Some(mandate.and_then(|mandate_obj| {
match (
mandate_obj.network_transaction_id,
mandate_obj.connector_mandate_ids,
) {
(_, Some(connector_mandate_id)) => connector_mandate_id
.parse_value("ConnectorMandateId")
.change_context(errors::ApiErrorResponse::MandateNotFound)
.map(|connector_id: api_models::payments::ConnectorMandateReferenceId| {
api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
connector_id.get_connector_mandate_id(),
connector_id.get_payment_method_id(),
None,
None,
connector_id.get_connector_mandate_request_reference_id(),
)
))
}
}),
(Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::NetworkMandateId(
network_tx_id,
),
),
}),
(_, _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: None,
}),
}
}))
})
.await
.transpose()?;
let mandate_id = if mandate_id.is_none() {
request
.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
RecurringDetails::ProcessorPaymentToken(token) => {
Some(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
Some(token.processor_payment_token.clone()),
None,
None,
None,
None,
),
),
),
})
}
_ => None,
})
} else {
mandate_id
};
let operation = payments::if_not_create_change_operation::<_, F>(
payment_intent.status,
request.confirm,
self,
);
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,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data;
let surcharge_details = request.surcharge_details.map(|request_surcharge_details| {
payments::types::SurchargeDetails::from((&request_surcharge_details, &payment_attempt))
});
let payment_method_data_after_card_bin_call = request
.payment_method_data
.as_ref()
.and_then(|payment_method_data_from_request| {
payment_method_data_from_request
.payment_method_data
.as_ref()
})
.zip(additional_payment_data)
.map(|(payment_method_data, additional_payment_data)| {
payment_method_data.apply_additional_payment_data(additional_payment_data)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Card cobadge check failed due to an invalid card network regex")?;
let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info {
let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| {
v.parse_value("PaymentMethodsData")
.map_err(|err| {
router_env::logger::info!(
"PaymentMethodsData deserialization failed: {:?}",
err
)
})
.ok()
})
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
card_detail_from_locker.map(|card_details| {
let additional_data = card_details.into();
api_models::payments::AdditionalPaymentData::Card(Box::new(additional_data))
})
} else {
None
};
// Only set `payment_attempt.payment_method_data` if `additional_pm_data_from_locker` is not None
if let Some(additional_pm_data) = additional_pm_data_from_locker.as_ref() {
payment_attempt.payment_method_data = Some(
Encode::encode_to_value(additional_pm_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?,
);
}
let amount = payment_attempt.get_total_amount().into();
payment_attempt.connector_mandate_detail =
Some(DieselConnectorMandateReferenceId::foreign_from(
api_models::payments::ConnectorMandateReferenceId::new(
None,
None,
None, // update_history
None, // mandate_metadata
Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)), // connector_mandate_request_reference_id
),
));
let address = PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing_address.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
);
let payment_method_data_billing = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.as_ref())
.and_then(|payment_method_data_billing| {
payment_method_data_billing.get_billing_address()
})
.map(From::from);
let unified_address =
address.unify_with_payment_method_data_billing(payment_method_data_billing);
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id: mandate_id.clone(),
mandate_connector,
setup_mandate,
customer_acceptance,
token,
address: unified_address,
token_data: None,
confirm: request.confirm,
payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),
payment_method_token: None,
payment_method_info,
refunds: vec![],
disputes: vec![],
attempts: None,
force_sync: None,
all_keys_required: None,
sessions_token: vec![],
card_cvc: request.card_cvc.clone(),
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key,
multiple_capture_data: None,
redirect_response: None,
surcharge_details,
frm_message: None,
payment_link_data,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation,
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentCreate {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<(PaymentCreateOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
async fn payments_dynamic_tax_calculation<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::Profile,
merchant_context: &domain::MerchantContext,
) -> CustomResult<(), errors::ApiErrorResponse> {
let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
let skip_external_tax_calculation = payment_data
.payment_intent
.skip_external_tax_calculation
.unwrap_or(false);
if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
let merchant_connector_id = business_profile
.tax_connector_id
.as_ref()
.get_required_value("business_profile.tax_connector_id")?;
#[cfg(feature = "v1")]
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&business_profile.merchant_id,
merchant_connector_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
#[cfg(feature = "v2")]
let mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
merchant_connector_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_connector_id.get_string_repr().to_string(),
},
)?;
let connector_data =
api::TaxCalculateConnectorData::get_connector_by_name(&mca.connector_name)?;
let router_data = core_utils::construct_payments_dynamic_tax_calculation_router_data(
state,
merchant_context,
payment_data,
&mca,
)
.await?;
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CalculateTax,
types::PaymentsTaxCalculationData,
types::TaxCalculationResponseData,
> = connector_data.connector.get_connector_integration();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Tax connector Response Failed")?;
let tax_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.clone().to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
payment_data.payment_intent.tax_details = Some(diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_response.order_tax_amount,
}),
payment_method_type: None,
});
Ok(())
} else {
Ok(())
}
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: enums::MerchantStorageScheme,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentCreateOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
merchant_key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await
}
#[instrument(skip_all)]
async fn add_task_to_process_tracker<'a>(
&'a self,
_state: &'a SessionState,
_payment_attempt: &PaymentAttempt,
_requeue: bool,
_schedule_time: Option<PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
helpers::get_connector_default(state, request.routing.clone()).await
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentCreate {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCreateOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let status = match payment_data.payment_intent.status {
IntentStatus::RequiresPaymentMethod => match payment_data.payment_method_data {
Some(_) => Some(IntentStatus::RequiresConfirmation),
_ => None,
},
IntentStatus::RequiresConfirmation => {
if let Some(true) = payment_data.confirm {
//TODO: do this later, request validation should happen before
Some(IntentStatus::Processing)
} else {
None
}
}
_ => None,
};
let payment_token = payment_data.token.clone();
let connector = payment_data.payment_attempt.connector.clone();
let straight_through_algorithm = payment_data
.payment_attempt
.straight_through_algorithm
.clone();
let authorized_amount = payment_data.payment_attempt.get_total_amount();
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);
let routing_approach = payment_data.payment_attempt.routing_approach.clone();
let is_stored_credential = helpers::is_stored_credential(
&payment_data.recurring_details,
&payment_data.pm_token,
payment_data.mandate_id.is_some(),
payment_data.payment_attempt.is_stored_credential,
);
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
storage::PaymentAttemptUpdate::UpdateTrackers {
payment_token,
connector,
straight_through_algorithm,
amount_capturable: match payment_data.confirm.unwrap_or(true) {
true => Some(authorized_amount),
false => None,
},
surcharge_amount,
tax_amount,
updated_by: storage_scheme.to_string(),
merchant_connector_id,
routing_approach,
is_stored_credential,
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let customer_id = payment_data.payment_intent.customer_id.clone();
let raw_customer_details = customer
.map(|customer| CustomerData::foreign_try_from(customer.clone()))
.transpose()?;
let key_manager_state = state.into();
// Updation of Customer Details for the cases where both customer_id and specific customer
// details are provided in Payment Create Request
let customer_details = raw_customer_details
.clone()
.async_map(|customer_details| {
create_encrypted_data(&key_manager_state, key_store, customer_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?;
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
storage::PaymentIntentUpdate::PaymentCreateUpdate {
return_url: None,
status,
customer_id,
shipping_address_id: None,
billing_address_id: None,
customer_details,
updated_by: storage_scheme.to_string(),
},
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCreate))
.with(payment_data.to_event())
.emit();
// payment_data.mandate_id = response.and_then(|router_data| router_data.request.mandate_id);
Ok((
payments::is_confirm(self, payment_data.confirm),
payment_data,
))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
for PaymentCreate
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentCreateOperation<'b, F>, operations::ValidateResult)> {
helpers::validate_customer_information(request)?;
if let Some(amount) = request.amount {
helpers::validate_max_amount(amount)?;
}
if let Some(session_expiry) = &request.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
}
if let Some(payment_link) = &request.payment_link {
if *payment_link {
helpers::validate_payment_link_request(request)?;
}
};
let payment_id = request.payment_id.clone().ok_or(error_stack::report!(
errors::ApiErrorResponse::PaymentNotFound
))?;
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?;
helpers::validate_request_amount_and_amount_to_capture(
request.amount,
request.amount_to_capture,
request.surcharge_details,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount_to_capture".to_string(),
expected_format: "amount_to_capture lesser than amount".to_string(),
})?;
helpers::validate_amount_to_capture_and_capture_method(None, request)?;
helpers::validate_card_data(
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
)?;
helpers::validate_payment_method_fields_present(request)?;
let mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
request.validate_stored_credential().change_context(
errors::ApiErrorResponse::InvalidRequestData {
message:
"is_stored_credential should be true when reusing stored payment method data"
.to_string(),
},
)?;
helpers::validate_overcapture_request(
&request.enable_overcapture,
&request.capture_method,
)?;
request.validate_mit_request().change_context(
errors::ApiErrorResponse::InvalidRequestData {
message:
"`mit_category` requires both: (1) `off_session = true`, and (2) `recurring_details`."
.to_string(),
},
)?;
if request.confirm.unwrap_or(false) {
helpers::validate_pm_or_token_given(
&request.payment_method,
&request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
&request.payment_method_type,
&mandate_type,
&request.payment_token,
&request.ctp_service_details,
)?;
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
request.customer_id.as_ref().or(request
.customer
.as_ref()
.map(|customer| customer.id.clone())
.as_ref()),
)?;
}
if request.split_payments.is_some() {
let amount = request.amount.get_required_value("amount")?;
helpers::validate_platform_request_for_marketplace(
amount,
request.split_payments.clone(),
)?;
};
let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request
.routing
.clone()
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid straight through routing rules format".to_string(),
})
.attach_printable("Invalid straight through routing rules format")?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
}
impl PaymentCreate {
#[cfg(feature = "v2")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn make_payment_attempt(
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
organization_id: &common_utils::id_type::OrganizationId,
money: (api::Amount, enums::Currency),
payment_method: Option<enums::PaymentMethod>,
payment_method_type: Option<enums::PaymentMethodType>,
request: &api::PaymentsRequest,
browser_info: Option<serde_json::Value>,
state: &SessionState,
payment_method_billing_address_id: Option<String>,
payment_method_info: &Option<domain::PaymentMethod>,
_key_store: &domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
customer_acceptance: &Option<payments::CustomerAcceptance>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
storage::PaymentAttemptNew,
Option<api_models::payments::AdditionalPaymentData>,
)> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn make_payment_attempt(
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
organization_id: &common_utils::id_type::OrganizationId,
money: (api::Amount, enums::Currency),
payment_method: Option<enums::PaymentMethod>,
payment_method_type: Option<enums::PaymentMethodType>,
request: &api::PaymentsRequest,
browser_info: Option<serde_json::Value>,
state: &SessionState,
optional_payment_method_billing_address_id: Option<String>,
payment_method_info: &Option<domain::PaymentMethod>,
key_store: &domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
customer_acceptance: &Option<common_payments_types::CustomerAcceptance>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
storage::PaymentAttemptNew,
Option<api_models::payments::AdditionalPaymentData>,
)> {
let payment_method_data =
request
.payment_method_data
.as_ref()
.and_then(|payment_method_data_request| {
payment_method_data_request.payment_method_data.as_ref()
});
let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
let status = helpers::payment_attempt_status_fsm(payment_method_data, request.confirm);
let (amount, currency) = (money.0, Some(money.1));
let mut additional_pm_data = request
.payment_method_data
.as_ref()
.and_then(|payment_method_data_request| {
payment_method_data_request.payment_method_data.clone()
})
.async_map(|payment_method_data| async {
helpers::get_additional_payment_data(
&payment_method_data.into(),
&*state.store,
&profile_id,
)
.await
})
.await
.transpose()?
.flatten();
if additional_pm_data.is_none() {
// If recurring payment is made using payment_method_id, then fetch payment_method_data from retrieved payment_method object
additional_pm_data = payment_method_info.as_ref().and_then(|pm_info| {
pm_info
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| {
serde_json::from_value::<PaymentMethodsData>(v)
.map_err(|err| {
logger::error!(
"Unable to deserialize payment methods data: {:?}",
err
)
})
.ok()
})
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(card) => {
Some(api_models::payments::AdditionalPaymentData::Card(Box::new(
api::CardDetailFromLocker::from(card).into(),
)))
}
PaymentMethodsData::WalletDetails(wallet) => match payment_method_type {
Some(enums::PaymentMethodType::ApplePay) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: api::payments::ApplepayPaymentMethod::try_from(
wallet,
)
.inspect_err(|err| {
logger::error!(
"Unable to transform PaymentMethodDataWalletInfo to ApplepayPaymentMethod: {:?}",
err
)
})
.ok(),
google_pay: None,
samsung_pay: None,
})
}
Some(enums::PaymentMethodType::GooglePay) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: Some(wallet.into()),
samsung_pay: None,
})
}
Some(enums::PaymentMethodType::SamsungPay) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: Some(wallet.into()),
})
}
_ => None,
},
_ => None,
})
.or_else(|| match payment_method_type {
Some(enums::PaymentMethodType::Paypal) => {
Some(api_models::payments::AdditionalPaymentData::Wallet {
apple_pay: None,
google_pay: None,
samsung_pay: None,
})
}
_ => None,
})
});
};
let additional_pm_data_value = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
let attempt_id = if core_utils::is_merchant_enabled_for_payment_id_as_connector_request_id(
&state.conf,
merchant_id,
) {
payment_id.get_string_repr().to_owned()
} else {
payment_id.get_attempt_id(1)
};
if request.mandate_data.as_ref().is_some_and(|mandate_data| {
mandate_data.update_mandate_id.is_some() && mandate_data.mandate_type.is_some()
}) {
Err(errors::ApiErrorResponse::InvalidRequestData {message:"Only one field out of 'mandate_type' and 'update_mandate_id' was expected, found both".to_string()})?
}
let mandate_data = if let Some(update_id) = request
.mandate_data
.as_ref()
.and_then(|inner| inner.update_mandate_id.clone())
{
let mandate_details = MandateDetails {
update_mandate_id: Some(update_id),
};
Some(mandate_details)
} else {
None
};
let payment_method_type = Option::<enums::PaymentMethodType>::foreign_from((
payment_method_type,
additional_pm_data.as_ref(),
payment_method,
));
// TODO: remove once https://github.com/juspay/hyperswitch/issues/7421 is fixed
let payment_method_billing_address_id = match optional_payment_method_billing_address_id {
None => payment_method_info
.as_ref()
.and_then(|pm_info| pm_info.payment_method_billing_address.as_ref())
.map(|address| {
address.clone().deserialize_inner_value(|value| {
value.parse_value::<api_models::payments::Address>("Address")
})
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.ok()
.flatten()
.async_map(|addr| async move {
helpers::create_or_find_address_for_payment_by_request(
state,
Some(addr.get_inner()),
None,
merchant_id,
payment_method_info
.as_ref()
.map(|pmd_info| pmd_info.customer_id.clone())
.as_ref(),
key_store,
payment_id,
storage_scheme,
)
.await
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?
.flatten()
.map(|address| address.address_id),
address_id => address_id,
};
let is_stored_credential = helpers::is_stored_credential(
&request.recurring_details,
&request.payment_token,
request.mandate_id.is_some(),
request.is_stored_credential,
);
Ok((
storage::PaymentAttemptNew {
payment_id: payment_id.to_owned(),
merchant_id: merchant_id.to_owned(),
attempt_id,
status,
currency,
payment_method,
capture_method: request.capture_method,
capture_on: request.capture_on,
confirm: request.confirm.unwrap_or(false),
created_at,
modified_at,
last_synced,
authentication_type: request.authentication_type,
browser_info,
payment_experience: request.payment_experience,
payment_method_type,
payment_method_data: additional_pm_data_value,
amount_to_capture: request.amount_to_capture,
payment_token: request.payment_token.clone(),
mandate_id: request.mandate_id.clone(),
business_sub_label: request.business_sub_label.clone(),
mandate_details: request
.mandate_data
.as_ref()
.and_then(|inner| inner.mandate_type.clone().map(Into::into)),
external_three_ds_authentication_attempted: None,
mandate_data,
payment_method_billing_address_id,
net_amount: hyperswitch_domain_models::payments::payment_attempt::NetAmount::from_payments_request(
request,
MinorUnit::from(amount),
),
save_to_locker: None,
connector: None,
error_message: None,
offer_amount: None,
payment_method_id: payment_method_info
.as_ref()
.map(|pm_info| pm_info.get_id().clone()),
cancellation_reason: None,
error_code: None,
connector_metadata: None,
straight_through_algorithm: None,
preprocessing_step_id: None,
error_reason: None,
connector_response_reference_id: None,
multiple_capture_count: None,
amount_capturable: MinorUnit::new(i64::default()),
updated_by: String::default(),
authentication_data: None,
encoded_data: None,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
fingerprint_id: None,
authentication_connector: None,
authentication_id: None,
client_source: None,
client_version: None,
customer_acceptance: customer_acceptance
.clone()
.map(|customer_acceptance| customer_acceptance.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize customer_acceptance")?
.map(Secret::new),
organization_id: organization_id.clone(),
profile_id,
connector_mandate_detail: None,
request_extended_authorization: None,
extended_authorization_applied: None,
capture_before: None,
card_discovery: None,
processor_merchant_id: merchant_id.to_owned(),
created_by: None,
setup_future_usage_applied: request.setup_future_usage,
routing_approach: Some(common_enums::RoutingApproach::default()),
connector_request_reference_id: None,
network_transaction_id:None,
network_details:None,
is_stored_credential,
authorized_amount: None,
},
additional_pm_data,
))
}
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
async fn make_payment_intent(
state: &SessionState,
payment_id: &common_utils::id_type::PaymentId,
merchant_context: &domain::MerchantContext,
money: (api::Amount, enums::Currency),
request: &api::PaymentsRequest,
shipping_address_id: Option<String>,
payment_link_data: Option<api_models::payments::PaymentLinkResponse>,
billing_address_id: Option<String>,
active_attempt_id: String,
profile_id: common_utils::id_type::ProfileId,
session_expiry: PrimitiveDateTime,
business_profile: &domain::Profile,
is_payment_id_from_merchant: bool,
) -> RouterResult<storage::PaymentIntent> {
let created_at @ modified_at @ last_synced = common_utils::date_time::now();
let status = helpers::payment_intent_status_fsm(
request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
}),
request.confirm,
);
let client_secret = payment_id.generate_client_secret();
let (amount, currency) = (money.0, Some(money.1));
let order_details = request
.get_order_details_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?;
let allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting allowed_payment_types to Value")?;
let connector_metadata = request
.get_connector_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting connector_metadata to Value")?;
let feature_metadata = request
.get_feature_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting feature_metadata to Value")?;
let payment_link_id = payment_link_data.map(|pl_data| pl_data.payment_link_id);
let request_incremental_authorization =
core_utils::get_request_incremental_authorization_value(
request.request_incremental_authorization,
request.capture_method,
)?;
let split_payments = request.split_payments.clone();
// Derivation of directly supplied Customer data in our Payment Create Request
let raw_customer_details = if request.customer_id.is_none()
&& (request.name.is_some()
|| request.email.is_some()
|| request.phone.is_some()
|| request.phone_country_code.is_some())
{
Some(CustomerData {
name: request.name.clone(),
phone: request.phone.clone(),
email: request.email.clone(),
phone_country_code: request.phone_country_code.clone(),
tax_registration_id: None,
})
} else {
None
};
let is_payment_processor_token_flow = request.recurring_details.as_ref().and_then(
|recurring_details| match recurring_details {
RecurringDetails::ProcessorPaymentToken(_) => Some(true),
_ => None,
},
);
let key = merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek();
let identifier = Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
);
let key_manager_state: KeyManagerState = state.into();
let shipping_details_encoded = request
.shipping
.clone()
.map(|shipping| Encode::encode_to_value(&shipping).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode billing details to serde_json::Value")?;
let billing_details_encoded = request
.billing
.clone()
.map(|billing| Encode::encode_to_value(&billing).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode billing details to serde_json::Value")?;
let customer_details_encoded = raw_customer_details
.map(|customer| Encode::encode_to_value(&customer).map(Secret::new))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encode shipping details to serde_json::Value")?;
let encrypted_data = domain::types::crypto_operation(
&key_manager_state,
type_name!(storage::PaymentIntent),
domain::types::CryptoOperation::BatchEncrypt(
FromRequestEncryptablePaymentIntent::to_encryptable(
FromRequestEncryptablePaymentIntent {
shipping_details: shipping_details_encoded,
billing_details: billing_details_encoded,
customer_details: customer_details_encoded,
},
),
),
identifier.clone(),
key,
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt data")?;
let encrypted_data = FromRequestEncryptablePaymentIntent::from_encryptable(encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt the payment intent data")?;
let skip_external_tax_calculation = request.skip_external_tax_calculation;
let tax_details = request
.order_tax_amount
.map(|tax_amount| diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax {
order_tax_amount: tax_amount,
}),
payment_method_type: None,
});
let force_3ds_challenge_trigger = request
.force_3ds_challenge
.unwrap_or(business_profile.force_3ds_challenge);
Ok(storage::PaymentIntent {
payment_id: payment_id.to_owned(),
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
status,
amount: MinorUnit::from(amount),
currency,
description: request.description.clone(),
created_at,
modified_at,
last_synced: Some(last_synced),
client_secret: Some(client_secret),
setup_future_usage: request.setup_future_usage,
off_session: request.off_session,
return_url: request.return_url.as_ref().map(|a| a.to_string()),
shipping_address_id,
billing_address_id,
statement_descriptor_name: request.statement_descriptor_name.clone(),
statement_descriptor_suffix: request.statement_descriptor_suffix.clone(),
metadata: request.metadata.clone(),
business_country: request.business_country,
business_label: request.business_label.clone(),
active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID(
active_attempt_id,
),
order_details,
amount_captured: None,
customer_id: request.get_customer_id().cloned(),
connector_id: None,
allowed_payment_method_types,
connector_metadata,
feature_metadata,
attempt_count: 1,
profile_id: Some(profile_id),
merchant_decision: None,
payment_link_id,
payment_confirm_source: None,
surcharge_applicable: None,
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
request_incremental_authorization,
incremental_authorization_allowed: None,
authorization_count: None,
fingerprint_id: None,
session_expiry: Some(session_expiry),
request_external_three_ds_authentication: request
.request_external_three_ds_authentication,
split_payments,
frm_metadata: request.frm_metadata.clone(),
billing_details: encrypted_data.billing_details,
customer_details: encrypted_data.customer_details,
merchant_order_reference_id: request.merchant_order_reference_id.clone(),
shipping_details: encrypted_data.shipping_details,
is_payment_processor_token_flow,
organization_id: merchant_context
.get_merchant_account()
.organization_id
.clone(),
shipping_cost: request.shipping_cost,
tax_details,
skip_external_tax_calculation,
request_extended_authorization: request.request_extended_authorization,
psd2_sca_exemption_type: request.psd2_sca_exemption_type,
processor_merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
created_by: None,
force_3ds_challenge: request.force_3ds_challenge,
force_3ds_challenge_trigger: Some(force_3ds_challenge_trigger),
is_iframe_redirection_enabled: request
.is_iframe_redirection_enabled
.or(business_profile.is_iframe_redirection_enabled),
is_payment_id_from_merchant: Some(is_payment_id_from_merchant),
payment_channel: request.payment_channel.clone(),
order_date: request.order_date,
discount_amount: request.discount_amount,
duty_amount: request.duty_amount,
tax_status: request.tax_status,
shipping_amount_tax: request.shipping_amount_tax,
enable_partial_authorization: request.enable_partial_authorization,
enable_overcapture: request.enable_overcapture,
mit_category: request.mit_category,
})
}
#[instrument(skip_all)]
pub async fn get_ephemeral_key(
request: &api::PaymentsRequest,
state: &SessionState,
merchant_context: &domain::MerchantContext,
) -> Option<ephemeral_key::EphemeralKey> {
match request.get_customer_id() {
Some(customer_id) => helpers::make_ephemeral_key(
state.clone(),
customer_id.clone(),
merchant_context
.get_merchant_account()
.get_id()
.to_owned()
.clone(),
)
.await
.ok()
.and_then(|ek| {
if let services::ApplicationResponse::Json(ek) = ek {
Some(ek)
} else {
None
}
}),
None => None,
}
}
}
#[instrument(skip_all)]
pub fn payments_create_request_validation(
req: &api::PaymentsRequest,
) -> RouterResult<(api::Amount, enums::Currency)> {
let currency = req.currency.get_required_value("currency")?;
let amount = req.amount.get_required_value("amount")?;
Ok((amount, currency))
}
#[allow(clippy::too_many_arguments)]
async fn create_payment_link(
request: &api::PaymentsRequest,
payment_link_config: api_models::admin::PaymentLinkConfig,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: common_utils::id_type::PaymentId,
db: &dyn StorageInterface,
amount: api::Amount,
description: Option<String>,
profile_id: common_utils::id_type::ProfileId,
domain_name: String,
session_expiry: PrimitiveDateTime,
locale: Option<String>,
) -> RouterResult<Option<api_models::payments::PaymentLinkResponse>> {
let created_at @ last_modified_at = Some(common_utils::date_time::now());
let payment_link_id = utils::generate_id(consts::ID_LENGTH, "plink");
let locale_str = locale.unwrap_or("en".to_owned());
let open_payment_link = format!(
"{}/payment_link/{}/{}?locale={}",
domain_name,
merchant_id.get_string_repr(),
payment_id.get_string_repr(),
locale_str.clone(),
);
let secure_link = payment_link_config.allowed_domains.as_ref().map(|_| {
format!(
"{}/payment_link/s/{}/{}?locale={}",
domain_name,
merchant_id.get_string_repr(),
payment_id.get_string_repr(),
locale_str,
)
});
let payment_link_config_encoded_value = payment_link_config.encode_to_value().change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_link_config",
},
)?;
let payment_link_req = storage::PaymentLinkNew {
payment_link_id: payment_link_id.clone(),
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
link_to_pay: open_payment_link.clone(),
amount: MinorUnit::from(amount),
currency: request.currency,
created_at,
last_modified_at,
fulfilment_time: Some(session_expiry),
custom_merchant_name: Some(payment_link_config.seller_name),
description,
payment_link_config: Some(payment_link_config_encoded_value),
profile_id: Some(profile_id),
secure_link,
};
let payment_link_db = db
.insert_payment_link(payment_link_req)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "payment link already exists!".to_string(),
})?;
Ok(Some(api_models::payments::PaymentLinkResponse {
link: payment_link_db.link_to_pay.clone(),
secure_link: payment_link_db.secure_link,
payment_link_id: payment_link_db.payment_link_id,
}))
}
| crates/router/src/core/payments/operations/payment_create.rs | router::src::core::payments::operations::payment_create | 12,736 | true |
// File: crates/router/src/core/payments/operations/payment_cancel.rs
// Module: router::src::core::payments::operations::payment_cancel
use std::marker::PhantomData;
use api_models::enums::FrmSuggestion;
use async_trait::async_trait;
use common_utils::ext_traits::AsyncExt;
use error_stack::ResultExt;
use router_derive;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentData},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
self as core_types,
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "cancel")]
pub struct PaymentCancel;
type PaymentCancelOperation<'b, F> =
BoxedOperation<'b, F, api::PaymentsCancelRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
for PaymentCancel
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsCancelRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<
operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest, PaymentData<F>>,
> {
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::Failed,
enums::IntentStatus::Succeeded,
enums::IntentStatus::Cancelled,
enums::IntentStatus::Processing,
enums::IntentStatus::RequiresMerchantAction,
],
"cancel",
)?;
let mut payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
payment_intent.active_attempt.get_id().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
payment_attempt
.cancellation_reason
.clone_from(&request.cancellation_reason);
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,
merchant_context.get_merchant_account().get_id(),
mcd,
)
.await
})
.await
.transpose()?;
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
token_data: None,
address: core_types::PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
is_l2_l3_enabled: false,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
for PaymentCancel
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentCancelOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let cancellation_reason = payment_data.payment_attempt.cancellation_reason.clone();
let (intent_status_update, attempt_status_update) =
if payment_data.payment_intent.status != enums::IntentStatus::RequiresCapture {
let payment_intent_update = storage::PaymentIntentUpdate::PGStatusUpdate {
status: enums::IntentStatus::Cancelled,
updated_by: storage_scheme.to_string(),
incremental_authorization_allowed: None,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
};
(Some(payment_intent_update), enums::AttemptStatus::Voided)
} else {
(None, enums::AttemptStatus::VoidInitiated)
};
if let Some(payment_intent_update) = intent_status_update {
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
storage::PaymentAttemptUpdate::VoidUpdate {
status: attempt_status_update,
cancellation_reason: cancellation_reason.clone(),
updated_by: storage_scheme.to_string(),
},
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentCancelled {
cancellation_reason,
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsCancelRequest, PaymentData<F>>
for PaymentCancel
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsCancelRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentCancelOperation<'b, F>, operations::ValidateResult)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
| crates/router/src/core/payments/operations/payment_cancel.rs | router::src::core::payments::operations::payment_cancel | 2,290 | true |
// File: crates/router/src/core/payments/operations/payment_confirm.rs
// Module: router::src::core::payments::operations::payment_confirm
use std::marker::PhantomData;
#[cfg(feature = "v1")]
use api_models::payment_methods::PaymentMethodsData;
use api_models::{
admin::ExtendedCardInfoConfig,
enums::FrmSuggestion,
payments::{ConnectorMandateReferenceId, ExtendedCardInfo, GetAddressFromPaymentMethodData},
};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt};
use diesel_models::payment_attempt::ConnectorMandateReferenceId as DieselConnectorMandateReferenceId;
use error_stack::{report, ResultExt};
use futures::FutureExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdateFields;
use hyperswitch_domain_models::router_request_types::unified_authentication_service;
use masking::{ExposeInterface, PeekInterface};
use router_derive::PaymentOperation;
use router_env::{instrument, logger, tracing};
use tracing_futures::Instrument;
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
#[cfg(feature = "v1")]
use crate::{
consts,
core::payment_methods::cards::create_encrypted_data,
events::audit_events::{AuditEvent, AuditEventType},
};
use crate::{
core::{
authentication,
blocklist::utils as blocklist_utils,
card_testing_guard::utils as card_testing_guard_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payments::{
self, helpers, operations,
operations::payment_confirm::unified_authentication_service::ThreeDsMetaData,
populate_surcharge_details, CustomerDetails, PaymentAddress, PaymentData,
},
three_ds_decision_rule,
unified_authentication_service::{
self as uas_utils,
types::{ClickToPay, UnifiedAuthenticationService},
},
utils as core_utils,
},
routes::{app::ReqState, SessionState},
services,
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
domain::{self},
storage::{self, enums as storage_enums},
transformers::{ForeignFrom, ForeignInto},
},
utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
#[operation(operations = "all", flow = "authorize")]
pub struct PaymentConfirm;
type PaymentConfirmOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
for PaymentConfirm
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
request: &api::PaymentsRequest,
merchant_context: &domain::MerchantContext,
auth_flow: services::AuthFlow,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>>
{
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let (currency, amount);
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
// Stage 1
let store = &*state.store;
let m_merchant_id = merchant_id.clone();
// Parallel calls - level 0
let mut payment_intent = store
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
&m_merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
// TODO (#7195): Add platform merchant account validation once client_secret auth is solved
if let Some(order_details) = &request.order_details {
helpers::validate_order_details_amount(
order_details.to_owned(),
payment_intent.amount,
false,
)?;
}
helpers::validate_customer_access(&payment_intent, auth_flow, request)?;
if [
Some(common_enums::PaymentSource::Webhook),
Some(common_enums::PaymentSource::ExternalAuthenticator),
]
.contains(&header_payload.payment_confirm_source)
{
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Cancelled,
storage_enums::IntentStatus::Succeeded,
storage_enums::IntentStatus::Processing,
storage_enums::IntentStatus::RequiresCapture,
storage_enums::IntentStatus::RequiresMerchantAction,
],
"confirm",
)?;
} else {
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
storage_enums::IntentStatus::Cancelled,
storage_enums::IntentStatus::Succeeded,
storage_enums::IntentStatus::Processing,
storage_enums::IntentStatus::RequiresCapture,
storage_enums::IntentStatus::RequiresMerchantAction,
storage_enums::IntentStatus::RequiresCustomerAction,
],
"confirm",
)?;
}
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let customer_details = helpers::get_customer_details_from_request(request);
// Stage 2
let attempt_id = payment_intent.active_attempt.get_id();
let profile_id = payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let store = state.store.clone();
let key_manager_state_clone = key_manager_state.clone();
let key_store_clone = merchant_context.get_merchant_key_store().clone();
let business_profile_fut = tokio::spawn(
async move {
store
.find_business_profile_by_profile_id(
&key_manager_state_clone,
&key_store_clone,
&profile_id,
)
.map(|business_profile_result| {
business_profile_result.to_not_found_response(
errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
},
)
})
.await
}
.in_current_span(),
);
let store = state.store.clone();
let m_payment_id = payment_intent.payment_id.clone();
let m_merchant_id = merchant_id.clone();
let payment_attempt_fut = tokio::spawn(
async move {
store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&m_payment_id,
&m_merchant_id,
attempt_id.as_str(),
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
let m_merchant_id = merchant_id.clone();
let m_request_shipping = request.shipping.clone();
let m_payment_intent_shipping_address_id = payment_intent.shipping_address_id.clone();
let m_payment_intent_payment_id = payment_intent.payment_id.clone();
let m_customer_details_customer_id = customer_details.customer_id.clone();
let m_payment_intent_customer_id = payment_intent.customer_id.clone();
let m_key_store = merchant_context.get_merchant_key_store().clone();
let session_state = state.clone();
let shipping_address_fut = tokio::spawn(
async move {
helpers::create_or_update_address_for_payment_by_request(
&session_state,
m_request_shipping.as_ref(),
m_payment_intent_shipping_address_id.as_deref(),
&m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
&m_key_store,
&m_payment_intent_payment_id,
storage_scheme,
)
.await
}
.in_current_span(),
);
let m_merchant_id = merchant_id.clone();
let m_request_billing = request.billing.clone();
let m_customer_details_customer_id = customer_details.customer_id.clone();
let m_payment_intent_customer_id = payment_intent.customer_id.clone();
let m_payment_intent_billing_address_id = payment_intent.billing_address_id.clone();
let m_payment_intent_payment_id = payment_intent.payment_id.clone();
let m_key_store = merchant_context.get_merchant_key_store().clone();
let session_state = state.clone();
let billing_address_fut = tokio::spawn(
async move {
helpers::create_or_update_address_for_payment_by_request(
&session_state,
m_request_billing.as_ref(),
m_payment_intent_billing_address_id.as_deref(),
&m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
&m_key_store,
&m_payment_intent_payment_id,
storage_scheme,
)
.await
}
.in_current_span(),
);
let m_merchant_id = merchant_id.clone();
let store = state.clone().store;
let m_request_merchant_connector_details = request.merchant_connector_details.clone();
let config_update_fut = tokio::spawn(
async move {
m_request_merchant_connector_details
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
store.as_ref(),
&m_merchant_id,
mcd,
)
.await
})
.map(|x| x.transpose())
.await
}
.in_current_span(),
);
// Based on whether a retry can be performed or not, fetch relevant entities
let (mut payment_attempt, shipping_address, billing_address, business_profile) =
match payment_intent.status {
api_models::enums::IntentStatus::RequiresCustomerAction
| api_models::enums::IntentStatus::RequiresMerchantAction
| api_models::enums::IntentStatus::RequiresPaymentMethod
| api_models::enums::IntentStatus::RequiresConfirmation => {
// Normal payment
// Parallel calls - level 1
let (payment_attempt, shipping_address, billing_address, business_profile, _) =
tokio::try_join!(
utils::flatten_join_error(payment_attempt_fut),
utils::flatten_join_error(shipping_address_fut),
utils::flatten_join_error(billing_address_fut),
utils::flatten_join_error(business_profile_fut),
utils::flatten_join_error(config_update_fut)
)?;
(
payment_attempt,
shipping_address,
billing_address,
business_profile,
)
}
_ => {
// Retry payment
let (
mut payment_attempt,
shipping_address,
billing_address,
business_profile,
_,
) = tokio::try_join!(
utils::flatten_join_error(payment_attempt_fut),
utils::flatten_join_error(shipping_address_fut),
utils::flatten_join_error(billing_address_fut),
utils::flatten_join_error(business_profile_fut),
utils::flatten_join_error(config_update_fut)
)?;
let attempt_type = helpers::get_attempt_type(
&payment_intent,
&payment_attempt,
business_profile.is_manual_retry_enabled,
"confirm",
)?;
// 3
(payment_intent, payment_attempt) = attempt_type
.modify_payment_intent_and_payment_attempt(
request,
payment_intent,
payment_attempt,
state,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await?;
(
payment_attempt,
shipping_address,
billing_address,
business_profile,
)
}
};
payment_intent.order_details = request
.get_order_details_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?
.or(payment_intent.order_details);
payment_intent.setup_future_usage = request
.setup_future_usage
.or(payment_intent.setup_future_usage);
payment_intent.psd2_sca_exemption_type = request
.psd2_sca_exemption_type
.or(payment_intent.psd2_sca_exemption_type);
let browser_info = request
.browser_info
.clone()
.or(payment_attempt.browser_info)
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "browser_info",
})?;
let customer_acceptance = request.customer_acceptance.clone().or(payment_attempt
.customer_acceptance
.clone()
.map(|customer_acceptance| {
customer_acceptance
.expose()
.parse_value("CustomerAcceptance")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while deserializing customer_acceptance")
})
.transpose()?);
let recurring_details = request.recurring_details.clone();
helpers::validate_card_data(
request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
)?;
payment_attempt.browser_info = browser_info;
payment_attempt.payment_experience = request
.payment_experience
.or(payment_attempt.payment_experience);
payment_attempt.capture_method = request.capture_method.or(payment_attempt.capture_method);
payment_attempt.customer_acceptance = request
.customer_acceptance
.clone()
.map(|customer_acceptance| customer_acceptance.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encoding customer_acceptance to value")?
.map(masking::Secret::new)
.or(payment_attempt.customer_acceptance);
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.get_total_amount().into();
helpers::validate_customer_id_mandatory_cases(
request.setup_future_usage.is_some(),
payment_intent
.customer_id
.as_ref()
.or(customer_details.customer_id.as_ref()),
)?;
let creds_identifier = request
.merchant_connector_details
.as_ref()
.map(|mcd| mcd.creds_identifier.to_owned());
payment_intent.shipping_address_id =
shipping_address.as_ref().map(|i| i.address_id.clone());
payment_intent.billing_address_id = billing_address.as_ref().map(|i| i.address_id.clone());
payment_intent.return_url = request
.return_url
.as_ref()
.map(|a| a.to_string())
.or(payment_intent.return_url);
payment_intent.allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting allowed_payment_types to Value")?
.or(payment_intent.allowed_payment_method_types);
payment_intent.connector_metadata = request
.get_connector_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting connector_metadata to Value")?
.or(payment_intent.connector_metadata);
payment_intent.feature_metadata = request
.get_feature_metadata_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error converting feature_metadata to Value")?
.or(payment_intent.feature_metadata);
payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata);
payment_intent.frm_metadata = request.frm_metadata.clone().or(payment_intent.frm_metadata);
payment_intent.request_incremental_authorization = request
.request_incremental_authorization
.map(|request_incremental_authorization| {
core_utils::get_request_incremental_authorization_value(
Some(request_incremental_authorization),
payment_attempt.capture_method,
)
})
.unwrap_or(Ok(payment_intent.request_incremental_authorization))?;
payment_intent.enable_partial_authorization = request
.enable_partial_authorization
.or(payment_intent.enable_partial_authorization);
payment_attempt.business_sub_label = request
.business_sub_label
.clone()
.or(payment_attempt.business_sub_label);
let n_request_payment_method_data = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone());
let store = state.clone().store;
let profile_id = payment_intent
.profile_id
.clone()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let additional_pm_data_fut = tokio::spawn(
async move {
Ok(n_request_payment_method_data
.async_map(|payment_method_data| async move {
helpers::get_additional_payment_data(
&payment_method_data.into(),
store.as_ref(),
&profile_id,
)
.await
})
.await)
}
.in_current_span(),
);
let n_payment_method_billing_address_id =
payment_attempt.payment_method_billing_address_id.clone();
let n_request_payment_method_billing_address = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.billing.clone());
let m_payment_intent_customer_id = payment_intent.customer_id.clone();
let m_payment_intent_payment_id = payment_intent.payment_id.clone();
let m_key_store = merchant_context.get_merchant_key_store().clone();
let m_customer_details_customer_id = customer_details.customer_id.clone();
let m_merchant_id = merchant_id.clone();
let session_state = state.clone();
let payment_method_billing_future = tokio::spawn(
async move {
helpers::create_or_update_address_for_payment_by_request(
&session_state,
n_request_payment_method_billing_address.as_ref(),
n_payment_method_billing_address_id.as_deref(),
&m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
&m_key_store,
&m_payment_intent_payment_id,
storage_scheme,
)
.await
}
.in_current_span(),
);
let mandate_type = m_helpers::get_mandate_type(
request.mandate_data.clone(),
request.off_session,
payment_intent.setup_future_usage,
request.customer_acceptance.clone(),
request.payment_token.clone(),
payment_attempt.payment_method.or(request.payment_method),
)
.change_context(errors::ApiErrorResponse::MandateValidationFailed {
reason: "Expected one out of recurring_details and mandate_data but got both".into(),
})?;
let m_state = state.clone();
let m_mandate_type = mandate_type;
let m_merchant_context = merchant_context.clone();
let m_request = request.clone();
let payment_intent_customer_id = payment_intent.customer_id.clone();
let mandate_details_fut = tokio::spawn(
async move {
Box::pin(helpers::get_token_pm_type_mandate_details(
&m_state,
&m_request,
m_mandate_type,
&m_merchant_context,
None,
payment_intent_customer_id.as_ref(),
))
.await
}
.in_current_span(),
);
// Parallel calls - level 2
let (mandate_details, additional_pm_info, payment_method_billing) = tokio::try_join!(
utils::flatten_join_error(mandate_details_fut),
utils::flatten_join_error(additional_pm_data_fut),
utils::flatten_join_error(payment_method_billing_future),
)?;
let additional_pm_data = additional_pm_info.transpose()?.flatten();
let m_helpers::MandateGenericData {
token,
payment_method,
payment_method_type,
mandate_data,
recurring_mandate_payment_data,
mandate_connector,
payment_method_info,
} = mandate_details;
let token = token.or_else(|| payment_attempt.payment_token.clone());
helpers::validate_pm_or_token_given(
&request.payment_method,
&request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.clone()),
&request.payment_method_type,
&mandate_type,
&token,
&request.ctp_service_details,
)?;
let (token_data, payment_method_info) = if let Some(token) = token.clone() {
let token_data = helpers::retrieve_payment_token_data(
state,
token,
payment_method.or(payment_attempt.payment_method),
)
.await?;
let payment_method_info = helpers::retrieve_payment_method_from_db_with_token_data(
state,
merchant_context.get_merchant_key_store(),
&token_data,
storage_scheme,
)
.await?;
(Some(token_data), payment_method_info)
} else {
(None, payment_method_info)
};
let additional_pm_data_from_locker = if let Some(ref pm) = payment_method_info {
let card_detail_from_locker: Option<api::CardDetailFromLocker> = pm
.payment_method_data
.clone()
.map(|x| x.into_inner().expose())
.and_then(|v| {
v.parse_value("PaymentMethodsData")
.map_err(|err| {
router_env::logger::info!(
"PaymentMethodsData deserialization failed: {:?}",
err
)
})
.ok()
})
.and_then(|pmd| match pmd {
PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
_ => None,
});
card_detail_from_locker.map(|card_details| {
let additional_data = card_details.into();
api_models::payments::AdditionalPaymentData::Card(Box::new(additional_data))
})
} else {
None
};
// Only set `payment_attempt.payment_method_data` if `additional_pm_data_from_locker` is not None
if let Some(additional_pm_data) = additional_pm_data_from_locker.as_ref() {
payment_attempt.payment_method_data = Some(
Encode::encode_to_value(additional_pm_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?,
);
}
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
let payment_method_type = Option::<api_models::enums::PaymentMethodType>::foreign_from((
payment_method_type,
additional_pm_data.as_ref(),
payment_method,
));
payment_attempt.payment_method_type = payment_method_type
.or(payment_attempt.payment_method_type)
.or(payment_method_info
.as_ref()
.and_then(|pm_info| pm_info.get_payment_method_subtype()));
// The operation merges mandate data from both request and payment_attempt
let setup_mandate = mandate_data.map(|mut sm| {
sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
sm.update_mandate_id = payment_attempt
.mandate_data
.clone()
.and_then(|mandate| mandate.update_mandate_id)
.or(sm.update_mandate_id);
sm
});
let mandate_details_present =
payment_attempt.mandate_details.is_some() || request.mandate_data.is_some();
helpers::validate_mandate_data_and_future_usage(
payment_intent.setup_future_usage,
mandate_details_present,
)?;
let payment_method_data_after_card_bin_call = request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
})
.zip(additional_pm_data)
.map(|(payment_method_data, additional_payment_data)| {
payment_method_data.apply_additional_payment_data(additional_payment_data)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Card cobadge check failed due to an invalid card network regex")?;
payment_attempt.payment_method_billing_address_id = payment_method_billing
.as_ref()
.map(|payment_method_billing| payment_method_billing.address_id.clone());
let address = PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
);
let payment_method_data_billing = request
.payment_method_data
.as_ref()
.and_then(|pmd| pmd.payment_method_data.as_ref())
.and_then(|payment_method_data_billing| {
payment_method_data_billing.get_billing_address()
})
.map(From::from);
let unified_address =
address.unify_with_payment_method_data_billing(payment_method_data_billing);
// If processor_payment_token is passed in request then populating the same in PaymentData
let mandate_id = request
.recurring_details
.as_ref()
.and_then(|recurring_details| match recurring_details {
api_models::mandates::RecurringDetails::ProcessorPaymentToken(token) => {
payment_intent.is_payment_processor_token_flow = Some(true);
Some(api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::ConnectorMandateId(
ConnectorMandateReferenceId::new(
Some(token.processor_payment_token.clone()), // connector_mandate_id
None, // payment_method_id
None, // update_history
None, // mandate_metadata
None, // connector_mandate_request_reference_id
),
),
),
})
}
_ => None,
});
let pmt_order_tax_amount = payment_intent.tax_details.clone().and_then(|tax| {
if tax.payment_method_type.clone().map(|a| a.pmt) == payment_attempt.payment_method_type
{
tax.payment_method_type.map(|a| a.order_tax_amount)
} else {
None
}
});
let order_tax_amount = pmt_order_tax_amount.or_else(|| {
payment_intent
.tax_details
.clone()
.and_then(|tax| tax.default.map(|a| a.order_tax_amount))
});
payment_attempt
.net_amount
.set_order_tax_amount(order_tax_amount);
payment_attempt.connector_mandate_detail = Some(
DieselConnectorMandateReferenceId::foreign_from(ConnectorMandateReferenceId::new(
None,
None,
None, // update_history
None, // mandate_metadata
Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)), // connector_mandate_request_reference_id
)),
);
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: request.email.clone(),
mandate_id: mandate_id.clone(),
mandate_connector,
setup_mandate,
customer_acceptance,
token,
address: unified_address,
token_data,
confirm: request.confirm,
payment_method_data: payment_method_data_after_card_bin_call.map(Into::into),
payment_method_token: None,
payment_method_info,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: request.card_cvc.clone(),
creds_identifier,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details,
poll_config: None,
tax_data: None,
session_id: None,
service_details: request.ctp_service_details.clone(),
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: business_profile.is_manual_retry_enabled,
is_l2_l3_enabled: business_profile.is_l2_l3_enabled,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: Some(customer_details),
payment_data,
business_profile,
mandate_type,
};
Ok(get_trackers_response)
}
async fn validate_request_with_state(
&self,
state: &SessionState,
request: &api::PaymentsRequest,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> RouterResult<()> {
let payment_method_data: Option<&api_models::payments::PaymentMethodData> = request
.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
});
let customer_id = &payment_data.payment_intent.customer_id;
match payment_method_data {
Some(api_models::payments::PaymentMethodData::Card(card)) => {
payment_data.card_testing_guard_data =
card_testing_guard_utils::validate_card_testing_guard_checks(
state,
request.browser_info.as_ref(),
card.card_number.clone(),
customer_id,
business_profile,
)
.await?;
Ok(())
}
_ => Ok(()),
}
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for PaymentConfirm {
#[instrument(skip_all)]
async fn get_or_create_customer_details<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<
(PaymentConfirmOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
> {
helpers::create_customer_if_not_exist(
state,
Box::new(self),
payment_data,
request,
&key_store.merchant_id,
key_store,
storage_scheme,
)
.await
}
#[instrument(skip_all)]
async fn make_pm_data<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
storage_scheme: storage_enums::MerchantStorageScheme,
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
PaymentConfirmOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
let (op, payment_method_data, pm_id) = Box::pin(helpers::make_pm_data(
Box::new(self),
state,
payment_data,
key_store,
customer,
storage_scheme,
business_profile,
should_retry_with_pan,
))
.await?;
utils::when(payment_method_data.is_none(), || {
Err(errors::ApiErrorResponse::PaymentMethodNotFound)
})?;
Ok((op, payment_method_data, pm_id))
}
#[instrument(skip_all)]
async fn add_task_to_process_tracker<'a>(
&'a self,
state: &'a SessionState,
payment_attempt: &storage::PaymentAttempt,
requeue: bool,
schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
// This spawns this futures in a background thread, the exception inside this future won't affect
// the current thread and the lifecycle of spawn thread is not handled by runtime.
// So when server shutdown won't wait for this thread's completion.
let m_payment_attempt = payment_attempt.clone();
let m_state = state.clone();
let m_self = *self;
tokio::spawn(
async move {
helpers::add_domain_task_to_pt(
&m_self,
&m_state,
&m_payment_attempt,
requeue,
schedule_time,
)
.await
}
.in_current_span(),
);
Ok(())
}
async fn get_connector<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
state: &SessionState,
request: &api::PaymentsRequest,
_payment_intent: &storage::PaymentIntent,
) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> {
// Use a new connector in the confirm call or use the same one which was passed when
// creating the payment or if none is passed then use the routing algorithm
helpers::get_connector_default(state, request.routing.clone()).await
}
#[instrument(skip_all)]
async fn populate_payment_data<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
_merchant_context: &domain::MerchantContext,
business_profile: &domain::Profile,
connector_data: &api::ConnectorData,
) -> CustomResult<(), errors::ApiErrorResponse> {
populate_surcharge_details(state, payment_data).await?;
payment_data.payment_attempt.request_extended_authorization = payment_data
.payment_intent
.get_request_extended_authorization_bool_if_connector_supports(
connector_data.connector_name,
business_profile.always_request_extended_authorization,
payment_data.payment_attempt.payment_method,
payment_data.payment_attempt.payment_method_type,
);
payment_data.payment_intent.enable_overcapture = payment_data
.payment_intent
.get_enable_overcapture_bool_if_connector_supports(
connector_data.connector_name,
business_profile.always_enable_overcapture,
&payment_data.payment_attempt.capture_method,
);
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn call_external_three_ds_authentication_if_eligible<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
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> {
let external_authentication_flow =
helpers::get_payment_external_authentication_flow_during_confirm(
state,
key_store,
business_profile,
payment_data,
connector_call_type,
mandate_type,
)
.await?;
payment_data.authentication = match external_authentication_flow {
Some(helpers::PaymentExternalAuthenticationFlow::PreAuthenticationFlow {
acquirer_details,
card,
token,
}) => {
let authentication_store = Box::pin(authentication::perform_pre_authentication(
state,
key_store,
*card,
token,
business_profile,
acquirer_details,
payment_data.payment_attempt.payment_id.clone(),
payment_data.payment_attempt.organization_id.clone(),
payment_data.payment_intent.force_3ds_challenge,
payment_data.payment_intent.psd2_sca_exemption_type,
))
.await?;
if authentication_store
.authentication
.is_separate_authn_required()
|| authentication_store
.authentication
.authentication_status
.is_failed()
{
*should_continue_confirm_transaction = false;
let default_poll_config = types::PollConfig::default();
let default_config_str = default_poll_config
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while stringifying default poll config")?;
// raise error if authentication_connector is not present since it should we be present in the current flow
let authentication_connector = authentication_store
.authentication
.authentication_connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"authentication_connector not present in authentication record",
)?;
let poll_config = state
.store
.find_config_by_key_unwrap_or(
&types::PollConfig::get_poll_config_key(authentication_connector),
Some(default_config_str),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The poll config was not found in the DB")?;
let poll_config: types::PollConfig = poll_config
.config
.parse_struct("PollConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing PollConfig")?;
payment_data.poll_config = Some(poll_config)
}
Some(authentication_store)
}
Some(helpers::PaymentExternalAuthenticationFlow::PostAuthenticationFlow {
authentication_id,
}) => {
let authentication_store = Box::pin(authentication::perform_post_authentication(
state,
key_store,
business_profile.clone(),
authentication_id.clone(),
&payment_data.payment_intent.payment_id,
))
.await?;
//If authentication is not successful, skip the payment connector flows and mark the payment as failure
if authentication_store.authentication.authentication_status
!= api_models::enums::AuthenticationStatus::Success
{
*should_continue_confirm_transaction = false;
}
Some(authentication_store)
}
None => None,
};
Ok(())
}
async fn apply_three_ds_authentication_strategy<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
business_profile: &domain::Profile,
) -> CustomResult<(), errors::ApiErrorResponse> {
// If the business profile has a three_ds_decision_rule_algorithm, we will use it to determine the 3DS strategy (authentication_type, exemption_type and force_three_ds_challenge)
if let Some(three_ds_decision_rule) =
business_profile.three_ds_decision_rule_algorithm.clone()
{
// Parse the three_ds_decision_rule to get the algorithm_id
let algorithm_id = three_ds_decision_rule
.parse_value::<api::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not decode profile routing algorithm ref")?
.algorithm_id
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No algorithm_id found in three_ds_decision_rule_algorithm")?;
// get additional card info from payment data
let additional_card_info = payment_data
.payment_attempt
.payment_method_data
.as_ref()
.map(|payment_method_data| {
payment_method_data
.clone()
.parse_value::<api_models::payments::AdditionalPaymentData>(
"additional_payment_method_data",
)
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse value into additional_payment_method_data")?
.and_then(|additional_payment_method_data| {
additional_payment_method_data.get_additional_card_info()
});
// get acquirer details from business profile based on card network
let acquirer_config = additional_card_info.as_ref().and_then(|card_info| {
card_info
.card_network
.clone()
.and_then(|network| business_profile.get_acquirer_details_from_network(network))
});
let country = business_profile
.merchant_country_code
.as_ref()
.map(|country_code| {
country_code.validate_and_get_country_from_merchant_country_code()
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing country from merchant country code")?;
// get three_ds_decision_rule_output using algorithm_id and payment data
let decision = three_ds_decision_rule::get_three_ds_decision_rule_output(
state,
&business_profile.merchant_id,
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest {
routing_id: algorithm_id,
payment: api_models::three_ds_decision_rule::PaymentData {
amount: payment_data.payment_intent.amount,
currency: payment_data
.payment_intent
.currency
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("currency is not set in payment intent")?,
},
payment_method: Some(
api_models::three_ds_decision_rule::PaymentMethodMetaData {
card_network: additional_card_info
.as_ref()
.and_then(|info| info.card_network.clone()),
},
),
issuer: Some(api_models::three_ds_decision_rule::IssuerData {
name: additional_card_info
.as_ref()
.and_then(|info| info.card_issuer.clone()),
country: additional_card_info
.as_ref()
.map(|info| info.card_issuing_country.clone().parse_enum("Country"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Error while getting country enum from issuer country",
)?,
}),
customer_device: None,
acquirer: acquirer_config.as_ref().map(|acquirer| {
api_models::three_ds_decision_rule::AcquirerData {
country,
fraud_rate: Some(acquirer.acquirer_fraud_rate),
}
}),
},
)
.await?;
logger::info!("Three DS Decision Rule Output: {:?}", decision);
// We should update authentication_type from the Three DS Decision if it is not already set
if payment_data.payment_attempt.authentication_type.is_none() {
payment_data.payment_attempt.authentication_type =
Some(common_enums::AuthenticationType::foreign_from(decision));
}
// We should update psd2_sca_exemption_type from the Three DS Decision
payment_data.payment_intent.psd2_sca_exemption_type = decision.foreign_into();
// We should update force_3ds_challenge from the Three DS Decision
payment_data.payment_intent.force_3ds_challenge =
decision.should_force_3ds_challenge().then_some(true);
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn call_unified_authentication_service_if_eligible<'a>(
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
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> {
let unified_authentication_service_flow =
helpers::decide_action_for_unified_authentication_service(
state,
key_store,
business_profile,
payment_data,
connector_call_type,
mandate_type,
)
.await?;
if let Some(unified_authentication_service_flow) = unified_authentication_service_flow {
match unified_authentication_service_flow {
helpers::UnifiedAuthenticationServiceFlow::ClickToPayInitiate => {
let authentication_product_ids = business_profile
.authentication_product_ids
.clone()
.ok_or(errors::ApiErrorResponse::PreconditionFailed {
message: "authentication_product_ids is not configured in business profile"
.to_string(),
})?;
let click_to_pay_mca_id = authentication_product_ids
.get_click_to_pay_connector_account_id()
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "authentication_product_ids",
})?;
let key_manager_state = &(state).into();
let merchant_id = &business_profile.merchant_id;
let connector_mca = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
&click_to_pay_mca_id,
key_store,
)
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: click_to_pay_mca_id.get_string_repr().to_string(),
},
)?;
let authentication_id =
common_utils::id_type::AuthenticationId::generate_authentication_id(consts::AUTHENTICATION_ID_PREFIX);
let payment_method = payment_data.payment_attempt.payment_method.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method",
},
)?;
ClickToPay::pre_authentication(
state,
&payment_data.payment_attempt.merchant_id,
Some(&payment_data.payment_intent.payment_id),
payment_data.payment_method_data.as_ref(),
payment_data.payment_attempt.payment_method_type,
&helpers::MerchantConnectorAccountType::DbVal(Box::new(connector_mca.clone())),
&connector_mca.connector_name,
&authentication_id,
payment_method,
payment_data.payment_intent.amount,
payment_data.payment_intent.currency,
payment_data.service_details.clone(),
None,
None,
None,
None
)
.await?;
payment_data.payment_attempt.authentication_id = Some(authentication_id.clone());
let response = ClickToPay::post_authentication(
state,
business_profile,
Some(&payment_data.payment_intent.payment_id),
&helpers::MerchantConnectorAccountType::DbVal(Box::new(connector_mca.clone())),
&connector_mca.connector_name,
&authentication_id,
payment_method,
&payment_data.payment_intent.merchant_id,
None
)
.await?;
let (network_token, authentication_status) = match response.response.clone() {
Ok(unified_authentication_service::UasAuthenticationResponseData::PostAuthentication {
authentication_details,
}) => {
let token_details = authentication_details.token_details.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing authentication_details.token_details")?;
(Some(
hyperswitch_domain_models::payment_method_data::NetworkTokenData {
token_number: token_details.payment_token,
token_exp_month: token_details
.token_expiration_month,
token_exp_year: token_details
.token_expiration_year,
token_cryptogram: authentication_details
.dynamic_data_details
.and_then(|data| data.dynamic_data_value),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
eci: authentication_details.eci,
}),common_enums::AuthenticationStatus::Success)
},
Ok(unified_authentication_service::UasAuthenticationResponseData::PreAuthentication { .. })
| Ok(unified_authentication_service::UasAuthenticationResponseData::Confirmation {})
| Ok(unified_authentication_service::UasAuthenticationResponseData::Authentication { .. }) => Err(errors::ApiErrorResponse::InternalServerError).attach_printable("unexpected response received from unified authentication service")?,
Err(_) => (None, common_enums::AuthenticationStatus::Failed)
};
payment_data.payment_attempt.payment_method =
Some(common_enums::PaymentMethod::Card);
payment_data.payment_method_data = network_token
.clone()
.map(domain::PaymentMethodData::NetworkToken);
let authentication = uas_utils::create_new_authentication(
state,
payment_data.payment_attempt.merchant_id.clone(),
Some(connector_mca.connector_name.to_string()),
business_profile.get_id().clone(),
Some(payment_data.payment_intent.get_id().clone()),
Some(click_to_pay_mca_id.to_owned()),
&authentication_id,
payment_data.service_details.clone(),
authentication_status,
network_token.clone(),
payment_data.payment_attempt.organization_id.clone(),
payment_data.payment_intent.force_3ds_challenge,
payment_data.payment_intent.psd2_sca_exemption_type,
None,
None,
None,
None,
None,
None,
None
)
.await?;
let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: network_token.and_then(|token| token.token_cryptogram),
authentication
};
payment_data.authentication = Some(authentication_store);
},
helpers::UnifiedAuthenticationServiceFlow::ExternalAuthenticationInitiate {
acquirer_details,
..
} => {
let (authentication_connector, three_ds_connector_account) =
authentication::utils::get_authentication_connector_data(state, key_store, business_profile, None).await?;
let authentication_connector_name = authentication_connector.to_string();
let authentication_id =
common_utils::id_type::AuthenticationId::generate_authentication_id(consts::AUTHENTICATION_ID_PREFIX);
let (acquirer_bin, acquirer_merchant_id, acquirer_country_code) = if let Some(details) = &acquirer_details {
(
Some(details.acquirer_bin.clone()),
Some(details.acquirer_merchant_id.clone()),
details.acquirer_country_code.clone(),
)
} else {
(None, None, None)
};
let authentication = uas_utils::create_new_authentication(
state,
business_profile.merchant_id.clone(),
Some(authentication_connector_name.clone()),
business_profile.get_id().to_owned(),
Some(payment_data.payment_intent.payment_id.clone()),
Some(three_ds_connector_account
.get_mca_id()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while finding mca_id from merchant_connector_account")?),
&authentication_id,
payment_data.service_details.clone(),
common_enums::AuthenticationStatus::Started,
None,
payment_data.payment_attempt.organization_id.clone(),
payment_data.payment_intent.force_3ds_challenge,
payment_data.payment_intent.psd2_sca_exemption_type,
acquirer_bin,
acquirer_merchant_id,
acquirer_country_code,
None,
None,
None,
None,
)
.await?;
let acquirer_configs = authentication
.profile_acquirer_id
.clone()
.and_then(|acquirer_id| {
business_profile
.acquirer_config_map.as_ref()
.and_then(|acquirer_config_map| acquirer_config_map.0.get(&acquirer_id).cloned())
});
let metadata: Option<ThreeDsMetaData> = three_ds_connector_account
.get_metadata()
.map(|metadata| {
metadata
.expose()
.parse_value("ThreeDsMetaData")
.attach_printable("Error while parsing ThreeDsMetaData")
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let merchant_country_code = authentication.acquirer_country_code.clone();
let return_url = helpers::create_authorize_url(
&state.base_url,
&payment_data.payment_attempt.clone(),
payment_data.payment_attempt.connector.as_ref().get_required_value("connector")?,
);
let notification_url = Some(url::Url::parse(&return_url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook url")?;
let merchant_details = Some(unified_authentication_service::MerchantDetails {
merchant_id: Some(authentication.merchant_id.get_string_repr().to_string()),
merchant_name: acquirer_configs.clone().map(|detail| detail.merchant_name.clone()).or(metadata.clone().and_then(|metadata| metadata.merchant_name)),
merchant_category_code: business_profile.merchant_category_code.or(metadata.clone().and_then(|metadata| metadata.merchant_category_code)),
endpoint_prefix: metadata.clone().and_then(|metadata| metadata.endpoint_prefix),
three_ds_requestor_url: business_profile.authentication_connector_details.clone().map(|details| details.three_ds_requestor_url),
three_ds_requestor_id: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_id),
three_ds_requestor_name: metadata.clone().and_then(|metadata| metadata.three_ds_requestor_name),
merchant_country_code: merchant_country_code.map(common_types::payments::MerchantCountryCode::new),
notification_url,
});
let domain_address = payment_data.address.get_payment_method_billing();
let pre_auth_response = uas_utils::types::ExternalAuthentication::pre_authentication(
state,
&payment_data.payment_attempt.merchant_id,
Some(&payment_data.payment_intent.payment_id),
payment_data.payment_method_data.as_ref(),
payment_data.payment_attempt.payment_method_type,
&three_ds_connector_account,
&authentication_connector_name,
&authentication.authentication_id,
payment_data.payment_attempt.payment_method.ok_or(
errors::ApiErrorResponse::InternalServerError
).attach_printable("payment_method not found in payment_attempt")?,
payment_data.payment_intent.amount,
payment_data.payment_intent.currency,
payment_data.service_details.clone(),
merchant_details.as_ref(),
domain_address,
authentication.acquirer_bin.clone(),
authentication.acquirer_merchant_id.clone(),
)
.await?;
let updated_authentication = uas_utils::utils::external_authentication_update_trackers(
state,
pre_auth_response,
authentication.clone(),
acquirer_details,
key_store,
None,
None,
None,
None,
).await?;
let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: None, // since in case of pre_authentication cavv is not present
authentication: updated_authentication.clone(),
};
payment_data.authentication = Some(authentication_store.clone());
if updated_authentication.is_separate_authn_required()
|| updated_authentication.authentication_status.is_failed()
{
*should_continue_confirm_transaction = false;
let default_poll_config = types::PollConfig::default();
let default_config_str = default_poll_config
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while stringifying default poll config")?;
// raise error if authentication_connector is not present since it should we be present in the current flow
let authentication_connector = updated_authentication.authentication_connector
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("authentication_connector not found in updated_authentication")?;
let poll_config = state
.store
.find_config_by_key_unwrap_or(
&types::PollConfig::get_poll_config_key(
authentication_connector.clone(),
),
Some(default_config_str),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The poll config was not found in the DB")?;
let poll_config: types::PollConfig = poll_config
.config
.parse_struct("PollConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing PollConfig")?;
payment_data.poll_config = Some(poll_config)
}
},
helpers::UnifiedAuthenticationServiceFlow::ExternalAuthenticationPostAuthenticate {authentication_id} => {
let (authentication_connector, three_ds_connector_account) =
authentication::utils::get_authentication_connector_data(state, key_store, business_profile, None).await?;
let is_pull_mechanism_enabled =
utils::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,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Error while fetching authentication record with authentication_id {}", authentication_id.get_string_repr()))?;
let updated_authentication = if !authentication.authentication_status.is_terminal_status() && is_pull_mechanism_enabled {
let post_auth_response = uas_utils::types::ExternalAuthentication::post_authentication(
state,
business_profile,
Some(&payment_data.payment_intent.payment_id),
&three_ds_connector_account,
&authentication_connector.to_string(),
&authentication.authentication_id,
payment_data.payment_attempt.payment_method.ok_or(
errors::ApiErrorResponse::InternalServerError
).attach_printable("payment_method not found in payment_attempt")?,
&payment_data.payment_intent.merchant_id,
Some(&authentication),
).await?;
uas_utils::utils::external_authentication_update_trackers(
state,
post_auth_response,
authentication,
None,
key_store,
None,
None,
None,
None,
).await?
} else {
authentication
};
let tokenized_data = if updated_authentication.authentication_status.is_success() {
Some(crate::core::payment_methods::vault::get_tokenized_data(state, authentication_id.get_string_repr(), false, key_store.key.get_inner()).await?)
} else {
None
};
let authentication_store = hyperswitch_domain_models::router_request_types::authentication::AuthenticationStore {
cavv: tokenized_data.map(|tokenized_data| masking::Secret::new(tokenized_data.value1)),
authentication: updated_authentication
};
payment_data.authentication = Some(authentication_store.clone());
//If authentication is not successful, skip the payment connector flows and mark the payment as failure
if authentication_store.authentication.authentication_status
!= api_models::enums::AuthenticationStatus::Success
{
*should_continue_confirm_transaction = false;
}
},
}
}
Ok(())
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_data: &mut PaymentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
blocklist_utils::validate_data_for_blocklist(state, merchant_context, payment_data).await
}
#[instrument(skip_all)]
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> {
if let (Some(true), Some(domain::PaymentMethodData::Card(card)), Some(merchant_config)) = (
business_profile.is_extended_card_info_enabled,
payment_method_data,
business_profile.extended_card_info_config.clone(),
) {
let merchant_config = merchant_config
.expose()
.parse_value::<ExtendedCardInfoConfig>("ExtendedCardInfoConfig")
.map_err(|err| logger::error!(parse_err=?err,"Error while parsing ExtendedCardInfoConfig"));
let card_data = ExtendedCardInfo::from(card.clone())
.encode_to_vec()
.map_err(|err| logger::error!(encode_err=?err,"Error while encoding ExtendedCardInfo to vec"));
let (Ok(merchant_config), Ok(card_data)) = (merchant_config, card_data) else {
return Ok(());
};
let encrypted_payload =
services::encrypt_jwe(&card_data, merchant_config.public_key.peek(), services::EncryptionAlgorithm::A256GCM, None)
.await
.map_err(|err| {
logger::error!(jwe_encryption_err=?err,"Error while JWE encrypting extended card info")
});
let Ok(encrypted_payload) = encrypted_payload else {
return Ok(());
};
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = helpers::get_redis_key_for_extended_card_info(
&business_profile.merchant_id,
payment_id,
);
redis_conn
.set_key_with_expiry(
&key.into(),
encrypted_payload.clone(),
(*merchant_config.ttl_in_secs).into(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add extended card info in redis")?;
logger::info!("Extended card info added to redis");
}
Ok(())
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
_req_state: ReqState,
mut _payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>,
PaymentData<F>,
)>
where
F: 'b + Send,
{
todo!()
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for PaymentConfirm {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
frm_suggestion: Option<FrmSuggestion>,
header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>,
PaymentData<F>,
)>
where
F: 'b + Send,
{
let payment_method = payment_data.payment_attempt.payment_method;
let browser_info = payment_data.payment_attempt.browser_info.clone();
let frm_message = payment_data.frm_message.clone();
let capture_method = payment_data.payment_attempt.capture_method;
let default_status_result = (
storage_enums::IntentStatus::Processing,
storage_enums::AttemptStatus::Pending,
(None, None),
);
let status_handler_for_frm_results = |frm_suggestion: FrmSuggestion| match frm_suggestion {
FrmSuggestion::FrmCancelTransaction => (
storage_enums::IntentStatus::Failed,
storage_enums::AttemptStatus::Failure,
frm_message.map_or((None, None), |fraud_check| {
(
Some(Some(fraud_check.frm_status.to_string())),
Some(fraud_check.frm_reason.map(|reason| reason.to_string())),
)
}),
),
FrmSuggestion::FrmManualReview => (
storage_enums::IntentStatus::RequiresMerchantAction,
storage_enums::AttemptStatus::Unresolved,
(None, None),
),
FrmSuggestion::FrmAuthorizeTransaction => (
storage_enums::IntentStatus::RequiresCapture,
storage_enums::AttemptStatus::Authorized,
(None, None),
),
};
let status_handler_for_authentication_results =
|authentication: &storage::Authentication| {
if authentication.authentication_status.is_failed() {
(
storage_enums::IntentStatus::Failed,
storage_enums::AttemptStatus::Failure,
(
Some(Some("EXTERNAL_AUTHENTICATION_FAILURE".to_string())),
Some(Some("external authentication failure".to_string())),
),
)
} else if authentication.is_separate_authn_required() {
(
storage_enums::IntentStatus::RequiresCustomerAction,
storage_enums::AttemptStatus::AuthenticationPending,
(None, None),
)
} else {
default_status_result.clone()
}
};
let (intent_status, attempt_status, (error_code, error_message)) =
match (frm_suggestion, payment_data.authentication.as_ref()) {
(Some(frm_suggestion), _) => status_handler_for_frm_results(frm_suggestion),
(_, Some(authentication_details)) => status_handler_for_authentication_results(
&authentication_details.authentication,
),
_ => default_status_result,
};
let connector = payment_data.payment_attempt.connector.clone();
let merchant_connector_id = payment_data.payment_attempt.merchant_connector_id.clone();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone();
let straight_through_algorithm = payment_data
.payment_attempt
.straight_through_algorithm
.clone();
let payment_token = payment_data.token.clone();
let payment_method_type = payment_data.payment_attempt.payment_method_type;
let profile_id = payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_experience = payment_data.payment_attempt.payment_experience;
let additional_pm_data = payment_data
.payment_method_data
.as_ref()
.async_map(|payment_method_data| async {
helpers::get_additional_payment_data(payment_method_data, &*state.store, profile_id)
.await
})
.await
.transpose()?
.flatten();
let encoded_additional_pm_data = additional_pm_data
.as_ref()
.map(Encode::encode_to_value)
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
let customer_details = payment_data.payment_intent.customer_details.clone();
let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();
let authentication_type = payment_data.payment_attempt.authentication_type;
let (shipping_address_id, billing_address_id, payment_method_billing_address_id) = (
payment_data.payment_intent.shipping_address_id.clone(),
payment_data.payment_intent.billing_address_id.clone(),
payment_data
.payment_attempt
.payment_method_billing_address_id
.clone(),
);
let customer_id = customer.clone().map(|c| c.customer_id);
let return_url = payment_data.payment_intent.return_url.take();
let setup_future_usage = payment_data.payment_intent.setup_future_usage;
let business_label = payment_data.payment_intent.business_label.clone();
let business_country = payment_data.payment_intent.business_country;
let description = payment_data.payment_intent.description.take();
let statement_descriptor_name =
payment_data.payment_intent.statement_descriptor_name.take();
let statement_descriptor_suffix = payment_data
.payment_intent
.statement_descriptor_suffix
.take();
let order_details = payment_data.payment_intent.order_details.clone();
let metadata = payment_data.payment_intent.metadata.clone();
let frm_metadata = payment_data.payment_intent.frm_metadata.clone();
let client_source = header_payload
.client_source
.clone()
.or(payment_data.payment_attempt.client_source.clone());
let client_version = header_payload
.client_version
.clone()
.or(payment_data.payment_attempt.client_version.clone());
let m_payment_data_payment_attempt = payment_data.payment_attempt.clone();
let m_payment_method_id =
payment_data
.payment_attempt
.payment_method_id
.clone()
.or(payment_data
.payment_method_info
.as_ref()
.map(|payment_method| payment_method.payment_method_id.clone()));
let m_browser_info = browser_info.clone();
let m_connector = connector.clone();
let m_capture_method = capture_method;
let m_payment_token = payment_token.clone();
let m_additional_pm_data = encoded_additional_pm_data
.clone()
.or(payment_data.payment_attempt.payment_method_data.clone());
let m_business_sub_label = business_sub_label.clone();
let m_straight_through_algorithm = straight_through_algorithm.clone();
let m_error_code = error_code.clone();
let m_error_message = error_message.clone();
let m_fingerprint_id = payment_data.payment_attempt.fingerprint_id.clone();
let m_db = state.clone().store;
let surcharge_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_amount = payment_data
.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.tax_on_surcharge_amount);
let (
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
) = match payment_data.authentication.as_ref() {
Some(authentication_store) => (
Some(
authentication_store
.authentication
.is_separate_authn_required(),
),
authentication_store
.authentication
.authentication_connector
.clone(),
Some(
authentication_store
.authentication
.authentication_id
.clone(),
),
),
None => (None, None, None),
};
let card_discovery = payment_data.get_card_discovery_for_card_payment_method();
let is_stored_credential = helpers::is_stored_credential(
&payment_data.recurring_details,
&payment_data.pm_token,
payment_data.mandate_id.is_some(),
payment_data.payment_attempt.is_stored_credential,
);
let payment_attempt_fut = tokio::spawn(
async move {
m_db.update_payment_attempt_with_attempt_id(
m_payment_data_payment_attempt,
storage::PaymentAttemptUpdate::ConfirmUpdate {
currency: payment_data.currency,
status: attempt_status,
payment_method,
authentication_type,
capture_method: m_capture_method,
browser_info: m_browser_info,
connector: m_connector,
payment_token: m_payment_token,
payment_method_data: m_additional_pm_data,
payment_method_type,
payment_experience,
business_sub_label: m_business_sub_label,
straight_through_algorithm: m_straight_through_algorithm,
error_code: m_error_code,
error_message: m_error_message,
updated_by: storage_scheme.to_string(),
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
payment_method_billing_address_id,
fingerprint_id: m_fingerprint_id,
payment_method_id: m_payment_method_id,
client_source,
client_version,
customer_acceptance: payment_data.payment_attempt.customer_acceptance,
net_amount:
hyperswitch_domain_models::payments::payment_attempt::NetAmount::new(
payment_data.payment_attempt.net_amount.get_order_amount(),
payment_data.payment_intent.shipping_cost,
payment_data
.payment_attempt
.net_amount
.get_order_tax_amount(),
surcharge_amount,
tax_amount,
),
connector_mandate_detail: payment_data
.payment_attempt
.connector_mandate_detail,
card_discovery,
routing_approach: payment_data.payment_attempt.routing_approach,
connector_request_reference_id,
network_transaction_id: payment_data
.payment_attempt
.network_transaction_id
.clone(),
is_stored_credential,
request_extended_authorization: payment_data
.payment_attempt
.request_extended_authorization,
},
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
let billing_address = payment_data.address.get_payment_billing();
let key_manager_state = state.into();
let billing_details = billing_address
.async_map(|billing_details| {
create_encrypted_data(&key_manager_state, key_store, billing_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt billing details")?;
let shipping_address = payment_data.address.get_shipping();
let shipping_details = shipping_address
.async_map(|shipping_details| {
create_encrypted_data(&key_manager_state, key_store, shipping_details)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt shipping details")?;
let m_payment_data_payment_intent = payment_data.payment_intent.clone();
let m_customer_id = customer_id.clone();
let m_shipping_address_id = shipping_address_id.clone();
let m_billing_address_id = billing_address_id.clone();
let m_return_url = return_url.clone();
let m_business_label = business_label.clone();
let m_description = description.clone();
let m_statement_descriptor_name = statement_descriptor_name.clone();
let m_statement_descriptor_suffix = statement_descriptor_suffix.clone();
let m_order_details = order_details.clone();
let m_metadata = metadata.clone();
let m_frm_metadata = frm_metadata.clone();
let m_db = state.clone().store;
let m_storage_scheme = storage_scheme.to_string();
let session_expiry = m_payment_data_payment_intent.session_expiry;
let m_key_store = key_store.clone();
let key_manager_state = state.into();
let is_payment_processor_token_flow =
payment_data.payment_intent.is_payment_processor_token_flow;
let payment_intent_fut = tokio::spawn(
async move {
m_db.update_payment_intent(
&key_manager_state,
m_payment_data_payment_intent,
storage::PaymentIntentUpdate::Update(Box::new(PaymentIntentUpdateFields {
amount: payment_data.payment_intent.amount,
currency: payment_data.currency,
setup_future_usage,
status: intent_status,
customer_id: m_customer_id,
shipping_address_id: m_shipping_address_id,
billing_address_id: m_billing_address_id,
return_url: m_return_url,
business_country,
business_label: m_business_label,
description: m_description,
statement_descriptor_name: m_statement_descriptor_name,
statement_descriptor_suffix: m_statement_descriptor_suffix,
order_details: m_order_details,
metadata: m_metadata,
payment_confirm_source: header_payload.payment_confirm_source,
updated_by: m_storage_scheme,
fingerprint_id: None,
session_expiry,
request_external_three_ds_authentication: None,
frm_metadata: m_frm_metadata,
customer_details,
merchant_order_reference_id: None,
billing_details,
shipping_details,
is_payment_processor_token_flow,
tax_details: None,
force_3ds_challenge: payment_data.payment_intent.force_3ds_challenge,
is_iframe_redirection_enabled: payment_data
.payment_intent
.is_iframe_redirection_enabled,
is_confirm_operation: true, // Indicates that this is a confirm operation
payment_channel: payment_data.payment_intent.payment_channel,
feature_metadata: payment_data
.payment_intent
.feature_metadata
.clone()
.map(masking::Secret::new),
tax_status: payment_data.payment_intent.tax_status,
discount_amount: payment_data.payment_intent.discount_amount,
order_date: payment_data.payment_intent.order_date,
shipping_amount_tax: payment_data.payment_intent.shipping_amount_tax,
duty_amount: payment_data.payment_intent.duty_amount,
enable_partial_authorization: payment_data
.payment_intent
.enable_partial_authorization,
enable_overcapture: payment_data.payment_intent.enable_overcapture,
})),
&m_key_store,
storage_scheme,
)
.map(|x| x.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))
.await
}
.in_current_span(),
);
let customer_fut =
if let Some((updated_customer, customer)) = updated_customer.zip(customer) {
let m_customer_merchant_id = customer.merchant_id.to_owned();
let m_key_store = key_store.clone();
let m_updated_customer = updated_customer.clone();
let session_state = state.clone();
let m_db = session_state.store.clone();
let key_manager_state = state.into();
tokio::spawn(
async move {
let m_customer_customer_id = customer.customer_id.to_owned();
m_db.update_customer_by_customer_id_merchant_id(
&key_manager_state,
m_customer_customer_id,
m_customer_merchant_id,
customer,
m_updated_customer,
&m_key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update CustomerConnector in customer")?;
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(())
}
.in_current_span(),
)
} else {
tokio::spawn(
async move { Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(()) }
.in_current_span(),
)
};
let (payment_intent, payment_attempt, _) = tokio::try_join!(
utils::flatten_join_error(payment_intent_fut),
utils::flatten_join_error(payment_attempt_fut),
utils::flatten_join_error(customer_fut)
)?;
payment_data.payment_intent = payment_intent;
payment_data.payment_attempt = payment_attempt;
let client_src = payment_data.payment_attempt.client_source.clone();
let client_ver = payment_data.payment_attempt.client_version.clone();
let frm_message = payment_data.frm_message.clone();
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentConfirm {
client_src,
client_ver,
frm_message: Box::new(frm_message),
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
#[async_trait]
impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>>
for PaymentConfirm
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &api::PaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentConfirmOperation<'b, F>, operations::ValidateResult)> {
helpers::validate_customer_information(request)?;
if let Some(amount) = request.amount {
helpers::validate_max_amount(amount)?;
}
let request_merchant_id = request.merchant_id.as_ref();
helpers::validate_merchant_id(
merchant_context.get_merchant_account().get_id(),
request_merchant_id,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
})?;
helpers::validate_payment_method_fields_present(request)?;
let _mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
helpers::validate_recurring_details_and_token(
&request.recurring_details,
&request.payment_token,
&request.mandate_id,
)?;
request.validate_stored_credential().change_context(
errors::ApiErrorResponse::InvalidRequestData {
message:
"is_stored_credential should be true when reusing stored payment method data"
.to_string(),
},
)?;
let payment_id = request
.payment_id
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
let _request_straight_through: Option<api::routing::StraightThroughAlgorithm> = request
.routing
.clone()
.map(|val| val.parse_value("RoutingAlgorithm"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid straight through routing rules format".to_string(),
})
.attach_printable("Invalid straight through routing rules format")?;
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id,
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: matches!(
request.retry_action,
Some(api_models::enums::RetryAction::Requeue)
),
},
))
}
}
| crates/router/src/core/payments/operations/payment_confirm.rs | router::src::core::payments::operations::payment_confirm | 17,070 | true |
// File: crates/router/src/core/payments/operations/proxy_payments_intent.rs
// Module: router::src::core::payments::operations::proxy_payments_intent
use api_models::payments::ProxyPaymentsRequest;
use async_trait::async_trait;
use common_enums::enums;
use common_utils::types::keymanager::ToEncryptable;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData, payments::PaymentConfirmData,
};
use hyperswitch_interfaces::api::ConnectorSpecifications;
use masking::PeekInterface;
use router_env::{instrument, tracing};
use super::{Domain, GetTracker, Operation, PostUpdateTracker, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{
operations::{self, ValidateStatusForOperation},
OperationSessionGetters, OperationSessionSetters,
},
},
routes::{app::ReqState, SessionState},
types::{
self,
api::{self, ConnectorCallType},
domain::{self, types as domain_types},
storage::{self, enums as storage_enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentProxyIntent;
impl ValidateStatusForOperation for PaymentProxyIntent {
/// Validate if the current operation can be performed on the current status of the payment intent
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
//Failed state is included here so that in PCR, retries can be done for failed payments, otherwise for a failed attempt it was asking for new payment_intent
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Processing => Ok(()),
//Failed state is included here so that in PCR, retries can be done for failed payments, otherwise for a failed attempt it was asking for new payment_intent
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::Failed => Ok(()),
common_enums::IntentStatus::Conflicted
| common_enums::IntentStatus::Succeeded
| common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: ["requires_payment_method".to_string()].join(", "),
})
}
}
}
}
type BoxedConfirmOperation<'b, F> =
super::BoxedOperation<'b, F, ProxyPaymentsRequest, PaymentConfirmData<F>>;
impl<F: Send + Clone + Sync> Operation<F, ProxyPaymentsRequest> for &PaymentProxyIntent {
type Data = PaymentConfirmData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, ProxyPaymentsRequest, Self::Data> + Send + Sync)>
{
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, ProxyPaymentsRequest> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, ProxyPaymentsRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, ProxyPaymentsRequest> + Send + Sync)> {
Ok(*self)
}
}
#[automatically_derived]
impl<F: Send + Clone + Sync> Operation<F, ProxyPaymentsRequest> for PaymentProxyIntent {
type Data = PaymentConfirmData<F>;
fn to_validate_request(
&self,
) -> RouterResult<&(dyn ValidateRequest<F, ProxyPaymentsRequest, Self::Data> + Send + Sync)>
{
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, ProxyPaymentsRequest> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, ProxyPaymentsRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, ProxyPaymentsRequest> + Send + Sync)> {
Ok(self)
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, ProxyPaymentsRequest, PaymentConfirmData<F>>
for PaymentProxyIntent
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &ProxyPaymentsRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
let validate_result = operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
};
Ok(validate_result)
}
}
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentConfirmData<F>, ProxyPaymentsRequest>
for PaymentProxyIntent
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &ProxyPaymentsRequest,
merchant_context: &domain::MerchantContext,
_profile: &domain::Profile,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<PaymentConfirmData<F>>> {
let db = &*state.store;
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let cell_id = state.conf.cell_information.id.clone();
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::to_encryptable(
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt {
payment_method_billing_address: None,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payments::payment_attempt::FromRequestEncryptablePaymentAttempt::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let payment_attempt = match payment_intent.active_attempt_id.clone() {
Some(ref active_attempt_id) => db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
active_attempt_id,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Could not find payment attempt")?,
None => {
let payment_attempt_domain_model: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt =
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt::proxy_create_domain_model(
&payment_intent,
cell_id,
storage_scheme,
request,
encrypted_data
)
.await?;
db.insert_payment_attempt(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_attempt_domain_model,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not insert payment attempt")?
}
};
let processor_payment_token = request.recurring_details.processor_payment_token.clone();
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
.shipping_address
.clone()
.map(|address| address.into_inner()),
payment_intent
.billing_address
.clone()
.map(|address| address.into_inner()),
payment_attempt
.payment_method_billing_address
.clone()
.map(|address| address.into_inner()),
Some(true),
);
let mandate_data_input = api_models::payments::MandateIds {
mandate_id: None,
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId::new(
Some(processor_payment_token),
None,
None,
None,
None,
),
),
),
};
let payment_data = PaymentConfirmData {
flow: std::marker::PhantomData,
payment_intent,
payment_attempt,
payment_method_data: Some(PaymentMethodData::MandatePayment),
payment_address,
mandate_data: Some(mandate_data_input),
payment_method: None,
merchant_connector_details: None,
external_vault_pmd: None,
webhook_url: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Send + Sync> Domain<F, ProxyPaymentsRequest, PaymentConfirmData<F>>
for PaymentProxyIntent
{
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut PaymentConfirmData<F>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<(BoxedConfirmOperation<'a, F>, 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 PaymentConfirmData<F>,
_storage_scheme: storage_enums::MerchantStorageScheme,
_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
BoxedConfirmOperation<'a, F>,
Option<PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn populate_payment_data<'a>(
&'a self,
_state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
connector_data: &api::ConnectorData,
) -> CustomResult<(), errors::ApiErrorResponse> {
let connector_request_reference_id = connector_data
.connector
.generate_connector_request_reference_id(
&payment_data.payment_intent,
&payment_data.payment_attempt,
);
payment_data.set_connector_request_reference_id(Some(connector_request_reference_id));
Ok(())
}
async fn perform_routing<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
state: &SessionState,
payment_data: &mut PaymentConfirmData<F>,
) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse> {
let connector_name = payment_data.get_payment_attempt_connector();
if let Some(connector_name) = connector_name {
let merchant_connector_id = payment_data.get_merchant_connector_id_in_attempt();
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
merchant_connector_id,
)?;
Ok(ConnectorCallType::PreDetermined(connector_data.into()))
} else {
Err(error_stack::Report::new(
errors::ApiErrorResponse::InternalServerError,
))
}
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentConfirmData<F>, ProxyPaymentsRequest>
for PaymentProxyIntent
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: PaymentConfirmData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<api_models::enums::FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(BoxedConfirmOperation<'b, F>, PaymentConfirmData<F>)>
where
F: 'b + Send,
{
let db = &*state.store;
let key_manager_state = &state.into();
let intent_status = common_enums::IntentStatus::Processing;
let attempt_status = common_enums::AttemptStatus::Pending;
let connector = payment_data
.payment_attempt
.connector
.clone()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector is none when constructing response")?;
let merchant_connector_id = Some(
payment_data
.payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector id is none when constructing response")?,
);
let payment_intent_update =
hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::ConfirmIntent {
status: intent_status,
updated_by: storage_scheme.to_string(),
active_attempt_id: Some(payment_data.payment_attempt.id.clone()),
};
let authentication_type = payment_data
.payment_intent
.authentication_type
.unwrap_or_default();
let connector_request_reference_id = payment_data
.payment_attempt
.connector_request_reference_id
.clone();
let connector_response_reference_id = payment_data
.payment_attempt
.connector_response_reference_id
.clone();
let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ConfirmIntent {
status: attempt_status,
updated_by: storage_scheme.to_string(),
connector,
merchant_connector_id,
authentication_type,
connector_request_reference_id,
connector_response_reference_id,
};
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent.clone(),
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
payment_data.payment_intent = updated_payment_intent;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt.clone(),
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_attempt = updated_payment_attempt;
Ok((Box::new(self), payment_data))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<F: Clone> PostUpdateTracker<F, PaymentConfirmData<F>, types::PaymentsAuthorizeData>
for PaymentProxyIntent
{
async fn update_tracker<'b>(
&'b self,
state: &'b SessionState,
mut payment_data: PaymentConfirmData<F>,
response: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentConfirmData<F>>
where
F: 'b + Send + Sync,
types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<
F,
types::PaymentsAuthorizeData,
PaymentConfirmData<F>,
>,
{
use hyperswitch_domain_models::router_data::TrackerPostUpdateObjects;
let db = &*state.store;
let key_manager_state = &state.into();
let response_router_data = response;
let payment_intent_update =
response_router_data.get_payment_intent_update(&payment_data, storage_scheme);
let payment_attempt_update =
response_router_data.get_payment_attempt_update(&payment_data, storage_scheme);
let updated_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment intent")?;
let updated_payment_attempt = db
.update_payment_attempt(
key_manager_state,
key_store,
payment_data.payment_attempt,
payment_attempt_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment attempt")?;
payment_data.payment_intent = updated_payment_intent;
payment_data.payment_attempt = updated_payment_attempt;
Ok(payment_data)
}
}
| crates/router/src/core/payments/operations/proxy_payments_intent.rs | router::src::core::payments::operations::proxy_payments_intent | 4,038 | true |
// File: crates/router/src/core/payments/operations/payment_update_intent.rs
// Module: router::src::core::payments::operations::payment_update_intent
use std::marker::PhantomData;
use api_models::{
enums::{FrmSuggestion, UpdateActiveAttempt},
payments::PaymentsUpdateIntentRequest,
};
use async_trait::async_trait;
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, ValueExt},
types::keymanager::ToEncryptable,
};
use diesel_models::types::FeatureMetadata;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payments::payment_intent::{PaymentIntentUpdate, PaymentIntentUpdateFields},
ApiModelToDieselModelConvertor,
};
use masking::PeekInterface;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult},
payments::{
self, helpers,
operations::{self, ValidateStatusForOperation},
},
},
db::errors::StorageErrorExt,
routes::{app::ReqState, SessionState},
types::{
api,
domain::{self, types as domain_types},
storage::{self, enums},
},
};
#[derive(Debug, Clone, Copy)]
pub struct PaymentUpdateIntent;
impl ValidateStatusForOperation for PaymentUpdateIntent {
/// Validate if the current operation can be performed on the current status of the payment intent
fn validate_status_for_operation(
&self,
intent_status: common_enums::IntentStatus,
) -> Result<(), errors::ApiErrorResponse> {
match intent_status {
// if the status is `Failed`` we would want to Update few intent fields to perform a Revenue Recovery retry
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Conflicted => Ok(()),
common_enums::IntentStatus::Succeeded
| 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
| common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::RequiresConfirmation
| common_enums::IntentStatus::PartiallyCapturedAndCapturable
| common_enums::IntentStatus::Expired => {
Err(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: format!("{self:?}"),
field_name: "status".to_string(),
current_value: intent_status.to_string(),
states: ["requires_payment_method".to_string()].join(", "),
})
}
}
}
}
impl<F: Send + Clone> Operation<F, PaymentsUpdateIntentRequest> for &PaymentUpdateIntent {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, PaymentsUpdateIntentRequest, Self::Data> + Send + Sync),
> {
Ok(*self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&(dyn Domain<F, PaymentsUpdateIntentRequest, Self::Data>)> {
Ok(*self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(*self)
}
}
impl<F: Send + Clone> Operation<F, PaymentsUpdateIntentRequest> for PaymentUpdateIntent {
type Data = payments::PaymentIntentData<F>;
fn to_validate_request(
&self,
) -> RouterResult<
&(dyn ValidateRequest<F, PaymentsUpdateIntentRequest, Self::Data> + Send + Sync),
> {
Ok(self)
}
fn to_get_tracker(
&self,
) -> RouterResult<&(dyn GetTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, PaymentsUpdateIntentRequest, Self::Data>> {
Ok(self)
}
fn to_update_tracker(
&self,
) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, PaymentsUpdateIntentRequest> + Send + Sync)>
{
Ok(self)
}
}
type PaymentsUpdateIntentOperation<'b, F> =
BoxedOperation<'b, F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>;
#[async_trait]
impl<F: Send + Clone> GetTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest>
for PaymentUpdateIntent
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &common_utils::id_type::GlobalPaymentId,
request: &PaymentsUpdateIntentRequest,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<payments::PaymentIntentData<F>>> {
let db = &*state.store;
if let Some(routing_algorithm_id) = request.routing_algorithm_id.as_ref() {
helpers::validate_routing_id_with_profile_id(
db,
routing_algorithm_id,
profile.get_id(),
)
.await?;
}
let key_manager_state = &state.into();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
self.validate_status_for_operation(payment_intent.status)?;
let PaymentsUpdateIntentRequest {
amount_details,
routing_algorithm_id,
capture_method,
authentication_type,
billing,
shipping,
customer_present,
description,
return_url,
setup_future_usage,
apply_mit_exemption,
statement_descriptor,
order_details,
allowed_payment_method_types,
metadata,
connector_metadata,
feature_metadata,
payment_link_config,
request_incremental_authorization,
session_expiry,
frm_metadata,
request_external_three_ds_authentication,
set_active_attempt_id,
enable_partial_authorization,
} = request.clone();
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payments::PaymentIntent),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::to_encryptable(
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent {
shipping_address: shipping.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode shipping address")?.map(masking::Secret::new),
billing_address: billing.map(|address| address.encode_to_value()).transpose().change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to encode billing address")?.map(masking::Secret::new),
customer_details: None,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(merchant_context.get_merchant_account().get_id().to_owned()),
merchant_context.get_merchant_key_store().key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details".to_string())?;
let decrypted_payment_intent =
hyperswitch_domain_models::payments::FromRequestEncryptablePaymentIntent::from_encryptable(batch_encrypted_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment intent details")?;
let order_details = order_details.clone().map(|order_details| {
order_details
.into_iter()
.map(|order_detail| {
masking::Secret::new(
diesel_models::types::OrderDetailsWithAmount::convert_from(order_detail),
)
})
.collect()
});
let session_expiry = session_expiry.map(|expiry| {
payment_intent
.created_at
.saturating_add(time::Duration::seconds(i64::from(expiry)))
});
let updated_amount_details = match amount_details {
Some(details) => payment_intent.amount_details.update_from_request(&details),
None => payment_intent.amount_details,
};
let active_attempt_id = set_active_attempt_id
.map(|active_attempt_req| match active_attempt_req {
UpdateActiveAttempt::Set(global_attempt_id) => Some(global_attempt_id),
UpdateActiveAttempt::Unset => None,
})
.unwrap_or(payment_intent.active_attempt_id);
let payment_intent = hyperswitch_domain_models::payments::PaymentIntent {
amount_details: updated_amount_details,
description: description.or(payment_intent.description),
return_url: return_url.or(payment_intent.return_url),
metadata: metadata.or(payment_intent.metadata),
statement_descriptor: statement_descriptor.or(payment_intent.statement_descriptor),
modified_at: common_utils::date_time::now(),
order_details,
connector_metadata: connector_metadata.or(payment_intent.connector_metadata),
feature_metadata: (feature_metadata
.map(FeatureMetadata::convert_from)
.or(payment_intent.feature_metadata)),
updated_by: storage_scheme.to_string(),
request_incremental_authorization: request_incremental_authorization
.unwrap_or(payment_intent.request_incremental_authorization),
session_expiry: session_expiry.unwrap_or(payment_intent.session_expiry),
request_external_three_ds_authentication: request_external_three_ds_authentication
.unwrap_or(payment_intent.request_external_three_ds_authentication),
frm_metadata: frm_metadata.or(payment_intent.frm_metadata),
billing_address: decrypted_payment_intent
.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")?,
shipping_address: decrypted_payment_intent
.shipping_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 shipping address")?,
capture_method: capture_method.unwrap_or(payment_intent.capture_method),
authentication_type: authentication_type.or(payment_intent.authentication_type),
payment_link_config: payment_link_config
.map(ApiModelToDieselModelConvertor::convert_from)
.or(payment_intent.payment_link_config),
apply_mit_exemption: apply_mit_exemption.unwrap_or(payment_intent.apply_mit_exemption),
customer_present: customer_present.unwrap_or(payment_intent.customer_present),
routing_algorithm_id: routing_algorithm_id.or(payment_intent.routing_algorithm_id),
allowed_payment_method_types: allowed_payment_method_types
.or(payment_intent.allowed_payment_method_types),
active_attempt_id,
enable_partial_authorization: enable_partial_authorization
.or(payment_intent.enable_partial_authorization),
..payment_intent
};
let payment_data = payments::PaymentIntentData {
flow: PhantomData,
payment_intent,
client_secret: None,
sessions_token: vec![],
vault_session_details: None,
connector_customer_id: None,
};
let get_trackers_response = operations::GetTrackerResponse { payment_data };
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone> UpdateTracker<F, payments::PaymentIntentData<F>, PaymentsUpdateIntentRequest>
for PaymentUpdateIntent
{
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
_req_state: ReqState,
mut payment_data: payments::PaymentIntentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(
PaymentsUpdateIntentOperation<'b, F>,
payments::PaymentIntentData<F>,
)>
where
F: 'b + Send,
{
let db = &*state.store;
let key_manager_state = &state.into();
let intent = payment_data.payment_intent.clone();
let payment_intent_update =
PaymentIntentUpdate::UpdateIntent(Box::new(PaymentIntentUpdateFields {
amount: Some(intent.amount_details.order_amount),
currency: Some(intent.amount_details.currency),
shipping_cost: intent.amount_details.shipping_cost,
skip_external_tax_calculation: Some(
intent.amount_details.skip_external_tax_calculation,
),
skip_surcharge_calculation: Some(intent.amount_details.skip_surcharge_calculation),
surcharge_amount: intent.amount_details.surcharge_amount,
tax_on_surcharge: intent.amount_details.tax_on_surcharge,
routing_algorithm_id: intent.routing_algorithm_id,
capture_method: Some(intent.capture_method),
authentication_type: intent.authentication_type,
billing_address: intent.billing_address,
shipping_address: intent.shipping_address,
customer_present: Some(intent.customer_present),
description: intent.description,
return_url: intent.return_url,
setup_future_usage: Some(intent.setup_future_usage),
apply_mit_exemption: Some(intent.apply_mit_exemption),
statement_descriptor: intent.statement_descriptor,
order_details: intent.order_details,
allowed_payment_method_types: intent.allowed_payment_method_types,
metadata: intent.metadata,
connector_metadata: intent
.connector_metadata
.map(|cm| cm.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize connector_metadata")?
.map(masking::Secret::new),
feature_metadata: intent.feature_metadata,
payment_link_config: intent.payment_link_config,
request_incremental_authorization: Some(intent.request_incremental_authorization),
session_expiry: Some(intent.session_expiry),
frm_metadata: intent.frm_metadata,
request_external_three_ds_authentication: Some(
intent.request_external_three_ds_authentication,
),
updated_by: intent.updated_by,
tax_details: intent.amount_details.tax_details,
active_attempt_id: Some(intent.active_attempt_id),
force_3ds_challenge: intent.force_3ds_challenge,
is_iframe_redirection_enabled: intent.is_iframe_redirection_enabled,
enable_partial_authorization: intent.enable_partial_authorization,
}));
let new_payment_intent = db
.update_payment_intent(
key_manager_state,
payment_data.payment_intent,
payment_intent_update,
key_store,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not update Intent")?;
payment_data.payment_intent = new_payment_intent;
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone>
ValidateRequest<F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>
for PaymentUpdateIntent
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
_request: &PaymentsUpdateIntentRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<operations::ValidateResult> {
Ok(operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
})
}
}
#[async_trait]
impl<F: Clone + Send> Domain<F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>
for PaymentUpdateIntent
{
#[instrument(skip_all)]
async fn get_customer_details<'a>(
&'a self,
_state: &SessionState,
_payment_data: &mut payments::PaymentIntentData<F>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<
(
BoxedOperation<'a, F, PaymentsUpdateIntentRequest, payments::PaymentIntentData<F>>,
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 payments::PaymentIntentData<F>,
_storage_scheme: enums::MerchantStorageScheme,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_business_profile: &domain::Profile,
_should_retry_with_pan: bool,
) -> RouterResult<(
PaymentsUpdateIntentOperation<'a, F>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
Ok((Box::new(self), None, None))
}
#[instrument(skip_all)]
async fn perform_routing<'a>(
&'a self,
_merchant_context: &domain::MerchantContext,
_business_profile: &domain::Profile,
_state: &SessionState,
_payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
Ok(api::ConnectorCallType::Skip)
}
#[instrument(skip_all)]
async fn guard_payment_against_blocklist<'a>(
&'a self,
_state: &SessionState,
_merchant_context: &domain::MerchantContext,
_payment_data: &mut payments::PaymentIntentData<F>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
Ok(false)
}
}
| crates/router/src/core/payments/operations/payment_update_intent.rs | router::src::core::payments::operations::payment_update_intent | 3,959 | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.