repo
stringclasses 1
value | instance_id
stringlengths 22
24
| problem_statement
stringlengths 24
24.1k
| patch
stringlengths 0
1.9M
| test_patch
stringclasses 1
value | created_at
stringdate 2022-11-25 05:12:07
2025-10-09 08:44:51
| hints_text
stringlengths 11
235k
| base_commit
stringlengths 40
40
| test_instructions
stringlengths 0
232k
|
|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch
|
juspay__hyperswitch-4948
|
Bug: [REFACTOR] wrap the encryption and file storage interface client in appstate with `Arc` as opposed to `Box`
Currently, the encryption interface and file storage interface client is wrapped with `Box`. These clients live in AppState. Since state is cloned for each api handler, wrap the clients in `Arc` so that the internal data doesn't gets cloned.
|
diff --git a/crates/drainer/src/settings.rs b/crates/drainer/src/settings.rs
index 311cee0cede..e64b5dbd4ad 100644
--- a/crates/drainer/src/settings.rs
+++ b/crates/drainer/src/settings.rs
@@ -31,7 +31,7 @@ pub struct CmdLineConf {
#[derive(Clone)]
pub struct AppState {
pub conf: Arc<Settings<RawSecret>>,
- pub encryption_client: Box<dyn EncryptionManagementInterface>,
+ pub encryption_client: Arc<dyn EncryptionManagementInterface>,
}
impl AppState {
diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs
index fb419b6ec64..e551cfee2af 100644
--- a/crates/external_services/src/file_storage.rs
+++ b/crates/external_services/src/file_storage.rs
@@ -2,7 +2,10 @@
//! Module for managing file storage operations with support for multiple storage schemes.
//!
-use std::fmt::{Display, Formatter};
+use std::{
+ fmt::{Display, Formatter},
+ sync::Arc,
+};
use common_utils::errors::CustomResult;
@@ -39,11 +42,11 @@ impl FileStorageConfig {
}
/// Retrieves the appropriate file storage client based on the file storage configuration.
- pub async fn get_file_storage_client(&self) -> Box<dyn FileStorageInterface> {
+ pub async fn get_file_storage_client(&self) -> Arc<dyn FileStorageInterface> {
match self {
#[cfg(feature = "aws_s3")]
- Self::AwsS3 { aws_s3 } => Box::new(aws_s3::AwsFileStorageClient::new(aws_s3).await),
- Self::FileSystem => Box::new(file_system::FileSystem),
+ Self::AwsS3 { aws_s3 } => Arc::new(aws_s3::AwsFileStorageClient::new(aws_s3).await),
+ Self::FileSystem => Arc::new(file_system::FileSystem),
}
}
}
diff --git a/crates/external_services/src/managers/encryption_management.rs b/crates/external_services/src/managers/encryption_management.rs
index 4612190926c..678239c60b1 100644
--- a/crates/external_services/src/managers/encryption_management.rs
+++ b/crates/external_services/src/managers/encryption_management.rs
@@ -2,6 +2,8 @@
//! Encryption management util module
//!
+use std::sync::Arc;
+
use common_utils::errors::CustomResult;
use hyperswitch_interfaces::encryption_interface::{
EncryptionError, EncryptionManagementInterface,
@@ -42,12 +44,12 @@ impl EncryptionManagementConfig {
/// Retrieves the appropriate encryption client based on the configuration.
pub async fn get_encryption_management_client(
&self,
- ) -> CustomResult<Box<dyn EncryptionManagementInterface>, EncryptionError> {
+ ) -> CustomResult<Arc<dyn EncryptionManagementInterface>, EncryptionError> {
Ok(match self {
#[cfg(feature = "aws_kms")]
- Self::AwsKms { aws_kms } => Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await),
+ Self::AwsKms { aws_kms } => Arc::new(aws_kms::core::AwsKmsClient::new(aws_kms).await),
- Self::NoEncryption => Box::new(NoEncryption),
+ Self::NoEncryption => Arc::new(NoEncryption),
})
}
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 83d8c714e92..8d88d9c4b26 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -82,7 +82,7 @@ pub struct SessionState {
pub email_client: Arc<dyn EmailService>,
#[cfg(feature = "olap")]
pub pool: AnalyticsProvider,
- pub file_storage_client: Box<dyn FileStorageInterface>,
+ pub file_storage_client: Arc<dyn FileStorageInterface>,
pub request_id: Option<RequestId>,
pub base_url: String,
pub tenant: String,
@@ -144,8 +144,8 @@ pub struct AppState {
#[cfg(feature = "olap")]
pub opensearch_client: Arc<OpenSearchClient>,
pub request_id: Option<RequestId>,
- pub file_storage_client: Box<dyn FileStorageInterface>,
- pub encryption_client: Box<dyn EncryptionManagementInterface>,
+ pub file_storage_client: Arc<dyn FileStorageInterface>,
+ pub encryption_client: Arc<dyn EncryptionManagementInterface>,
}
impl scheduler::SchedulerAppState for AppState {
fn get_tenants(&self) -> Vec<String> {
|
2024-06-11T11:33:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently, the encryption interface and file storage interface client is wrapped with `Box`. These clients live in `AppState`. Since state is cloned for each api handler, wrapping the clients in Arc will help in not cloning the actual internal data rather maintaining a counter on the single client instance.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Basic sanity testing should suffice
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b705757be37a9803b964ef94d04c664c0f1e102d
|
Basic sanity testing should suffice
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4975
|
Bug: Include the pre-routing connectors in apple pay retries
Currently for apple pay pre-routing is done before the session call and only one connector is decided based on the routing logic. Now since we want to enable auto retries for apple pay we need to consider all the connectors form the routing rule and construct a list of it. After which this connectors should be filtered out with the connectors that supports apple pay simplified flow.
Once this is done there will be a list of connectors with which apple pay retries can we performed.
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 0641c842390..04983ed8b19 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2085,7 +2085,15 @@ pub async fn list_payment_methods(
}
if let Some(choice) = result.get(&intermediate.payment_method_type) {
- intermediate.connector == choice.connector.connector_name.to_string()
+ if let Some(first_routable_connector) = choice.first() {
+ intermediate.connector
+ == first_routable_connector
+ .connector
+ .connector_name
+ .to_string()
+ } else {
+ false
+ }
} else {
false
}
@@ -2105,26 +2113,32 @@ pub async fn list_payment_methods(
let mut pre_routing_results: HashMap<
api_enums::PaymentMethodType,
- routing_types::RoutableConnectorChoice,
+ storage::PreRoutingConnectorChoice,
> = HashMap::new();
- for (pm_type, choice) in result {
- let routable_choice = routing_types::RoutableConnectorChoice {
- #[cfg(feature = "backwards_compatibility")]
- choice_kind: routing_types::RoutableChoiceKind::FullStruct,
- connector: choice
- .connector
- .connector_name
- .to_string()
- .parse::<api_enums::RoutableConnectors>()
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- #[cfg(feature = "connector_choice_mca_id")]
- merchant_connector_id: choice.connector.merchant_connector_id,
- #[cfg(not(feature = "connector_choice_mca_id"))]
- sub_label: choice.sub_label,
- };
-
- pre_routing_results.insert(pm_type, routable_choice);
+ for (pm_type, routing_choice) in result {
+ let mut routable_choice_list = vec![];
+ for choice in routing_choice {
+ let routable_choice = routing_types::RoutableConnectorChoice {
+ #[cfg(feature = "backwards_compatibility")]
+ choice_kind: routing_types::RoutableChoiceKind::FullStruct,
+ connector: choice
+ .connector
+ .connector_name
+ .to_string()
+ .parse::<api_enums::RoutableConnectors>()
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ #[cfg(feature = "connector_choice_mca_id")]
+ merchant_connector_id: choice.connector.merchant_connector_id.clone(),
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: choice.sub_label,
+ };
+ routable_choice_list.push(routable_choice);
+ }
+ pre_routing_results.insert(
+ pm_type,
+ storage::PreRoutingConnectorChoice::Multiple(routable_choice_list),
+ );
}
let redis_conn = db
@@ -2135,15 +2149,28 @@ pub async fn list_payment_methods(
let mut val = Vec::new();
for (payment_method_type, routable_connector_choice) in &pre_routing_results {
+ 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 first_routable_connector = routable_connector_list
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
+
#[cfg(not(feature = "connector_choice_mca_id"))]
let connector_label = get_connector_label(
payment_intent.business_country,
payment_intent.business_label.as_ref(),
#[cfg(not(feature = "connector_choice_mca_id"))]
- routable_connector_choice.sub_label.as_ref(),
+ first_routable_connector.sub_label.as_ref(),
#[cfg(feature = "connector_choice_mca_id")]
None,
- routable_connector_choice.connector.to_string().as_str(),
+ first_routable_connector.connector.to_string().as_str(),
);
#[cfg(not(feature = "connector_choice_mca_id"))]
let matched_mca = filtered_mcas
@@ -2152,7 +2179,7 @@ pub async fn list_payment_methods(
#[cfg(feature = "connector_choice_mca_id")]
let matched_mca = filtered_mcas.iter().find(|m| {
- routable_connector_choice.merchant_connector_id.as_ref()
+ first_routable_connector.merchant_connector_id.as_ref()
== Some(&m.merchant_connector_id)
});
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index e1290637dbe..50eedcfb568 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3182,32 +3182,51 @@ where
.as_ref()
.zip(payment_data.payment_attempt.payment_method_type.as_ref())
{
- if let (Some(choice), None) = (
+ if let (Some(routable_connector_choice), None) = (
pre_routing_results.get(storage_pm_type),
&payment_data.token_data,
) {
- let connector_data = api::ConnectorData::get_connector_by_name(
- &state.conf.connectors,
- &choice.connector.to_string(),
- api::GetToken::Connector,
- #[cfg(feature = "connector_choice_mca_id")]
- choice.merchant_connector_id.clone(),
- #[cfg(not(feature = "connector_choice_mca_id"))]
- None,
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Invalid connector name received")?;
+ 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(choice.connector.to_string());
+ routing_data.routed_through = Some(first_routable_connector.connector.to_string());
#[cfg(feature = "connector_choice_mca_id")]
{
routing_data
.merchant_connector_id
- .clone_from(&choice.merchant_connector_id);
+ .clone_from(&first_routable_connector.merchant_connector_id);
}
#[cfg(not(feature = "connector_choice_mca_id"))]
{
- routing_data.business_sub_label = choice.sub_label.clone();
+ routing_data.business_sub_label = first_routable_connector.sub_label.clone();
+ }
+
+ 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,
+ #[cfg(feature = "connector_choice_mca_id")]
+ connector_choice.merchant_connector_id.clone(),
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ None,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Invalid connector name received")?;
+
+ pre_routing_connector_data_list.push(connector_data);
}
#[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))]
@@ -3224,8 +3243,11 @@ where
merchant_account,
payment_data,
key_store,
- connector_data.clone(),
- choice.merchant_connector_id.clone().as_ref(),
+ &pre_routing_connector_data_list,
+ first_routable_connector
+ .merchant_connector_id
+ .clone()
+ .as_ref(),
)
.await?;
@@ -3237,7 +3259,13 @@ where
}
}
- return Ok(ConnectorCallType::PreDetermined(connector_data));
+ let first_pre_routing_connector_data_list = pre_routing_connector_data_list
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
+
+ return Ok(ConnectorCallType::PreDetermined(
+ first_pre_routing_connector_data_list.clone(),
+ ));
}
}
@@ -3614,11 +3642,22 @@ where
}));
let mut final_list: Vec<api::SessionConnectorData> = Vec::new();
- for (routed_pm_type, choice) in pre_routing_results.into_iter() {
- if let Some(session_connector_data) =
- payment_methods.remove(&(choice.to_string(), routed_pm_type))
- {
- final_list.push(session_connector_data);
+ for (routed_pm_type, pre_routing_choice) in pre_routing_results.into_iter() {
+ let routable_connector_list = match pre_routing_choice {
+ storage::PreRoutingConnectorChoice::Single(routable_connector) => {
+ vec![routable_connector.clone()]
+ }
+ storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
+ routable_connector_list.clone()
+ }
+ };
+ for routable_connector in routable_connector_list {
+ if let Some(session_connector_data) =
+ payment_methods.remove(&(routable_connector.to_string(), routed_pm_type))
+ {
+ final_list.push(session_connector_data);
+ break;
+ }
}
}
@@ -3666,8 +3705,11 @@ where
if !routing_enabled_pms.contains(&connector_data.payment_method_type) {
final_list.push(connector_data);
} else if let Some(choice) = result.get(&connector_data.payment_method_type) {
- if connector_data.connector.connector_name == choice.connector.connector_name {
- connector_data.business_sub_label = choice.sub_label.clone();
+ let routing_choice = choice
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;
+ if connector_data.connector.connector_name == routing_choice.connector.connector_name {
+ connector_data.business_sub_label = routing_choice.sub_label.clone();
final_list.push(connector_data);
}
}
@@ -3678,7 +3720,10 @@ where
if !routing_enabled_pms.contains(&connector_data.payment_method_type) {
final_list.push(connector_data);
} else if let Some(choice) = result.get(&connector_data.payment_method_type) {
- if connector_data.connector.connector_name == choice.connector.connector_name {
+ let routing_choice = choice
+ .first()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;
+ if connector_data.connector.connector_name == routing_choice.connector.connector_name {
final_list.push(connector_data);
}
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index c94c1c714c7..a3751465b2c 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4022,7 +4022,7 @@ pub async fn get_apple_pay_retryable_connectors<F>(
merchant_account: &domain::MerchantAccount,
payment_data: &mut PaymentData<F>,
key_store: &domain::MerchantKeyStore,
- decided_connector_data: api::ConnectorData,
+ pre_routing_connector_data_list: &[api::ConnectorData],
merchant_connector_id: Option<&String>,
) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse>
where
@@ -4037,13 +4037,17 @@ where
field_name: "profile_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_account.merchant_id.as_str(),
payment_data.creds_identifier.to_owned(),
key_store,
profile_id,
- &decided_connector_data.connector_name.to_string(),
+ &pre_decided_connector_data_first.connector_name.to_string(),
merchant_connector_id,
)
.await?;
@@ -4070,7 +4074,7 @@ where
Some(profile_id.to_string()),
);
- let mut connector_data_list = vec![decided_connector_data.clone()];
+ 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(
@@ -4107,16 +4111,31 @@ where
.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.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 default fallback connectors configuration.
- let mut ordered_connector_data_list = vec![decided_connector_data.clone()];
- fallback_connetors_list
+ // 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(|fallback_connector| {
+ .for_each(|merchant_connector_id| {
let connector_data = connector_data_list.iter().find(|connector_data| {
- fallback_connector.merchant_connector_id == connector_data.merchant_connector_id
- && fallback_connector.merchant_connector_id
- != decided_connector_data.merchant_connector_id
+ *merchant_connector_id == connector_data.merchant_connector_id
});
if let Some(connector_data_details) = connector_data {
ordered_connector_data_list.push(connector_data_details.clone());
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 4394637d99a..3afb933d467 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -855,7 +855,8 @@ pub async fn perform_eligibility_analysis_with_fallback<F: Clone>(
pub async fn perform_session_flow_routing(
session_input: SessionFlowRoutingInput<'_>,
transaction_type: &api_enums::TransactionType,
-) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice>> {
+) -> RoutingResult<FxHashMap<api_enums::PaymentMethodType, Vec<routing_types::SessionRoutingChoice>>>
+{
let mut pm_type_map: FxHashMap<api_enums::PaymentMethodType, FxHashMap<String, api::GetToken>> =
FxHashMap::default();
@@ -962,8 +963,10 @@ pub async fn perform_session_flow_routing(
);
}
- let mut result: FxHashMap<api_enums::PaymentMethodType, routing_types::SessionRoutingChoice> =
- FxHashMap::default();
+ 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;
@@ -985,20 +988,37 @@ pub async fn perform_session_flow_routing(
))]
profile_id: session_input.payment_intent.profile_id.clone(),
};
- let maybe_choice =
- perform_session_routing_for_pm_type(session_pm_input, transaction_type).await?;
-
- // (connector, sub_label)
- if let Some(data) = maybe_choice {
- result.insert(
- pm_type,
- routing_types::SessionRoutingChoice {
- connector: data.0,
+ let routable_connector_choice_option =
+ perform_session_routing_for_pm_type(&session_pm_input, transaction_type).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(
+ &session_pm_input.state.clone().conf.connectors,
+ &connector_name,
+ get_token.clone(),
+ #[cfg(feature = "connector_choice_mca_id")]
+ selection.merchant_connector_id,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ None,
+ )
+ .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
#[cfg(not(feature = "connector_choice_mca_id"))]
- sub_label: data.1,
- payment_method_type: pm_type,
- },
- );
+ let sub_label = selection.sub_label;
+
+ session_routing_choice.push(routing_types::SessionRoutingChoice {
+ connector: connector_data,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: sub_label,
+ payment_method_type: pm_type,
+ });
+ }
+ }
+ result.insert(pm_type, session_routing_choice);
}
}
@@ -1006,9 +1026,9 @@ pub async fn perform_session_flow_routing(
}
async fn perform_session_routing_for_pm_type(
- session_pm_input: SessionRoutingPmTypeInput<'_>,
+ session_pm_input: &SessionRoutingPmTypeInput<'_>,
transaction_type: &api_enums::TransactionType,
-) -> RoutingResult<Option<(api::ConnectorData, Option<String>)>> {
+) -> RoutingResult<Option<Vec<api_models::routing::RoutableConnectorChoice>>> {
let merchant_id = &session_pm_input.key_store.merchant_id;
let chosen_connectors = match session_pm_input.routing_algorithm {
@@ -1091,7 +1111,7 @@ async fn perform_session_routing_for_pm_type(
&session_pm_input.state.clone(),
session_pm_input.key_store,
fallback,
- session_pm_input.backend_input,
+ session_pm_input.backend_input.clone(),
None,
#[cfg(feature = "business_profile_routing")]
session_pm_input.profile_id.clone(),
@@ -1100,32 +1120,11 @@ async fn perform_session_routing_for_pm_type(
.await?;
}
- let mut final_choice: Option<(api::ConnectorData, Option<String>)> = None;
-
- for selection in final_selection {
- 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(),
- #[cfg(feature = "connector_choice_mca_id")]
- selection.merchant_connector_id,
- #[cfg(not(feature = "connector_choice_mca_id"))]
- None,
- )
- .change_context(errors::RoutingError::InvalidConnectorName(connector_name))?;
- #[cfg(not(feature = "connector_choice_mca_id"))]
- let sub_label = selection.sub_label;
- #[cfg(feature = "connector_choice_mca_id")]
- let sub_label = None;
-
- final_choice = Some((connector_data, sub_label));
- break;
- }
+ if final_selection.is_empty() {
+ Ok(None)
+ } else {
+ Ok(Some(final_selection))
}
-
- Ok(final_choice)
}
pub fn make_dsl_input_for_surcharge(
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 77550bedabe..79c8b2ed2f0 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -81,14 +81,21 @@ pub struct RoutingData {
pub struct PaymentRoutingInfo {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
- Option<HashMap<api_models::enums::PaymentMethodType, routing::RoutableConnectorChoice>>,
+ Option<HashMap<api_models::enums::PaymentMethodType, PreRoutingConnectorChoice>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentRoutingInfoInner {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
- Option<HashMap<api_models::enums::PaymentMethodType, routing::RoutableConnectorChoice>>,
+ Option<HashMap<api_models::enums::PaymentMethodType, PreRoutingConnectorChoice>>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(untagged)]
+pub enum PreRoutingConnectorChoice {
+ Single(routing::RoutableConnectorChoice),
+ Multiple(Vec<routing::RoutableConnectorChoice>),
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
2024-06-11T16:09:43Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently for apple pay pre-routing is done before the session call and only one connector is decided based on the routing logic. Now since we want to enable auto retries for apple pay we need to consider all the connectors form the routing rule and construct a list of it. After which this connectors should be filtered out with the connectors that supports apple pay simplified flow.
Once this is done there will be a list of connectors with which apple pay retries can we performed.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create merchant account
-> Enable auto retries for the specific `merchant_id`
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "should_call_gsm_merchant_1718202727",
"value": "true"
}'
```
-> Set the maximum retry counts for the auto retries enabled `merchant_id`
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "max_auto_retries_enabled_merchant_1718202727",
"value": "1"
}'
```
-> Configure the error code and error message in the gsm
```
curl --location 'localhost:8080/gsm' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"connector": "stripe",
"flow": "Authorize",
"sub_flow": "sub_flow",
"code": "No error code",
"message": "No error message",
"status": "Failure",
"decision": "retry",
"step_up_possible": false
}'
```
-> Create merchant connector accounts (enable apple pay simplified if you wish to retry the failed apple pay payment with it)
metadata for simplified flow
```
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Configure the routing rules for the configured connectors
```
curl --location 'http://localhost:8080/routing' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \
--data '{
"name": "priority config",
"description": "some desc",
"algorithm": {
"type": "priority",
"data": [
{
"connector": "stripe",
"merchant_connector_id": "mca_eF7yV3fNcAZ2wmGlKORq"
},
{
"connector": "cybersource",
"merchant_connector_id": "mca_YAgldl8pmWD7mlqKrPlj"
},
{
"connector": "adyen",
"merchant_connector_id": "mca_rkYJzRw3mSpDnPr25huU"
},
{
"connector": "rapyd",
"merchant_connector_id": "mca_Vjg1fbX8FKP2ywlU4kOq"
}
]
},
"profile_id": "pro_Rv8QaYCARaEOCglUGXpa"
}'
```
<img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0fc7248d-abcb-487f-b266-afa98b28b2d6">
-> Create a apple pay payment with confirm false
```
{
"amount": 6500,
"currency": "USD",
"confirm": false,
"amount_to_capture": 6500,
"customer_id": "test_priority_routing",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}
```
<img width="1001" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/5674379f-7f8a-4705-ace3-f36f1d761671">
-> List payment methods for merchant
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_uKquqDLCGBBzbXpsEKyy_secret_soCWAMLK8xCq7WZ42KQD' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_97bb28e2fc3b42099d802df96188f7ec'
```
<img width="1120" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9eac6d54-f99d-4b5a-bddb-3b1b8aecade2">
-> Confirm the payment with `payment_id`
```
curl --location 'http://localhost:8080/payments/pay_uKquqDLCGBBzbXpsEKyy/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \
--data '{
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}'
```
<img width="1075" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9400e62e-7a9b-4f4b-b8af-cba74d61719e">
-> Retrieve the payment with the `payment_id`.
```
curl --location 'http://localhost:8080/payments/pay_uKquqDLCGBBzbXpsEKyy?expand_attempts=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn'
```
<img width="737" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/6b290982-7d4b-4e92-b21b-cd756c2d4f02">
In the above response we can see that apple payment got failed with stripe and it was auto retried with adyen based on the configured routing rule.
-> The routing rule configured during test is as shown below
<img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c7916e7f-f3f8-4529-b90c-aafc67de28a9">
-> Below is entry of the pre-routing in the payment attempt table
"apple_pay": [{"connector": "stripe", "merchant_c
onnector_id": "mca_eF7yV3fNcAZ2wmGlKORq"}, {"connector": "cybersource", "merchant_connector_id": "mca_YAgldl8pmWD7mlqKrPlj"}, {"connector": "adyen", "merchant_connector_id": "mca_rkYJzRw3mSpDnPr25huU"}, {"connector": "rapyd", "merchant_connector_id": "mca_Vjg1fbX8FKP2ywlU4kOq"}],
-> The order of apple pay retryable connector as below. As per the routing rules the stripe comes in the first of the list followed by adyen, as apple pay simplified flow is configured only for stripe and adyen.

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b847606d665388fba898425b31dd5f207f60a56e
|
-> Create merchant account
-> Enable auto retries for the specific `merchant_id`
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "should_call_gsm_merchant_1718202727",
"value": "true"
}'
```
-> Set the maximum retry counts for the auto retries enabled `merchant_id`
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "max_auto_retries_enabled_merchant_1718202727",
"value": "1"
}'
```
-> Configure the error code and error message in the gsm
```
curl --location 'localhost:8080/gsm' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"connector": "stripe",
"flow": "Authorize",
"sub_flow": "sub_flow",
"code": "No error code",
"message": "No error message",
"status": "Failure",
"decision": "retry",
"step_up_possible": false
}'
```
-> Create merchant connector accounts (enable apple pay simplified if you wish to retry the failed apple pay payment with it)
metadata for simplified flow
```
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Configure the routing rules for the configured connectors
```
curl --location 'http://localhost:8080/routing' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \
--data '{
"name": "priority config",
"description": "some desc",
"algorithm": {
"type": "priority",
"data": [
{
"connector": "stripe",
"merchant_connector_id": "mca_eF7yV3fNcAZ2wmGlKORq"
},
{
"connector": "cybersource",
"merchant_connector_id": "mca_YAgldl8pmWD7mlqKrPlj"
},
{
"connector": "adyen",
"merchant_connector_id": "mca_rkYJzRw3mSpDnPr25huU"
},
{
"connector": "rapyd",
"merchant_connector_id": "mca_Vjg1fbX8FKP2ywlU4kOq"
}
]
},
"profile_id": "pro_Rv8QaYCARaEOCglUGXpa"
}'
```
<img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0fc7248d-abcb-487f-b266-afa98b28b2d6">
-> Create a apple pay payment with confirm false
```
{
"amount": 6500,
"currency": "USD",
"confirm": false,
"amount_to_capture": 6500,
"customer_id": "test_priority_routing",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}
```
<img width="1001" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/5674379f-7f8a-4705-ace3-f36f1d761671">
-> List payment methods for merchant
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_uKquqDLCGBBzbXpsEKyy_secret_soCWAMLK8xCq7WZ42KQD' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_97bb28e2fc3b42099d802df96188f7ec'
```
<img width="1120" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9eac6d54-f99d-4b5a-bddb-3b1b8aecade2">
-> Confirm the payment with `payment_id`
```
curl --location 'http://localhost:8080/payments/pay_uKquqDLCGBBzbXpsEKyy/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn' \
--data '{
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}'
```
<img width="1075" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9400e62e-7a9b-4f4b-b8af-cba74d61719e">
-> Retrieve the payment with the `payment_id`.
```
curl --location 'http://localhost:8080/payments/pay_uKquqDLCGBBzbXpsEKyy?expand_attempts=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_T4l0hzK8OqmFbaNYGWEVhC6d0RkxRKPCMyA3Fi0C94C7kweFZSErnTz5fNuw8sCn'
```
<img width="737" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/6b290982-7d4b-4e92-b21b-cd756c2d4f02">
In the above response we can see that apple payment got failed with stripe and it was auto retried with adyen based on the configured routing rule.
-> The routing rule configured during test is as shown below
<img width="1133" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c7916e7f-f3f8-4529-b90c-aafc67de28a9">
-> Below is entry of the pre-routing in the payment attempt table
"apple_pay": [{"connector": "stripe", "merchant_c
onnector_id": "mca_eF7yV3fNcAZ2wmGlKORq"}, {"connector": "cybersource", "merchant_connector_id": "mca_YAgldl8pmWD7mlqKrPlj"}, {"connector": "adyen", "merchant_connector_id": "mca_rkYJzRw3mSpDnPr25huU"}, {"connector": "rapyd", "merchant_connector_id": "mca_Vjg1fbX8FKP2ywlU4kOq"}],
-> The order of apple pay retryable connector as below. As per the routing rules the stripe comes in the first of the list followed by adyen, as apple pay simplified flow is configured only for stripe and adyen.

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4947
|
Bug: [REFACTOR] Allow deletion of Default Payment Methods
### Feature Description
Allow deletion of Payment Methods , even if there is only one PM for that respective connector
### Possible Implementation
Allow deletion of Payment Methods , even if there is only one PM for that respective connector
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 499eddafc1f..0641c842390 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3993,16 +3993,6 @@ pub async fn delete_payment_method(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- let payment_methods_count = db
- .get_payment_method_count_by_customer_id_merchant_id_status(
- &key.customer_id,
- &merchant_account.merchant_id,
- api_enums::PaymentMethodStatus::Active,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get a count of payment methods for a customer")?;
-
let customer = db
.find_customer_by_customer_id_merchant_id(
&key.customer_id,
@@ -4014,12 +4004,6 @@ pub async fn delete_payment_method(
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Customer not found for the payment method")?;
- utils::when(
- customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id)
- && payment_methods_count > 1,
- || Err(errors::ApiErrorResponse::PaymentMethodDeleteFailed),
- )?;
-
if key.payment_method == Some(enums::PaymentMethod::Card) {
let response = delete_card_from_locker(
&state,
|
2024-06-11T08:57:32Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Previously we did not support the deletion of the Default Payment Method, if it's the only PM for the particular customer. In this PR we enable deletion of default Payment Methods
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create a MA and a MCA
- Do a payment , with `setup_future_usag:off_session`; the card would be saved
- Do a List PM for Customers, you'll have only one card , which has been set as default
```
Response
{
"customer_payment_methods": [
{
"payment_token": "token_FC8TupTKMEmhtM69dmYS",
"payment_method_id": "pm_Syvbg2Nb8mGdZC9oi4Sv",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "11",
"expiry_year": "2040",
"card_token": null,
"card_holder_name": "AKA",
"card_fingerprint": null,
"nick_name": "HELO",
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-06-11T10:14:09.587Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-06-11T10:14:09.587Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
- Delete the Payment Method, it'll be a success
```
Request
curl --location --request DELETE 'http://localhost:8080/payment_methods/:payment_method_id' \
--header 'Accept: application/json' \
--header 'api-key: dev_u3eBlxHY8BxUeQxxgvZGxKRXf7HEPaAw0sXmhjXjFFTmQ0pfyslENYRDajyrQnOf'
```
```
Response
{
"payment_method_id": "pm_50cS5VsVOhgbKQ63WReh",
"deleted": true
}
```
- List the Pm for Customer would be empty
```
Response
{
"customer_payment_methods": [],
"is_guest_customer": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b705757be37a9803b964ef94d04c664c0f1e102d
|
- Create a MA and a MCA
- Do a payment , with `setup_future_usag:off_session`; the card would be saved
- Do a List PM for Customers, you'll have only one card , which has been set as default
```
Response
{
"customer_payment_methods": [
{
"payment_token": "token_FC8TupTKMEmhtM69dmYS",
"payment_method_id": "pm_Syvbg2Nb8mGdZC9oi4Sv",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "11",
"expiry_year": "2040",
"card_token": null,
"card_holder_name": "AKA",
"card_fingerprint": null,
"nick_name": "HELO",
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-06-11T10:14:09.587Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-06-11T10:14:09.587Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
- Delete the Payment Method, it'll be a success
```
Request
curl --location --request DELETE 'http://localhost:8080/payment_methods/:payment_method_id' \
--header 'Accept: application/json' \
--header 'api-key: dev_u3eBlxHY8BxUeQxxgvZGxKRXf7HEPaAw0sXmhjXjFFTmQ0pfyslENYRDajyrQnOf'
```
```
Response
{
"payment_method_id": "pm_50cS5VsVOhgbKQ63WReh",
"deleted": true
}
```
- List the Pm for Customer would be empty
```
Response
{
"customer_payment_methods": [],
"is_guest_customer": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4938
|
Bug: [FEATURE] Add support for gauge metrics and include IMC metrics
Add support for gauge metrics. Additionally also add a background thread, which will be spawned during application startup, that runs for every fixed interval (configurable) of time, collecting the metrics. For now this collector can collect the gauge metrics of `cache_entry_count` of all the cache types.
|
diff --git a/config/config.example.toml b/config/config.example.toml
index f4a6a66cd61..81516ee8b6b 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -112,6 +112,7 @@ otel_exporter_otlp_endpoint = "http://localhost:4317" # endpoint to send metrics
otel_exporter_otlp_timeout = 5000 # timeout (in milliseconds) for sending metrics and traces
use_xray_generator = false # Set this to true for AWS X-ray compatible traces
route_to_trace = ["*/confirm"]
+bg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread
# This section provides some secret values.
[secrets]
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index a097e1b66dc..9ab790b8ee8 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -139,6 +139,7 @@ otel_exporter_otlp_endpoint = "http://localhost:4317" # endpoint to send metrics
otel_exporter_otlp_timeout = 5000 # timeout (in milliseconds) for sending metrics and traces
use_xray_generator = false # Set this to true for AWS X-ray compatible traces
route_to_trace = ["*/confirm"]
+bg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread
[lock_settings]
delay_between_retries_in_milliseconds = 500 # Delay between retries in milliseconds
diff --git a/config/development.toml b/config/development.toml
index 2c6d67e7515..e475459573a 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -10,6 +10,7 @@ log_format = "default"
traces_enabled = false
metrics_enabled = false
use_xray_generator = false
+bg_metrics_collection_interval_in_secs = 15
# TODO: Update database credentials before running application
[master_database]
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 2a4fe369286..2cd93eade01 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -18,7 +18,8 @@ traces_enabled = false # Whether traces are
metrics_enabled = true # Whether metrics are enabled.
ignore_errors = false # Whether to ignore errors during traces or metrics pipeline setup.
otel_exporter_otlp_endpoint = "https://otel-collector:4317" # Endpoint to send metrics and traces to.
-use_xray_generator = false
+use_xray_generator = false # Set this to true for AWS X-ray compatible traces
+bg_metrics_collection_interval_in_secs = 15 # Interval for collecting the metrics in background thread
[master_database]
username = "db_user"
diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs
index 094f799cb27..8271e458b24 100644
--- a/crates/router/src/bin/router.rs
+++ b/crates/router/src/bin/router.rs
@@ -2,6 +2,7 @@ use router::{
configs::settings::{CmdLineConf, Settings},
core::errors::{ApplicationError, ApplicationResult},
logger,
+ routes::metrics,
};
#[tokio::main]
@@ -27,6 +28,11 @@ async fn main() -> ApplicationResult<()> {
logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log);
+ // Spawn a thread for collecting metrics at fixed intervals
+ metrics::bg_metrics_collector::spawn_metrics_collector(
+ &conf.log.telemetry.bg_metrics_collection_interval_in_secs,
+ );
+
#[allow(clippy::expect_used)]
let server = Box::pin(router::start_server(conf))
.await
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 1123be1a874..18014c6e193 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -1,4 +1,8 @@
-use router_env::{counter_metric, global_meter, histogram_metric, metrics_context};
+pub mod bg_metrics_collector;
+pub mod request;
+pub mod utils;
+
+use router_env::{counter_metric, gauge_metric, global_meter, histogram_metric, metrics_context};
metrics_context!(CONTEXT);
global_meter!(GLOBAL_METER, "ROUTER_API");
@@ -133,5 +137,5 @@ counter_metric!(ACCESS_TOKEN_CACHE_HIT, GLOBAL_METER);
// A counter to indicate the access token cache miss
counter_metric!(ACCESS_TOKEN_CACHE_MISS, GLOBAL_METER);
-pub mod request;
-pub mod utils;
+// Metrics for In-memory cache
+gauge_metric!(CACHE_ENTRY_COUNT, GLOBAL_METER);
diff --git a/crates/router/src/routes/metrics/bg_metrics_collector.rs b/crates/router/src/routes/metrics/bg_metrics_collector.rs
new file mode 100644
index 00000000000..65cb7a13e5e
--- /dev/null
+++ b/crates/router/src/routes/metrics/bg_metrics_collector.rs
@@ -0,0 +1,46 @@
+use storage_impl::redis::cache;
+
+const DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS: u16 = 15;
+
+macro_rules! gauge_metrics_for_imc {
+ ($($cache:ident),*) => {
+ $(
+ {
+ cache::$cache.run_pending_tasks().await;
+
+ super::CACHE_ENTRY_COUNT.observe(
+ &super::CONTEXT,
+ cache::$cache.get_entry_count(),
+ &[super::request::add_attributes(
+ "cache_type",
+ stringify!($cache),
+ )],
+ );
+ }
+ )*
+ };
+}
+
+pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: &Option<u16>) {
+ let metrics_collection_interval = metrics_collection_interval_in_secs
+ .unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS);
+
+ tokio::spawn(async move {
+ loop {
+ gauge_metrics_for_imc!(
+ CONFIG_CACHE,
+ ACCOUNTS_CACHE,
+ ROUTING_CACHE,
+ CGRAPH_CACHE,
+ PM_FILTERS_CGRAPH_CACHE,
+ DECISION_MANAGER_CACHE,
+ SURCHARGE_CACHE
+ );
+
+ tokio::time::sleep(std::time::Duration::from_secs(
+ metrics_collection_interval.into(),
+ ))
+ .await
+ }
+ });
+}
diff --git a/crates/router_env/src/logger/config.rs b/crates/router_env/src/logger/config.rs
index 09d285a8628..135451f266e 100644
--- a/crates/router_env/src/logger/config.rs
+++ b/crates/router_env/src/logger/config.rs
@@ -103,6 +103,8 @@ pub struct LogTelemetry {
pub use_xray_generator: bool,
/// Route Based Tracing
pub route_to_trace: Option<Vec<String>>,
+ /// Interval for collecting the metrics (such as gauge) in background thread
+ pub bg_metrics_collection_interval_in_secs: Option<u16>,
}
/// Telemetry / tracing.
diff --git a/crates/router_env/src/metrics.rs b/crates/router_env/src/metrics.rs
index e145caace00..e75cacaa3c9 100644
--- a/crates/router_env/src/metrics.rs
+++ b/crates/router_env/src/metrics.rs
@@ -101,3 +101,22 @@ macro_rules! histogram_metric_i64 {
> = once_cell::sync::Lazy::new(|| $meter.i64_histogram($description).init());
};
}
+
+/// Create a [`ObservableGauge`][ObservableGauge] metric with the specified name and an optional description,
+/// associated with the specified meter. Note that the meter must be to a valid [`Meter`][Meter].
+///
+/// [ObservableGauge]: opentelemetry::metrics::ObservableGauge
+/// [Meter]: opentelemetry::metrics::Meter
+#[macro_export]
+macro_rules! gauge_metric {
+ ($name:ident, $meter:ident) => {
+ pub(crate) static $name: once_cell::sync::Lazy<
+ $crate::opentelemetry::metrics::ObservableGauge<u64>,
+ > = once_cell::sync::Lazy::new(|| $meter.u64_observable_gauge(stringify!($name)).init());
+ };
+ ($name:ident, $meter:ident, description:literal) => {
+ pub(crate) static $name: once_cell::sync::Lazy<
+ $crate::opentelemetry::metrics::ObservableGauge<u64>,
+ > = once_cell::sync::Lazy::new(|| $meter.u64_observable_gauge($description).init());
+ };
+}
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index e4efab0da33..6ad96be2795 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -207,6 +207,16 @@ impl Cache {
pub async fn remove(&self, key: CacheKey) {
self.inner.invalidate::<String>(&key.into()).await;
}
+
+ /// Performs any pending maintenance operations needed by the cache.
+ pub async fn run_pending_tasks(&self) {
+ self.inner.run_pending_tasks().await;
+ }
+
+ /// Returns an approximate number of entries in this cache.
+ pub fn get_entry_count(&self) -> u64 {
+ self.inner.entry_count()
+ }
}
#[instrument(skip_all)]
|
2024-06-10T18:02:28Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR adds support for gauge metrics. Additionally the pr also adds a background thread, which will be spawned during application startup, that runs for every fixed interval (configurable) of time, collecting the metrics. For now this collector collects the gauge metrics of `cache_entry_count` of all the cache types.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Hit list payment methods for a merchant endpoint and check for `router_CACHE_ENTRY_COUNT` metric in grafana

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b705757be37a9803b964ef94d04c664c0f1e102d
|
Hit list payment methods for a merchant endpoint and check for `router_CACHE_ENTRY_COUNT` metric in grafana

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4934
|
Bug: [BUG] 5xx is thrown when invalid certificate and private key is configured in MCA for Netcetera
### Bug Description
5xx is thrown during authentication call when invalid certificate and private key is configured in MCA for Netcetera
### Expected Behavior
4xx should be thrown when invalid certificate or private keys are configured during MCA creation or updation.
### Actual Behavior
5xx is thrown during authentication call when invalid certificate and private key is configured in MCA for Netcetera
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Create a netcetera connector with invalid certificate or private key.
2. No validation error is thrown.
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index f9da9908d95..fc83573e21d 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -858,27 +858,7 @@ pub async fn create_payment_connector(
expected_format: "auth_type and api_key".to_string(),
})?;
- validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata).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 {} is invalid", field_name),
- }),
- 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(),
- }),
- }
- })?;
+ validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata)?;
let frm_configs = get_frm_config_as_secret(req.frm_configs);
@@ -1208,27 +1188,7 @@ pub async fn update_payment_connector(
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
- validate_auth_and_metadata_type(connector_enum, &auth, &metadata).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 {} is invalid", field_name),
- }),
- 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(),
- }),
- })?;
+ validate_auth_and_metadata_type(connector_enum, &auth, &metadata)?;
let (connector_status, disabled) =
validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?;
@@ -1817,7 +1777,35 @@ pub async fn connector_agnostic_mit_toggle(
))
}
-pub(crate) fn validate_auth_and_metadata_type(
+pub fn validate_auth_and_metadata_type(
+ connector_name: api_models::enums::Connector,
+ auth_type: &types::ConnectorAuthType,
+ connector_meta_data: &Option<pii::SecretSerdeValue>,
+) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
+ validate_connector_auth_type(auth_type)?;
+ validate_auth_and_metadata_type_with_connector(connector_name, auth_type, connector_meta_data)
+ .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 {} is invalid", field_name),
+ }),
+ 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(),
+ }),
+ })
+}
+
+pub(crate) fn validate_auth_and_metadata_type_with_connector(
connector_name: api_models::enums::Connector,
val: &types::ConnectorAuthType,
connector_meta_data: &Option<pii::SecretSerdeValue>,
@@ -2094,6 +2082,84 @@ pub(crate) fn validate_auth_and_metadata_type(
}
}
+pub(crate) fn validate_connector_auth_type(
+ auth_type: &types::ConnectorAuthType,
+) -> 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 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,
+ } => {
+ helpers::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(()),
+ }
+}
+
#[cfg(feature = "dummy_connector")]
pub async fn validate_dummy_connector_enabled(
state: &SessionState,
|
2024-06-10T11:13:12Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Wrote a validation function to validate ConnectorAuthType being passed during MCA create and update.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Manual.
1. SignatureKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_3589e3c3-2b53-4627-b0f9-8449b37a9c07/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "",
"key1": "",
"api_secret": ""
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
2. BodyKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "airwallex",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "",
"key1": ""
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
3. SignatureKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "checkout",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "",
"key1": "",
"api_secret": ""
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
4. MultiAuthKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "forte",
"connector_account_details": {
"auth_type": "MultiAuthKey",
"api_key": "",
"key1": "",
"api_secret": "",
"key2": ""
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
5. CurrencyAuthKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "cashtocode",
"connector_account_details": {
"auth_type": "CurrencyAuthKey",
"auth_key_map": {}
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
6. CertificateAuth
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "authentication_processor",
"business_country": "US",
"business_label": "default",
"connector_name": "netcetera",
"connector_account_details": {
"auth_type": "CertificateAuth",
"certificate": "",
"private_key": ""
},
"test_mode": true,
"disabled": false,
"metadata": {
"mcc": "5411",
"merchant_country_code": "840",
"merchant_name": "Dummy Merchant",
"endpoint_prefix": "flowbird",
"three_ds_requestor_name": "juspay-prev",
"three_ds_requestor_id": "juspay-prev",
"pull_mechanism_for_external_3ds_enabled": false
}
}'
```
All above curls contain invalid data in connector_account_details. So should be getting appropriate error message like below.
```
{
"error": {
"type": "invalid_request",
"message": "connector_account_details.certificate or connector_account_details.private_key contains invalid data. Expected format is a valid base64 encoded string of PEM encoded Certificate and Private Key",
"code": "IR_05"
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7085a46271791ca3f1c7b86afa7c8b199b93c0cd
|
Manual.
1. SignatureKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_3589e3c3-2b53-4627-b0f9-8449b37a9c07/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "",
"key1": "",
"api_secret": ""
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
2. BodyKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "airwallex",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "",
"key1": ""
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
3. SignatureKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "checkout",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "",
"key1": "",
"api_secret": ""
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
4. MultiAuthKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "forte",
"connector_account_details": {
"auth_type": "MultiAuthKey",
"api_key": "",
"key1": "",
"api_secret": "",
"key2": ""
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
5. CurrencyAuthKey
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "cashtocode",
"connector_account_details": {
"auth_type": "CurrencyAuthKey",
"auth_key_map": {}
},
"test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
6. CertificateAuth
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_f40f3037-ca64-462a-9a00-1e63b69abca0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "authentication_processor",
"business_country": "US",
"business_label": "default",
"connector_name": "netcetera",
"connector_account_details": {
"auth_type": "CertificateAuth",
"certificate": "",
"private_key": ""
},
"test_mode": true,
"disabled": false,
"metadata": {
"mcc": "5411",
"merchant_country_code": "840",
"merchant_name": "Dummy Merchant",
"endpoint_prefix": "flowbird",
"three_ds_requestor_name": "juspay-prev",
"three_ds_requestor_id": "juspay-prev",
"pull_mechanism_for_external_3ds_enabled": false
}
}'
```
All above curls contain invalid data in connector_account_details. So should be getting appropriate error message like below.
```
{
"error": {
"type": "invalid_request",
"message": "connector_account_details.certificate or connector_account_details.private_key contains invalid data. Expected format is a valid base64 encoded string of PEM encoded Certificate and Private Key",
"code": "IR_05"
}
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4929
|
Bug: [BUG] [CRYPTOPAY] Amount conversion to lower unit causing parsing error
### Bug Description
The conversion of a f64 base amount to i64 minor amount is causing parsing error in cryptopay. This needs to be fixed by using decimal type instead of f64.
### Expected Behavior
The conversion of a f64 base amount to i64 minor amount should not cause parsing error in cryptopay.
### Actual Behavior
The conversion of a f64 base amount to i64 minor amount is causing parsing error in cryptopay.
### Steps To Reproduce
Try doing a Cryptopay payment using amount 115.
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs
index f7d137eff20..a3e0844842c 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/router/src/connector/cryptopay.rs
@@ -1,13 +1,12 @@
pub mod transformers;
-use std::fmt::Debug;
-
use base64::Engine;
use common_utils::{
crypto::{self, GenerateDigest, SignMessage},
date_time,
ext_traits::ByteSliceExt,
request::RequestContent,
+ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hex::encode;
@@ -36,8 +35,18 @@ use crate::{
utils::BytesExt,
};
-#[derive(Debug, Clone)]
-pub struct Cryptopay;
+#[derive(Clone)]
+pub struct Cryptopay {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
+}
+
+impl Cryptopay {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMajorUnitForConnector,
+ }
+ }
+}
impl api::Payment for Cryptopay {}
impl api::PaymentSession for Cryptopay {}
@@ -123,7 +132,7 @@ where
(headers::DATE.to_string(), date.into()),
(
headers::CONTENT_TYPE.to_string(),
- Self.get_content_type().to_string().into(),
+ self.get_content_type().to_string().into(),
),
];
Ok(headers)
@@ -244,12 +253,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_router_data = cryptopay::CryptopayRouterData::try_from((
- &self.get_currency_unit(),
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
req.request.currency,
- req.request.amount,
- req,
- ))?;
+ )?;
+ let connector_router_data = cryptopay::CryptopayRouterData::from((amount, req));
let connector_req = cryptopay::CryptopayPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -288,13 +297,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+ let capture_amount_in_minor_units = match response.data.price_amount {
+ Some(ref amount) => Some(utils::convert_back(
+ self.amount_converter,
+ amount.clone(),
+ data.request.currency,
+ )?),
+ None => None,
+ };
types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
- data.request.currency,
+ capture_amount_in_minor_units,
))
}
@@ -375,13 +392,21 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
+ let capture_amount_in_minor_units = match response.data.price_amount {
+ Some(ref amount) => Some(utils::convert_back(
+ self.amount_converter,
+ amount.clone(),
+ data.request.currency,
+ )?),
+ None => None,
+ };
types::RouterData::foreign_try_from((
types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
- data.request.currency,
+ capture_amount_in_minor_units,
))
}
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index bcbc9a043a1..6c999727841 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -1,10 +1,11 @@
-use common_utils::pii;
-use error_stack::ResultExt;
+use common_utils::{
+ pii,
+ types::{MinorUnit, StringMajorUnit},
+};
use masking::Secret;
use reqwest::Url;
use serde::{Deserialize, Serialize};
-use super::utils as connector_utils;
use crate::{
connector::utils::{self, is_payment_failure, CryptoData, PaymentsAuthorizeRequestData},
consts,
@@ -15,31 +16,22 @@ use crate::{
#[derive(Debug, Serialize)]
pub struct CryptopayRouterData<T> {
- pub amount: String,
+ pub amount: StringMajorUnit,
pub router_data: T,
}
-impl<T> TryFrom<(&types::api::CurrencyUnit, enums::Currency, i64, T)> for CryptopayRouterData<T> {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- (currency_unit, currency, amount, item): (
- &types::api::CurrencyUnit,
- enums::Currency,
- i64,
- T,
- ),
- ) -> Result<Self, Self::Error> {
- let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
- Ok(Self {
+impl<T> From<(StringMajorUnit, T)> for CryptopayRouterData<T> {
+ fn from((amount, item): (StringMajorUnit, T)) -> Self {
+ Self {
amount,
router_data: item,
- })
+ }
}
}
#[derive(Default, Debug, Serialize)]
pub struct CryptopayPaymentsRequest {
- price_amount: String,
+ price_amount: StringMajorUnit,
price_currency: enums::Currency,
pay_currency: String,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -62,7 +54,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
domain::PaymentMethodData::Crypto(ref cryptodata) => {
let pay_currency = cryptodata.get_pay_currency()?;
Ok(Self {
- price_amount: item.amount.to_owned(),
+ price_amount: item.amount.clone(),
price_currency: item.router_data.request.currency,
pay_currency,
network: cryptodata.network.to_owned(),
@@ -140,20 +132,20 @@ impl From<CryptopayPaymentStatus> for enums::AttemptStatus {
#[derive(Debug, Serialize, Deserialize)]
pub struct CryptopayPaymentsResponse {
- data: CryptopayPaymentResponseData,
+ pub data: CryptopayPaymentResponseData,
}
impl<F, T>
ForeignTryFrom<(
types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
- diesel_models::enums::Currency,
+ Option<MinorUnit>,
)> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
- (item, currency): (
+ (item, amount_captured_in_minor_units): (
types::ResponseRouterData<F, CryptopayPaymentsResponse, T, types::PaymentsResponseData>,
- diesel_models::enums::Currency,
+ Option<MinorUnit>,
),
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.data.status.clone());
@@ -196,15 +188,9 @@ impl<F, T>
charge_id: None,
})
};
-
- match item.response.data.price_amount {
- Some(price_amount) => {
- let amount_captured = Some(
- connector_utils::to_currency_lower_unit(price_amount, currency)?
- .parse::<i64>()
- .change_context(errors::ConnectorError::ParsingFailed)?,
- );
-
+ match amount_captured_in_minor_units {
+ Some(minor_amount) => {
+ let amount_captured = Some(minor_amount.get_amount_as_i64());
Ok(Self {
status,
response,
@@ -243,9 +229,9 @@ pub struct CryptopayPaymentResponseData {
pub address: Option<Secret<String>>,
pub network: Option<String>,
pub uri: Option<String>,
- pub price_amount: Option<String>,
+ pub price_amount: Option<StringMajorUnit>,
pub price_currency: Option<String>,
- pub pay_amount: Option<String>,
+ pub pay_amount: Option<StringMajorUnit>,
pub pay_currency: Option<String>,
pub fee: Option<String>,
pub fee_currency: Option<String>,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index ee62b2ce551..498da04c6a2 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -329,7 +329,7 @@ impl ConnectorData {
enums::Connector::Cashtocode => Ok(Box::new(&connector::Cashtocode)),
enums::Connector::Checkout => Ok(Box::new(&connector::Checkout)),
enums::Connector::Coinbase => Ok(Box::new(&connector::Coinbase)),
- enums::Connector::Cryptopay => Ok(Box::new(&connector::Cryptopay)),
+ enums::Connector::Cryptopay => Ok(Box::new(connector::Cryptopay::new())),
enums::Connector::Cybersource => Ok(Box::new(&connector::Cybersource)),
enums::Connector::Dlocal => Ok(Box::new(&connector::Dlocal)),
#[cfg(feature = "dummy_connector")]
diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs
index 20c727756e7..988c704249a 100644
--- a/crates/router/tests/connectors/cryptopay.rs
+++ b/crates/router/tests/connectors/cryptopay.rs
@@ -13,7 +13,7 @@ impl utils::Connector for CryptopayTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Cryptopay;
api::ConnectorData {
- connector: Box::new(&Cryptopay),
+ connector: Box::new(Cryptopay::new()),
connector_name: types::Connector::Cryptopay,
get_token: api::GetToken::Connector,
merchant_connector_id: None,
|
2024-06-10T09:46:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The conversion of a f64 base amount to i64 minor amount is causing parsing error in cryptopay. This needs to be fixed by using decimal type instead of f64.
Also this Pr adds amount conversion framework to Cryptopay
Note: Cryptopay uses String Major Unit

### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4929
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
We need to test Cryptopay payments for various different amounts.
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 115,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
}
}
}'
```
Response:
```
{
"payment_id": "pay_6xbLnqQCFF6t23vtANeX",
"merchant_id": "merchant_1717926706",
"status": "requires_customer_action",
"amount": 115,
"net_amount": 115,
"amount_capturable": 115,
"amount_received": 115,
"connector": "cryptopay",
"client_secret": "pay_6xbLnqQCFF6t23vtANeX_secret_YIJnRmmD1hu2YhtJ3rpR",
"created": "2024-06-10T10:02:23.598Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_6xbLnqQCFF6t23vtANeX/merchant_1717926706/pay_6xbLnqQCFF6t23vtANeX_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "a31c8590-3fc7-495c-91f0-392c3aa65b26",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_6xbLnqQCFF6t23vtANeX_1",
"payment_link": null,
"profile_id": "pro_kr0RocqcrWsWzyfCMsbV",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_cbz96DuLRCEdzUAd4syf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-10T10:17:23.598Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-06-10T10:02:24.390Z",
"charges": null,
"frm_metadata": null
}
```
Note: Specifically test for amount 115.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7085a46271791ca3f1c7b86afa7c8b199b93c0cd
|
We need to test Cryptopay payments for various different amounts.
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 115,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "litecoin"
}
}
}'
```
Response:
```
{
"payment_id": "pay_6xbLnqQCFF6t23vtANeX",
"merchant_id": "merchant_1717926706",
"status": "requires_customer_action",
"amount": 115,
"net_amount": 115,
"amount_capturable": 115,
"amount_received": 115,
"connector": "cryptopay",
"client_secret": "pay_6xbLnqQCFF6t23vtANeX_secret_YIJnRmmD1hu2YhtJ3rpR",
"created": "2024-06-10T10:02:23.598Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_6xbLnqQCFF6t23vtANeX/merchant_1717926706/pay_6xbLnqQCFF6t23vtANeX_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "a31c8590-3fc7-495c-91f0-392c3aa65b26",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_6xbLnqQCFF6t23vtANeX_1",
"payment_link": null,
"profile_id": "pro_kr0RocqcrWsWzyfCMsbV",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_cbz96DuLRCEdzUAd4syf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-10T10:17:23.598Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-06-10T10:02:24.390Z",
"charges": null,
"frm_metadata": null
}
```
Note: Specifically test for amount 115.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4945
|
Bug: [REFACTOR] Move trait ConnectorIntegration to crate hyperswitch_interfaces
### Feature Description
The trait ConnectorIntegration needs to be moved to crate hyperswitch_interfaces from router. This is required to move connector code out from crate router.
### Possible Implementation
The trait ConnectorIntegration along with it's dependent types needs to be moved to crate hyperswitch_interfaces.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/Cargo.lock b/Cargo.lock
index 77f9b33ddc4..6ea7937eca6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3695,11 +3695,22 @@ name = "hyperswitch_interfaces"
version = "0.1.0"
dependencies = [
"async-trait",
+ "bytes 1.6.0",
"common_utils",
"dyn-clone",
+ "http 0.2.12",
+ "hyperswitch_domain_models",
"masking",
+ "mime",
+ "once_cell",
+ "reqwest",
+ "router_derive",
+ "router_env",
"serde",
+ "serde_json",
+ "storage_impl",
"thiserror",
+ "time",
]
[[package]]
diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml
index 034e0a67d92..95b3b98af05 100644
--- a/crates/hyperswitch_interfaces/Cargo.toml
+++ b/crates/hyperswitch_interfaces/Cargo.toml
@@ -6,12 +6,28 @@ rust-version.workspace = true
readme = "README.md"
license.workspace = true
+[features]
+default = ["dummy_connector", "payouts"]
+dummy_connector = []
+payouts = []
+
[dependencies]
async-trait = "0.1.79"
+bytes = "1.6.0"
dyn-clone = "1.0.17"
+http = "0.2.12"
+mime = "0.3.17"
+once_cell = "1.19.0"
+reqwest = "0.11.27"
serde = { version = "1.0.197", features = ["derive"] }
+serde_json = "1.0.115"
thiserror = "1.0.58"
+time = "0.3.35"
# First party crates
common_utils = { version = "0.1.0", path = "../common_utils" }
+hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
masking = { version = "0.1.0", path = "../masking" }
+router_derive = { version = "0.1.0", path = "../router_derive" }
+router_env = { version = "0.1.0", path = "../router_env" }
+storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
diff --git a/crates/hyperswitch_interfaces/src/api.rs b/crates/hyperswitch_interfaces/src/api.rs
new file mode 100644
index 00000000000..63cbc6dabf8
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/api.rs
@@ -0,0 +1,183 @@
+//! API interface
+
+use common_utils::{
+ errors::CustomResult,
+ request::{Method, Request, RequestContent},
+};
+use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData};
+use masking::Maskable;
+use serde_json::json;
+
+use crate::{
+ configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, metrics, types,
+};
+
+/// type BoxedConnectorIntegration
+pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
+ Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>;
+
+/// trait ConnectorIntegrationAny
+pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static {
+ /// fn get_connector_integration
+ fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>;
+}
+
+impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S
+where
+ S: ConnectorIntegration<T, Req, Resp> + Send + Sync,
+{
+ fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> {
+ Box::new(self)
+ }
+}
+
+/// trait ConnectorIntegration
+pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync {
+ /// fn get_headers
+ fn get_headers(
+ &self,
+ _req: &RouterData<T, Req, Resp>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
+ Ok(vec![])
+ }
+
+ /// fn get_content_type
+ fn get_content_type(&self) -> &'static str {
+ mime::APPLICATION_JSON.essence_str()
+ }
+
+ /// primarily used when creating signature based on request method of payment flow
+ fn get_http_method(&self) -> Method {
+ Method::Post
+ }
+
+ /// fn get_url
+ fn get_url(
+ &self,
+ _req: &RouterData<T, Req, Resp>,
+ _connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(String::new())
+ }
+
+ /// fn get_request_body
+ fn get_request_body(
+ &self,
+ _req: &RouterData<T, Req, Resp>,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ Ok(RequestContent::Json(Box::new(json!(r#"{}"#))))
+ }
+
+ /// fn get_request_form_data
+ fn get_request_form_data(
+ &self,
+ _req: &RouterData<T, Req, Resp>,
+ ) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> {
+ Ok(None)
+ }
+
+ /// fn build_request
+ fn build_request(
+ &self,
+ req: &RouterData<T, Req, Resp>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ metrics::UNIMPLEMENTED_FLOW.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::add_attributes("connector", req.connector.clone())],
+ );
+ Ok(None)
+ }
+
+ /// fn handle_response
+ fn handle_response(
+ &self,
+ data: &RouterData<T, Req, Resp>,
+ event_builder: Option<&mut ConnectorEvent>,
+ _res: types::Response,
+ ) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError>
+ where
+ T: Clone,
+ Req: Clone,
+ Resp: Clone,
+ {
+ event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"})));
+ Ok(data.clone())
+ }
+
+ /// fn get_error_response
+ fn get_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
+ Ok(ErrorResponse::get_not_implemented())
+ }
+
+ /// fn get_5xx_error_response
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
+ let error_message = match res.status_code {
+ 500 => "internal_server_error",
+ 501 => "not_implemented",
+ 502 => "bad_gateway",
+ 503 => "service_unavailable",
+ 504 => "gateway_timeout",
+ 505 => "http_version_not_supported",
+ 506 => "variant_also_negotiates",
+ 507 => "insufficient_storage",
+ 508 => "loop_detected",
+ 510 => "not_extended",
+ 511 => "network_authentication_required",
+ _ => "unknown_error",
+ };
+ Ok(ErrorResponse {
+ code: res.status_code.to_string(),
+ message: error_message.to_string(),
+ reason: String::from_utf8(res.response.to_vec()).ok(),
+ status_code: res.status_code,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+
+ /// whenever capture sync is implemented at the connector side, this method should be overridden
+ fn get_multiple_capture_sync_method(
+ &self,
+ ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into())
+ }
+
+ /// fn get_certificate
+ fn get_certificate(
+ &self,
+ _req: &RouterData<T, Req, Resp>,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ Ok(None)
+ }
+
+ /// fn get_certificate_key
+ fn get_certificate_key(
+ &self,
+ _req: &RouterData<T, Req, Resp>,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ Ok(None)
+ }
+}
+
+/// Sync Methods for multiple captures
+#[derive(Debug)]
+pub enum CaptureSyncMethod {
+ /// For syncing multiple captures individually
+ Individual,
+ /// For syncing multiple captures together
+ Bulk,
+}
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
new file mode 100644
index 00000000000..8f3b5600f08
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -0,0 +1,132 @@
+//! Configs interface
+use router_derive;
+use serde::Deserialize;
+use storage_impl::errors::ApplicationError;
+
+// struct Connectors
+#[allow(missing_docs, missing_debug_implementations)]
+#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
+#[serde(default)]
+pub struct Connectors {
+ pub aci: ConnectorParams,
+ #[cfg(feature = "payouts")]
+ pub adyen: ConnectorParamsWithSecondaryBaseUrl,
+ pub adyenplatform: ConnectorParams,
+ #[cfg(not(feature = "payouts"))]
+ pub adyen: ConnectorParams,
+ pub airwallex: ConnectorParams,
+ pub applepay: ConnectorParams,
+ pub authorizedotnet: ConnectorParams,
+ pub bambora: ConnectorParams,
+ pub bankofamerica: ConnectorParams,
+ pub billwerk: ConnectorParams,
+ pub bitpay: ConnectorParams,
+ pub bluesnap: ConnectorParamsWithSecondaryBaseUrl,
+ pub boku: ConnectorParams,
+ pub braintree: ConnectorParams,
+ pub cashtocode: ConnectorParams,
+ pub checkout: ConnectorParams,
+ pub coinbase: ConnectorParams,
+ pub cryptopay: ConnectorParams,
+ pub cybersource: ConnectorParams,
+ pub datatrans: ConnectorParams,
+ pub dlocal: ConnectorParams,
+ #[cfg(feature = "dummy_connector")]
+ pub dummyconnector: ConnectorParams,
+ pub ebanx: ConnectorParams,
+ pub fiserv: ConnectorParams,
+ pub forte: ConnectorParams,
+ pub globalpay: ConnectorParams,
+ pub globepay: ConnectorParams,
+ pub gocardless: ConnectorParams,
+ pub gpayments: ConnectorParams,
+ pub helcim: ConnectorParams,
+ pub iatapay: ConnectorParams,
+ pub klarna: ConnectorParams,
+ pub mifinity: ConnectorParams,
+ pub mollie: ConnectorParams,
+ pub multisafepay: ConnectorParams,
+ pub netcetera: ConnectorParams,
+ pub nexinets: ConnectorParams,
+ pub nmi: ConnectorParams,
+ pub noon: ConnectorParamsWithModeType,
+ pub nuvei: ConnectorParams,
+ pub opayo: ConnectorParams,
+ pub opennode: ConnectorParams,
+ pub payeezy: ConnectorParams,
+ pub payme: ConnectorParams,
+ pub payone: ConnectorParams,
+ pub paypal: ConnectorParams,
+ pub payu: ConnectorParams,
+ pub placetopay: ConnectorParams,
+ pub powertranz: ConnectorParams,
+ pub prophetpay: ConnectorParams,
+ pub rapyd: ConnectorParams,
+ pub riskified: ConnectorParams,
+ pub shift4: ConnectorParams,
+ pub signifyd: ConnectorParams,
+ pub square: ConnectorParams,
+ pub stax: ConnectorParams,
+ pub stripe: ConnectorParamsWithFileUploadUrl,
+ pub threedsecureio: ConnectorParams,
+ pub trustpay: ConnectorParamsWithMoreUrls,
+ pub tsys: ConnectorParams,
+ pub volt: ConnectorParams,
+ pub wise: ConnectorParams,
+ pub worldline: ConnectorParams,
+ pub worldpay: ConnectorParams,
+ pub zen: ConnectorParams,
+ pub zsl: ConnectorParams,
+}
+
+/// struct ConnectorParams
+#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
+#[serde(default)]
+pub struct ConnectorParams {
+ /// base url
+ pub base_url: String,
+ /// secondary base url
+ pub secondary_base_url: Option<String>,
+}
+
+/// struct ConnectorParamsWithModeType
+#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
+#[serde(default)]
+pub struct ConnectorParamsWithModeType {
+ /// base url
+ pub base_url: String,
+ /// secondary base url
+ pub secondary_base_url: Option<String>,
+ /// Can take values like Test or Live for Noon
+ pub key_mode: String,
+}
+
+/// struct ConnectorParamsWithMoreUrls
+#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
+#[serde(default)]
+pub struct ConnectorParamsWithMoreUrls {
+ /// base url
+ pub base_url: String,
+ /// base url for bank redirects
+ pub base_url_bank_redirects: String,
+}
+
+/// struct ConnectorParamsWithFileUploadUrl
+#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
+#[serde(default)]
+pub struct ConnectorParamsWithFileUploadUrl {
+ /// base url
+ pub base_url: String,
+ /// base url for file upload
+ pub base_url_file_upload: String,
+}
+
+/// struct ConnectorParamsWithSecondaryBaseUrl
+#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
+#[serde(default)]
+pub struct ConnectorParamsWithSecondaryBaseUrl {
+ /// base url
+ pub base_url: String,
+ /// secondary base url
+ pub secondary_base_url: String,
+}
diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs
new file mode 100644
index 00000000000..e36707af6b0
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/errors.rs
@@ -0,0 +1,149 @@
+//! Errors interface
+
+use common_utils::errors::ErrorSwitch;
+use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
+
+/// Connector Errors
+#[allow(missing_docs, missing_debug_implementations)]
+#[derive(Debug, thiserror::Error, PartialEq)]
+pub enum ConnectorError {
+ #[error("Error while obtaining URL for the integration")]
+ FailedToObtainIntegrationUrl,
+ #[error("Failed to encode connector request")]
+ RequestEncodingFailed,
+ #[error("Request encoding failed : {0}")]
+ RequestEncodingFailedWithReason(String),
+ #[error("Parsing failed")]
+ ParsingFailed,
+ #[error("Failed to deserialize connector response")]
+ ResponseDeserializationFailed,
+ #[error("Failed to execute a processing step: {0:?}")]
+ ProcessingStepFailed(Option<bytes::Bytes>),
+ #[error("The connector returned an unexpected response: {0:?}")]
+ UnexpectedResponseError(bytes::Bytes),
+ #[error("Failed to parse custom routing rules from merchant account")]
+ RoutingRulesParsingError,
+ #[error("Failed to obtain preferred connector from merchant account")]
+ FailedToObtainPreferredConnector,
+ #[error("An invalid connector name was provided")]
+ InvalidConnectorName,
+ #[error("An invalid Wallet was used")]
+ InvalidWallet,
+ #[error("Failed to handle connector response")]
+ ResponseHandlingFailed,
+ #[error("Missing required field: {field_name}")]
+ MissingRequiredField { field_name: &'static str },
+ #[error("Missing required fields: {field_names:?}")]
+ MissingRequiredFields { field_names: Vec<&'static str> },
+ #[error("Failed to obtain authentication type")]
+ FailedToObtainAuthType,
+ #[error("Failed to obtain certificate")]
+ FailedToObtainCertificate,
+ #[error("Connector meta data not found")]
+ NoConnectorMetaData,
+ #[error("Failed to obtain certificate key")]
+ FailedToObtainCertificateKey,
+ #[error("This step has not been implemented for: {0}")]
+ NotImplemented(String),
+ #[error("{message} is not supported by {connector}")]
+ NotSupported {
+ message: String,
+ connector: &'static str,
+ },
+ #[error("{flow} flow not supported by {connector} connector")]
+ FlowNotSupported { flow: String, connector: String },
+ #[error("Capture method not supported")]
+ CaptureMethodNotSupported,
+ #[error("Missing connector mandate ID")]
+ MissingConnectorMandateID,
+ #[error("Missing connector transaction ID")]
+ MissingConnectorTransactionID,
+ #[error("Missing connector refund ID")]
+ MissingConnectorRefundID,
+ #[error("Missing apple pay tokenization data")]
+ MissingApplePayTokenData,
+ #[error("Webhooks not implemented for this connector")]
+ WebhooksNotImplemented,
+ #[error("Failed to decode webhook event body")]
+ WebhookBodyDecodingFailed,
+ #[error("Signature not found for incoming webhook")]
+ WebhookSignatureNotFound,
+ #[error("Failed to verify webhook source")]
+ WebhookSourceVerificationFailed,
+ #[error("Could not find merchant secret in DB for incoming webhook source verification")]
+ WebhookVerificationSecretNotFound,
+ #[error("Merchant secret found for incoming webhook source verification is invalid")]
+ WebhookVerificationSecretInvalid,
+ #[error("Incoming webhook object reference ID not found")]
+ WebhookReferenceIdNotFound,
+ #[error("Incoming webhook event type not found")]
+ WebhookEventTypeNotFound,
+ #[error("Incoming webhook event resource object not found")]
+ WebhookResourceObjectNotFound,
+ #[error("Could not respond to the incoming webhook event")]
+ WebhookResponseEncodingFailed,
+ #[error("Invalid Date/time format")]
+ InvalidDateFormat,
+ #[error("Date Formatting Failed")]
+ DateFormattingFailed,
+ #[error("Invalid Data format")]
+ InvalidDataFormat { field_name: &'static str },
+ #[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")]
+ MismatchedPaymentData,
+ #[error("Failed to parse {wallet_name} wallet token")]
+ InvalidWalletToken { wallet_name: String },
+ #[error("Missing Connector Related Transaction ID")]
+ MissingConnectorRelatedTransactionID { id: String },
+ #[error("File Validation failed")]
+ FileValidationFailed { reason: String },
+ #[error("Missing 3DS redirection payload: {field_name}")]
+ MissingConnectorRedirectionPayload { field_name: &'static str },
+ #[error("Failed at connector's end with code '{code}'")]
+ FailedAtConnector { message: String, code: String },
+ #[error("Payment Method Type not found")]
+ MissingPaymentMethodType,
+ #[error("Balance in the payment method is low")]
+ InSufficientBalanceInPaymentMethod,
+ #[error("Server responded with Request Timeout")]
+ RequestTimeoutReceived,
+ #[error("The given currency method is not configured with the given connector")]
+ CurrencyNotSupported {
+ message: String,
+ connector: &'static str,
+ },
+ #[error("Invalid Configuration")]
+ InvalidConnectorConfig { config: &'static str },
+ #[error("Failed to convert amount to required type")]
+ AmountConversionFailed,
+}
+
+impl ConnectorError {
+ /// fn is_connector_timeout
+ pub fn is_connector_timeout(&self) -> bool {
+ self == &Self::RequestTimeoutReceived
+ }
+}
+
+impl ErrorSwitch<ConnectorError> for common_utils::errors::ParsingError {
+ fn switch(&self) -> ConnectorError {
+ ConnectorError::ParsingFailed
+ }
+}
+
+impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
+ fn switch(&self) -> ApiErrorResponse {
+ match self {
+ Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed,
+ Self::WebhookSignatureNotFound
+ | Self::WebhookReferenceIdNotFound
+ | Self::WebhookResourceObjectNotFound
+ | Self::WebhookBodyDecodingFailed
+ | Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest,
+ Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity,
+ Self::WebhookVerificationSecretInvalid => {
+ ApiErrorResponse::WebhookInvalidMerchantSecret
+ }
+ _ => ApiErrorResponse::InternalServerError,
+ }
+ }
+}
diff --git a/crates/hyperswitch_interfaces/src/events.rs b/crates/hyperswitch_interfaces/src/events.rs
new file mode 100644
index 00000000000..3dcb7519545
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/events.rs
@@ -0,0 +1,3 @@
+//! Events interface
+
+pub mod connector_api_logs;
diff --git a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
new file mode 100644
index 00000000000..79b172e9ea7
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
@@ -0,0 +1,96 @@
+//! Connector API logs interface
+
+use common_utils::request::Method;
+use router_env::tracing_actix_web::RequestId;
+use serde::Serialize;
+use serde_json::json;
+use time::OffsetDateTime;
+
+/// struct ConnectorEvent
+#[derive(Debug, Serialize)]
+pub struct ConnectorEvent {
+ connector_name: String,
+ flow: String,
+ request: String,
+ masked_response: Option<String>,
+ error: Option<String>,
+ url: String,
+ method: String,
+ payment_id: String,
+ merchant_id: String,
+ created_at: i128,
+ /// Connector Event Request ID
+ pub request_id: String,
+ latency: u128,
+ refund_id: Option<String>,
+ dispute_id: Option<String>,
+ status_code: u16,
+}
+
+impl ConnectorEvent {
+ /// fn new ConnectorEvent
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ connector_name: String,
+ flow: &str,
+ request: serde_json::Value,
+ url: String,
+ method: Method,
+ payment_id: String,
+ merchant_id: String,
+ request_id: Option<&RequestId>,
+ latency: u128,
+ refund_id: Option<String>,
+ dispute_id: Option<String>,
+ status_code: u16,
+ ) -> Self {
+ Self {
+ connector_name,
+ flow: flow
+ .rsplit_once("::")
+ .map(|(_, s)| s)
+ .unwrap_or(flow)
+ .to_string(),
+ request: request.to_string(),
+ masked_response: None,
+ error: None,
+ url,
+ method: method.to_string(),
+ payment_id,
+ merchant_id,
+ created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
+ request_id: request_id
+ .map(|i| i.as_hyphenated().to_string())
+ .unwrap_or("NO_REQUEST_ID".to_string()),
+ latency,
+ refund_id,
+ dispute_id,
+ status_code,
+ }
+ }
+
+ /// fn set_response_body
+ pub fn set_response_body<T: Serialize>(&mut self, response: &T) {
+ match masking::masked_serialize(response) {
+ Ok(masked) => {
+ self.masked_response = Some(masked.to_string());
+ }
+ Err(er) => self.set_error(json!({"error": er.to_string()})),
+ }
+ }
+
+ /// fn set_error_response_body
+ pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) {
+ match masking::masked_serialize(response) {
+ Ok(masked) => {
+ self.error = Some(masked.to_string());
+ }
+ Err(er) => self.set_error(json!({"error": er.to_string()})),
+ }
+ }
+
+ /// fn set_error
+ pub fn set_error(&mut self, error: serde_json::Value) {
+ self.error = Some(error.to_string());
+ }
+}
diff --git a/crates/hyperswitch_interfaces/src/lib.rs b/crates/hyperswitch_interfaces/src/lib.rs
index 3f7b8d41c3e..7d3b319df83 100644
--- a/crates/hyperswitch_interfaces/src/lib.rs
+++ b/crates/hyperswitch_interfaces/src/lib.rs
@@ -1,7 +1,11 @@
//! Hyperswitch interface
-
#![warn(missing_docs, missing_debug_implementations)]
-pub mod secrets_interface;
-
+pub mod api;
+pub mod configs;
pub mod encryption_interface;
+pub mod errors;
+pub mod events;
+pub mod metrics;
+pub mod secrets_interface;
+pub mod types;
diff --git a/crates/hyperswitch_interfaces/src/metrics.rs b/crates/hyperswitch_interfaces/src/metrics.rs
new file mode 100644
index 00000000000..a03215a175d
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/metrics.rs
@@ -0,0 +1,16 @@
+//! Metrics interface
+
+use router_env::{counter_metric, global_meter, metrics_context, opentelemetry};
+
+metrics_context!(CONTEXT);
+global_meter!(GLOBAL_METER, "ROUTER_API");
+
+counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER);
+
+/// fn add attributes
+pub fn add_attributes<T: Into<opentelemetry::Value>>(
+ key: &'static str,
+ value: T,
+) -> opentelemetry::KeyValue {
+ opentelemetry::KeyValue::new(key, value)
+}
diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs
new file mode 100644
index 00000000000..2f0c5c2fbda
--- /dev/null
+++ b/crates/hyperswitch_interfaces/src/types.rs
@@ -0,0 +1,12 @@
+//! Types interface
+
+/// struct Response
+#[derive(Clone, Debug)]
+pub struct Response {
+ /// headers
+ pub headers: Option<http::HeaderMap>,
+ /// response
+ pub response: bytes::Bytes,
+ /// status code
+ pub status_code: u16,
+}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index ac8689d21b4..06cff596312 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -17,6 +17,7 @@ use external_services::{
secrets_management::SecretsManagementConfig,
},
};
+pub use hyperswitch_interfaces::configs::Connectors;
use hyperswitch_interfaces::secrets_interface::secret_state::{
RawSecret, SecretState, SecretStateContainer, SecuredSecret,
};
@@ -544,117 +545,6 @@ pub struct SupportedConnectors {
pub wallets: Vec<String>,
}
-#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
-#[serde(default)]
-pub struct Connectors {
- pub aci: ConnectorParams,
- #[cfg(feature = "payouts")]
- pub adyen: ConnectorParamsWithSecondaryBaseUrl,
- pub adyenplatform: ConnectorParams,
- #[cfg(not(feature = "payouts"))]
- pub adyen: ConnectorParams,
- pub airwallex: ConnectorParams,
- pub applepay: ConnectorParams,
- pub authorizedotnet: ConnectorParams,
- pub bambora: ConnectorParams,
- pub bankofamerica: ConnectorParams,
- pub billwerk: ConnectorParams,
- pub bitpay: ConnectorParams,
- pub bluesnap: ConnectorParamsWithSecondaryBaseUrl,
- pub boku: ConnectorParams,
- pub braintree: ConnectorParams,
- pub cashtocode: ConnectorParams,
- pub checkout: ConnectorParams,
- pub coinbase: ConnectorParams,
- pub cryptopay: ConnectorParams,
- pub cybersource: ConnectorParams,
- pub datatrans: ConnectorParams,
- pub dlocal: ConnectorParams,
- #[cfg(feature = "dummy_connector")]
- pub dummyconnector: ConnectorParams,
- pub ebanx: ConnectorParams,
- pub fiserv: ConnectorParams,
- pub forte: ConnectorParams,
- pub globalpay: ConnectorParams,
- pub globepay: ConnectorParams,
- pub gocardless: ConnectorParams,
- pub gpayments: ConnectorParams,
- pub helcim: ConnectorParams,
- pub iatapay: ConnectorParams,
- pub klarna: ConnectorParams,
- pub mifinity: ConnectorParams,
- pub mollie: ConnectorParams,
- pub multisafepay: ConnectorParams,
- pub netcetera: ConnectorParams,
- pub nexinets: ConnectorParams,
- pub nmi: ConnectorParams,
- pub noon: ConnectorParamsWithModeType,
- pub nuvei: ConnectorParams,
- pub opayo: ConnectorParams,
- pub opennode: ConnectorParams,
- pub payeezy: ConnectorParams,
- pub payme: ConnectorParams,
- pub payone: ConnectorParams,
- pub paypal: ConnectorParams,
- pub payu: ConnectorParams,
- pub placetopay: ConnectorParams,
- pub powertranz: ConnectorParams,
- pub prophetpay: ConnectorParams,
- pub rapyd: ConnectorParams,
- pub riskified: ConnectorParams,
- pub shift4: ConnectorParams,
- pub signifyd: ConnectorParams,
- pub square: ConnectorParams,
- pub stax: ConnectorParams,
- pub stripe: ConnectorParamsWithFileUploadUrl,
- pub threedsecureio: ConnectorParams,
- pub trustpay: ConnectorParamsWithMoreUrls,
- pub tsys: ConnectorParams,
- pub volt: ConnectorParams,
- pub wise: ConnectorParams,
- pub worldline: ConnectorParams,
- pub worldpay: ConnectorParams,
- pub zen: ConnectorParams,
- pub zsl: ConnectorParams,
-}
-
-#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
-#[serde(default)]
-pub struct ConnectorParams {
- pub base_url: String,
- pub secondary_base_url: Option<String>,
-}
-
-#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
-#[serde(default)]
-pub struct ConnectorParamsWithModeType {
- pub base_url: String,
- pub secondary_base_url: Option<String>,
- /// Can take values like Test or Live for Noon
- pub key_mode: String,
-}
-
-#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
-#[serde(default)]
-pub struct ConnectorParamsWithMoreUrls {
- pub base_url: String,
- pub base_url_bank_redirects: String,
-}
-
-#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
-#[serde(default)]
-pub struct ConnectorParamsWithFileUploadUrl {
- pub base_url: String,
- pub base_url_file_upload: String,
-}
-
-#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
-#[serde(default)]
-pub struct ConnectorParamsWithSecondaryBaseUrl {
- pub base_url: String,
- pub secondary_base_url: String,
-}
-
#[cfg(feature = "kv_store")]
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index e1ef11265c0..d6d376fa0ef 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -1837,12 +1837,6 @@ where
json.parse_value(std::any::type_name::<T>()).switch()
}
-impl common_utils::errors::ErrorSwitch<errors::ConnectorError> for errors::ParsingError {
- fn switch(&self) -> errors::ConnectorError {
- errors::ConnectorError::ParsingFailed
- }
-}
-
pub fn base64_decode(data: String) -> Result<Vec<u8>, Error> {
consts::BASE64_ENGINE
.decode(data)
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 0e9e4022798..83fa2143648 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -14,6 +14,7 @@ pub use hyperswitch_domain_models::errors::{
api_error_response::{ApiErrorResponse, ErrorType, NotImplementedMessage},
StorageError as DataStorageError,
};
+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;
@@ -111,118 +112,6 @@ pub fn http_not_implemented() -> actix_web::HttpResponse<BoxBody> {
.error_response()
}
-#[derive(Debug, thiserror::Error, PartialEq)]
-pub enum ConnectorError {
- #[error("Error while obtaining URL for the integration")]
- FailedToObtainIntegrationUrl,
- #[error("Failed to encode connector request")]
- RequestEncodingFailed,
- #[error("Request encoding failed : {0}")]
- RequestEncodingFailedWithReason(String),
- #[error("Parsing failed")]
- ParsingFailed,
- #[error("Failed to deserialize connector response")]
- ResponseDeserializationFailed,
- #[error("Failed to execute a processing step: {0:?}")]
- ProcessingStepFailed(Option<bytes::Bytes>),
- #[error("The connector returned an unexpected response: {0:?}")]
- UnexpectedResponseError(bytes::Bytes),
- #[error("Failed to parse custom routing rules from merchant account")]
- RoutingRulesParsingError,
- #[error("Failed to obtain preferred connector from merchant account")]
- FailedToObtainPreferredConnector,
- #[error("An invalid connector name was provided")]
- InvalidConnectorName,
- #[error("An invalid Wallet was used")]
- InvalidWallet,
- #[error("Failed to handle connector response")]
- ResponseHandlingFailed,
- #[error("Missing required field: {field_name}")]
- MissingRequiredField { field_name: &'static str },
- #[error("Missing required fields: {field_names:?}")]
- MissingRequiredFields { field_names: Vec<&'static str> },
- #[error("Failed to obtain authentication type")]
- FailedToObtainAuthType,
- #[error("Failed to obtain certificate")]
- FailedToObtainCertificate,
- #[error("Connector meta data not found")]
- NoConnectorMetaData,
- #[error("Failed to obtain certificate key")]
- FailedToObtainCertificateKey,
- #[error("This step has not been implemented for: {0}")]
- NotImplemented(String),
- #[error("{message} is not supported by {connector}")]
- NotSupported {
- message: String,
- connector: &'static str,
- },
- #[error("{flow} flow not supported by {connector} connector")]
- FlowNotSupported { flow: String, connector: String },
- #[error("Capture method not supported")]
- CaptureMethodNotSupported,
- #[error("Missing connector mandate ID")]
- MissingConnectorMandateID,
- #[error("Missing connector transaction ID")]
- MissingConnectorTransactionID,
- #[error("Missing connector refund ID")]
- MissingConnectorRefundID,
- #[error("Missing apple pay tokenization data")]
- MissingApplePayTokenData,
- #[error("Webhooks not implemented for this connector")]
- WebhooksNotImplemented,
- #[error("Failed to decode webhook event body")]
- WebhookBodyDecodingFailed,
- #[error("Signature not found for incoming webhook")]
- WebhookSignatureNotFound,
- #[error("Failed to verify webhook source")]
- WebhookSourceVerificationFailed,
- #[error("Could not find merchant secret in DB for incoming webhook source verification")]
- WebhookVerificationSecretNotFound,
- #[error("Merchant secret found for incoming webhook source verification is invalid")]
- WebhookVerificationSecretInvalid,
- #[error("Incoming webhook object reference ID not found")]
- WebhookReferenceIdNotFound,
- #[error("Incoming webhook event type not found")]
- WebhookEventTypeNotFound,
- #[error("Incoming webhook event resource object not found")]
- WebhookResourceObjectNotFound,
- #[error("Could not respond to the incoming webhook event")]
- WebhookResponseEncodingFailed,
- #[error("Invalid Date/time format")]
- InvalidDateFormat,
- #[error("Date Formatting Failed")]
- DateFormattingFailed,
- #[error("Invalid Data format")]
- InvalidDataFormat { field_name: &'static str },
- #[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")]
- MismatchedPaymentData,
- #[error("Failed to parse {wallet_name} wallet token")]
- InvalidWalletToken { wallet_name: String },
- #[error("Missing Connector Related Transaction ID")]
- MissingConnectorRelatedTransactionID { id: String },
- #[error("File Validation failed")]
- FileValidationFailed { reason: String },
- #[error("Missing 3DS redirection payload: {field_name}")]
- MissingConnectorRedirectionPayload { field_name: &'static str },
- #[error("Failed at connector's end with code '{code}'")]
- FailedAtConnector { message: String, code: String },
- #[error("Payment Method Type not found")]
- MissingPaymentMethodType,
- #[error("Balance in the payment method is low")]
- InSufficientBalanceInPaymentMethod,
- #[error("Server responded with Request Timeout")]
- RequestTimeoutReceived,
- #[error("The given currency method is not configured with the given connector")]
- CurrencyNotSupported {
- message: String,
- connector: &'static str,
- },
- #[error("Invalid Configuration")]
- InvalidConnectorConfig { config: &'static str },
- #[error("Failed to convert amount to required type")]
- AmountConversionFailed,
-}
-
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckOutGoing {
#[error("Outgoing call failed with error: {message}")]
@@ -335,12 +224,6 @@ pub enum ApplePayDecryptionError {
DerivingSharedSecretKeyFailed,
}
-impl ConnectorError {
- pub fn is_connector_timeout(&self) -> bool {
- self == &Self::RequestTimeoutReceived
- }
-}
-
#[cfg(feature = "detailed_errors")]
pub mod error_stack_parsing {
diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs
index df529f81803..f5e90771c14 100644
--- a/crates/router/src/core/errors/transformers.rs
+++ b/crates/router/src/core/errors/transformers.rs
@@ -1,25 +1,7 @@
use common_utils::errors::ErrorSwitch;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
-use super::{ConnectorError, CustomersErrorResponse, StorageError};
-
-impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
- fn switch(&self) -> ApiErrorResponse {
- match self {
- Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed,
- Self::WebhookSignatureNotFound
- | Self::WebhookReferenceIdNotFound
- | Self::WebhookResourceObjectNotFound
- | Self::WebhookBodyDecodingFailed
- | Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest,
- Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity,
- Self::WebhookVerificationSecretInvalid => {
- ApiErrorResponse::WebhookInvalidMerchantSecret
- }
- _ => ApiErrorResponse::InternalServerError,
- }
- }
-}
+use super::{CustomersErrorResponse, StorageError};
impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for CustomersErrorResponse {
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
diff --git a/crates/router/src/events/connector_api_logs.rs b/crates/router/src/events/connector_api_logs.rs
index af026356826..7c354620b5a 100644
--- a/crates/router/src/events/connector_api_logs.rs
+++ b/crates/router/src/events/connector_api_logs.rs
@@ -1,95 +1,8 @@
-use common_utils::request::Method;
-use router_env::tracing_actix_web::RequestId;
-use serde::Serialize;
-use serde_json::json;
-use time::OffsetDateTime;
+pub use hyperswitch_interfaces::events::connector_api_logs::ConnectorEvent;
use super::EventType;
use crate::services::kafka::KafkaMessage;
-#[derive(Debug, Serialize)]
-pub struct ConnectorEvent {
- connector_name: String,
- flow: String,
- request: String,
- masked_response: Option<String>,
- error: Option<String>,
- url: String,
- method: String,
- payment_id: String,
- merchant_id: String,
- created_at: i128,
- request_id: String,
- latency: u128,
- refund_id: Option<String>,
- dispute_id: Option<String>,
- status_code: u16,
-}
-
-impl ConnectorEvent {
- #[allow(clippy::too_many_arguments)]
- pub fn new(
- connector_name: String,
- flow: &str,
- request: serde_json::Value,
- url: String,
- method: Method,
- payment_id: String,
- merchant_id: String,
- request_id: Option<&RequestId>,
- latency: u128,
- refund_id: Option<String>,
- dispute_id: Option<String>,
- status_code: u16,
- ) -> Self {
- Self {
- connector_name,
- flow: flow
- .rsplit_once("::")
- .map(|(_, s)| s)
- .unwrap_or(flow)
- .to_string(),
- request: request.to_string(),
- masked_response: None,
- error: None,
- url,
- method: method.to_string(),
- payment_id,
- merchant_id,
- created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
- request_id: request_id
- .map(|i| i.as_hyphenated().to_string())
- .unwrap_or("NO_REQUEST_ID".to_string()),
- latency,
- refund_id,
- dispute_id,
- status_code,
- }
- }
-
- pub fn set_response_body<T: Serialize>(&mut self, response: &T) {
- match masking::masked_serialize(response) {
- Ok(masked) => {
- self.masked_response = Some(masked.to_string());
- }
- Err(er) => self.set_error(json!({"error": er.to_string()})),
- }
- }
-
- pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) {
- match masking::masked_serialize(response) {
- Ok(masked) => {
- self.error = Some(masked.to_string());
- }
- Err(er) => self.set_error(json!({"error": er.to_string()})),
- }
- }
-
- pub fn set_error(&mut self, error: serde_json::Value) {
- self.error = Some(error.to_string());
- }
-}
-
impl KafkaMessage for ConnectorEvent {
fn event_type(&self) -> EventType {
EventType::ConnectorApiLogs
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 18014c6e193..eef85410981 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -76,7 +76,6 @@ counter_metric!(REDIRECTION_TRIGGERED, GLOBAL_METER);
// Connector Level Metric
counter_metric!(REQUEST_BUILD_FAILURE, GLOBAL_METER);
-counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER);
// Connector http status code metrics
counter_metric!(CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT, GLOBAL_METER);
counter_metric!(CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT, GLOBAL_METER);
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index baa824ced3f..cccbaa496e1 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -25,6 +25,9 @@ use common_utils::{
};
use error_stack::{report, Report, ResultExt};
pub use hyperswitch_domain_models::router_response_types::RedirectForm;
+pub use hyperswitch_interfaces::api::{
+ BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration, ConnectorIntegrationAny,
+};
use masking::{Maskable, PeekInterface};
use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag};
use serde::Serialize;
@@ -34,7 +37,7 @@ use tera::{Context, Tera};
use self::request::{HeaderExt, RequestBuilderExt};
use super::authentication::AuthenticateAndFetch;
use crate::{
- configs::{settings::Connectors, Settings},
+ configs::Settings,
consts,
core::{
api_locking,
@@ -58,22 +61,6 @@ use crate::{
},
};
-pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
- Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>;
-
-pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static {
- fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>;
-}
-
-impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S
-where
- S: ConnectorIntegration<T, Req, Resp> + Send + Sync,
-{
- fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> {
- Box::new(self)
- }
-}
-
pub trait ConnectorValidation: ConnectorCommon {
fn validate_capture_method(
&self,
@@ -129,145 +116,6 @@ pub trait ConnectorValidation: ConnectorCommon {
}
}
-#[async_trait::async_trait]
-pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync {
- fn get_headers(
- &self,
- _req: &types::RouterData<T, Req, Resp>,
- _connectors: &Connectors,
- ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
- Ok(vec![])
- }
-
- fn get_content_type(&self) -> &'static str {
- mime::APPLICATION_JSON.essence_str()
- }
-
- /// primarily used when creating signature based on request method of payment flow
- fn get_http_method(&self) -> Method {
- Method::Post
- }
-
- fn get_url(
- &self,
- _req: &types::RouterData<T, Req, Resp>,
- _connectors: &Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Ok(String::new())
- }
-
- fn get_request_body(
- &self,
- _req: &types::RouterData<T, Req, Resp>,
- _connectors: &Connectors,
- ) -> CustomResult<RequestContent, errors::ConnectorError> {
- Ok(RequestContent::Json(Box::new(json!(r#"{}"#))))
- }
-
- fn get_request_form_data(
- &self,
- _req: &types::RouterData<T, Req, Resp>,
- ) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> {
- Ok(None)
- }
-
- fn build_request(
- &self,
- req: &types::RouterData<T, Req, Resp>,
- _connectors: &Connectors,
- ) -> CustomResult<Option<Request>, errors::ConnectorError> {
- metrics::UNIMPLEMENTED_FLOW.add(
- &metrics::CONTEXT,
- 1,
- &[metrics::request::add_attributes(
- "connector",
- req.connector.clone(),
- )],
- );
- Ok(None)
- }
-
- fn handle_response(
- &self,
- data: &types::RouterData<T, Req, Resp>,
- event_builder: Option<&mut ConnectorEvent>,
- _res: types::Response,
- ) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError>
- where
- T: Clone,
- Req: Clone,
- Resp: Clone,
- {
- event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"})));
- Ok(data.clone())
- }
-
- fn get_error_response(
- &self,
- res: types::Response,
- event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
- Ok(ErrorResponse::get_not_implemented())
- }
-
- fn get_5xx_error_response(
- &self,
- res: types::Response,
- event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
- let error_message = match res.status_code {
- 500 => "internal_server_error",
- 501 => "not_implemented",
- 502 => "bad_gateway",
- 503 => "service_unavailable",
- 504 => "gateway_timeout",
- 505 => "http_version_not_supported",
- 506 => "variant_also_negotiates",
- 507 => "insufficient_storage",
- 508 => "loop_detected",
- 510 => "not_extended",
- 511 => "network_authentication_required",
- _ => "unknown_error",
- };
- Ok(ErrorResponse {
- code: res.status_code.to_string(),
- message: error_message.to_string(),
- reason: String::from_utf8(res.response.to_vec()).ok(),
- status_code: res.status_code,
- attempt_status: None,
- connector_transaction_id: None,
- })
- }
-
- // whenever capture sync is implemented at the connector side, this method should be overridden
- fn get_multiple_capture_sync_method(
- &self,
- ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into())
- }
-
- fn get_certificate(
- &self,
- _req: &types::RouterData<T, Req, Resp>,
- ) -> CustomResult<Option<String>, errors::ConnectorError> {
- Ok(None)
- }
-
- fn get_certificate_key(
- &self,
- _req: &types::RouterData<T, Req, Resp>,
- ) -> CustomResult<Option<String>, errors::ConnectorError> {
- Ok(None)
- }
-}
-
-pub enum CaptureSyncMethod {
- Individual,
- Bulk,
-}
-
/// Handle the flow by interacting with connector module
/// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger`
/// In other cases, It will be created if required, even if it is not passed
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index d864eabd093..38e0bed699f 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -52,6 +52,7 @@ pub use hyperswitch_domain_models::{
VerifyWebhookSourceResponseData, VerifyWebhookStatus,
},
};
+pub use hyperswitch_interfaces::types::Response;
pub use crate::core::payments::CustomerDetails;
#[cfg(feature = "payouts")]
@@ -684,13 +685,6 @@ pub struct ConnectorsList {
pub connectors: Vec<String>,
}
-#[derive(Clone, Debug)]
-pub struct Response {
- pub headers: Option<http::HeaderMap>,
- pub response: bytes::Bytes,
- pub status_code: u16,
-}
-
impl ForeignTryFrom<ConnectorAuthType> for AccessTokenRequestData {
type Error = errors::ApiErrorResponse;
fn foreign_try_from(connector_auth: ConnectorAuthType) -> Result<Self, Self::Error> {
diff --git a/crates/router_derive/src/macros/misc.rs b/crates/router_derive/src/macros/misc.rs
index 4717fe730d9..04c37e75950 100644
--- a/crates/router_derive/src/macros/misc.rs
+++ b/crates/router_derive/src/macros/misc.rs
@@ -52,6 +52,7 @@ pub fn validate_config(input: syn::DeriveInput) -> Result<proc_macro2::TokenStre
let expansion = quote::quote! {
impl #struct_name {
+ /// Validates that the configuration provided for the `parent_field` does not contain empty or default values
pub fn validate(&self, parent_field: &str) -> Result<(), ApplicationError> {
#(#function_expansions)*
Ok(())
|
2024-06-11T09:50:21Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The trait ConnectorIntegration needs to be moved to crate hyperswitch_interfaces from router. This is required to move connector code out from crate router.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4945
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Basic testing is required for all the production connectors(and payment methods) on sandbox.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
658272904897f7cbc4d9a349278712f35a8d3e96
|
Basic testing is required for all the production connectors(and payment methods) on sandbox.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4927
|
Bug: bug(logging): recording restricted fields via tracing causes a stack overflow
We have a set of restricted fields which can't be set by users,
We log a small warning each time such field is being used
however when such fields are recorded we end up in a self loop where the warning log itself tries to use this field as part of the recorded fields
as such we should prevent from adding restricted fields to log framework either via in-line usage or recording them
|
diff --git a/crates/router/src/routes/health.rs b/crates/router/src/routes/health.rs
index 721dbd6a78d..3e2f42bcc25 100644
--- a/crates/router/src/routes/health.rs
+++ b/crates/router/src/routes/health.rs
@@ -16,6 +16,7 @@ use crate::{
pub async fn health() -> impl actix_web::Responder {
metrics::HEALTH_METRIC.add(&metrics::CONTEXT, 1, &[]);
logger::info!("Health was called");
+
actix_web::HttpResponse::Ok().body("health is good")
}
diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs
index 472b917e746..30a80aa15df 100644
--- a/crates/router_env/src/logger/formatter.rs
+++ b/crates/router_env/src/logger/formatter.rs
@@ -58,7 +58,6 @@ const SESSION_ID: &str = "session_id";
pub static IMPLICIT_KEYS: Lazy<rustc_hash::FxHashSet<&str>> = Lazy::new(|| {
let mut set = rustc_hash::FxHashSet::default();
- set.insert(MESSAGE);
set.insert(HOSTNAME);
set.insert(PID);
set.insert(ENV);
@@ -81,6 +80,7 @@ pub static IMPLICIT_KEYS: Lazy<rustc_hash::FxHashSet<&str>> = Lazy::new(|| {
pub static EXTRA_IMPLICIT_KEYS: Lazy<rustc_hash::FxHashSet<&str>> = Lazy::new(|| {
let mut set = rustc_hash::FxHashSet::default();
+ set.insert(MESSAGE);
set.insert(FLOW);
set.insert(MERCHANT_AUTH);
set.insert(MERCHANT_ID);
@@ -163,7 +163,7 @@ where
pub fn new_with_implicit_entries(
service: &str,
dst_writer: W,
- default_fields: HashMap<String, Value>,
+ mut default_fields: HashMap<String, Value>,
formatter: F,
) -> Self {
let pid = std::process::id();
@@ -174,6 +174,18 @@ where
#[cfg(feature = "vergen")]
let build = crate::build!().to_string();
let env = crate::env::which().to_string();
+ default_fields.retain(|key, value| {
+ if !IMPLICIT_KEYS.contains(key.as_str()) {
+ true
+ } else {
+ tracing::warn!(
+ ?key,
+ ?value,
+ "Attempting to log a reserved entry. It won't be added to the logs"
+ );
+ false
+ }
+ });
Self {
dst_writer,
@@ -196,9 +208,8 @@ where
map_serializer: &mut impl SerializeMap<Error = serde_json::Error>,
metadata: &Metadata<'_>,
span: Option<&SpanRef<'_, S>>,
- storage: Option<&Storage<'_>>,
+ storage: &Storage<'_>,
name: &str,
- message: &str,
) -> Result<(), std::io::Error>
where
S: Subscriber + for<'a> LookupSpan<'a>,
@@ -206,7 +217,6 @@ where
let is_extra = |s: &str| !IMPLICIT_KEYS.contains(s);
let is_extra_implicit = |s: &str| is_extra(s) && EXTRA_IMPLICIT_KEYS.contains(s);
- map_serializer.serialize_entry(MESSAGE, &message)?;
map_serializer.serialize_entry(HOSTNAME, &self.hostname)?;
map_serializer.serialize_entry(PID, &self.pid)?;
map_serializer.serialize_entry(ENV, &self.env)?;
@@ -228,30 +238,30 @@ where
// Write down implicit default entries.
for (key, value) in self.default_fields.iter() {
- if !IMPLICIT_KEYS.contains(key.as_str()) {
- map_serializer.serialize_entry(key, value)?;
- } else {
- tracing::warn!("{} is a reserved field. Skipping it.", key);
- }
+ map_serializer.serialize_entry(key, value)?;
}
#[cfg(feature = "log_custom_entries_to_extra")]
let mut extra = serde_json::Map::default();
let mut explicit_entries_set: HashSet<&str> = HashSet::default();
// Write down explicit event's entries.
- if let Some(storage) = storage {
- for (key, value) in storage.values.iter() {
- if is_extra_implicit(key) {
- #[cfg(feature = "log_extra_implicit_fields")]
- map_serializer.serialize_entry(key, value)?;
- explicit_entries_set.insert(key);
- } else if is_extra(key) {
- #[cfg(feature = "log_custom_entries_to_extra")]
- extra.insert(key.to_string(), value.clone());
- #[cfg(not(feature = "log_custom_entries_to_extra"))]
- map_serializer.serialize_entry(key, value)?;
- explicit_entries_set.insert(key);
- }
+ for (key, value) in storage.values.iter() {
+ if is_extra_implicit(key) {
+ #[cfg(feature = "log_extra_implicit_fields")]
+ map_serializer.serialize_entry(key, value)?;
+ explicit_entries_set.insert(key);
+ } else if is_extra(key) {
+ #[cfg(feature = "log_custom_entries_to_extra")]
+ extra.insert(key.to_string(), value.clone());
+ #[cfg(not(feature = "log_custom_entries_to_extra"))]
+ map_serializer.serialize_entry(key, value)?;
+ explicit_entries_set.insert(key);
+ } else {
+ tracing::warn!(
+ ?key,
+ ?value,
+ "Attempting to log a reserved entry. It won't be added to the logs"
+ );
}
}
@@ -269,7 +279,11 @@ where
#[cfg(not(feature = "log_custom_entries_to_extra"))]
map_serializer.serialize_entry(key, value)?;
} else {
- tracing::debug!("{} is a reserved entry. Skipping it.", key);
+ tracing::warn!(
+ ?key,
+ ?value,
+ "Attempting to log a reserved entry. It won't be added to the logs"
+ );
}
}
}
@@ -305,14 +319,15 @@ where
serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone());
let mut map_serializer = serializer.serialize_map(None)?;
let message = Self::span_message(span, ty);
+ let mut storage = Storage::default();
+ storage.record_value("message", message.into());
self.common_serialize(
&mut map_serializer,
span.metadata(),
Some(span),
- None,
+ &storage,
span.name(),
- &message,
)?;
map_serializer.end()?;
@@ -337,16 +352,9 @@ where
event.record(&mut storage);
let name = span.map_or("?", SpanRef::name);
- let message = Self::event_message(span, event, &storage);
+ Self::event_message(span, event, &mut storage);
- self.common_serialize(
- &mut map_serializer,
- event.metadata(),
- *span,
- Some(&storage),
- name,
- &message,
- )?;
+ self.common_serialize(&mut map_serializer, event.metadata(), *span, &storage, name)?;
map_serializer.end()?;
Ok(buffer)
@@ -374,32 +382,20 @@ where
fn event_message<S>(
span: &Option<&SpanRef<'_, S>>,
event: &Event<'_>,
- storage: &Storage<'_>,
- ) -> String
- where
+ storage: &mut Storage<'_>,
+ ) where
S: Subscriber + for<'a> LookupSpan<'a>,
{
// Get value of kept "message" or "target" if does not exist.
- let mut message = storage
+ let message = storage
.values
- .get("message")
- .and_then(|v| match v {
- Value::String(s) => Some(s.as_str()),
- _ => None,
- })
- .unwrap_or_else(|| event.metadata().target())
- .to_owned();
+ .entry("message")
+ .or_insert_with(|| event.metadata().target().into());
// Prepend the span name to the message if span exists.
- if let Some(span) = span {
- message = format!(
- "{} {}",
- Self::span_message(span, RecordType::Event),
- message,
- );
+ if let (Some(span), Value::String(a)) = (span, message) {
+ *a = format!("{} {}", Self::span_message(span, RecordType::Event), a,);
}
-
- message
}
}
diff --git a/crates/router_env/src/logger/storage.rs b/crates/router_env/src/logger/storage.rs
index a134bbed73e..ce220680bb1 100644
--- a/crates/router_env/src/logger/storage.rs
+++ b/crates/router_env/src/logger/storage.rs
@@ -28,6 +28,14 @@ impl<'a> Storage<'a> {
pub fn new() -> Self {
Self::default()
}
+
+ pub fn record_value(&mut self, key: &'a str, value: serde_json::Value) {
+ if super::formatter::IMPLICIT_KEYS.contains(key) {
+ tracing::warn!(value =? value, "{} is a reserved entry. Skipping it.", key);
+ } else {
+ self.values.insert(key, value);
+ }
+ }
}
/// Default constructor.
@@ -43,32 +51,27 @@ impl Default for Storage<'_> {
impl Visit for Storage<'_> {
/// A i64.
fn record_i64(&mut self, field: &Field, value: i64) {
- self.values
- .insert(field.name(), serde_json::Value::from(value));
+ self.record_value(field.name(), serde_json::Value::from(value));
}
/// A u64.
fn record_u64(&mut self, field: &Field, value: u64) {
- self.values
- .insert(field.name(), serde_json::Value::from(value));
+ self.record_value(field.name(), serde_json::Value::from(value));
}
/// A 64-bit floating point.
fn record_f64(&mut self, field: &Field, value: f64) {
- self.values
- .insert(field.name(), serde_json::Value::from(value));
+ self.record_value(field.name(), serde_json::Value::from(value));
}
/// A boolean.
fn record_bool(&mut self, field: &Field, value: bool) {
- self.values
- .insert(field.name(), serde_json::Value::from(value));
+ self.record_value(field.name(), serde_json::Value::from(value));
}
/// A string.
fn record_str(&mut self, field: &Field, value: &str) {
- self.values
- .insert(field.name(), serde_json::Value::from(value));
+ self.record_value(field.name(), serde_json::Value::from(value));
}
/// Otherwise.
@@ -77,7 +80,7 @@ impl Visit for Storage<'_> {
// Skip fields which are already handled
name if name.starts_with("log.") => (),
name if name.starts_with("r#") => {
- self.values.insert(
+ self.record_value(
#[allow(clippy::expect_used)]
name.get(2..)
.expect("field name must have a minimum of two characters"),
@@ -85,8 +88,7 @@ impl Visit for Storage<'_> {
);
}
name => {
- self.values
- .insert(name, serde_json::Value::from(format!("{value:?}")));
+ self.record_value(name, serde_json::Value::from(format!("{value:?}")));
}
};
}
@@ -165,7 +167,7 @@ impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer
span.parent().and_then(|p| {
p.extensions_mut()
.get_mut::<Storage<'_>>()
- .map(|s| s.values.insert(k, v.to_owned()))
+ .map(|s| s.record_value(k, v.to_owned()))
});
}
})
@@ -178,7 +180,7 @@ impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer
.expect("No visitor in extensions");
if let Ok(elapsed) = serde_json::to_value(elapsed_milliseconds) {
- visitor.values.insert("elapsed_milliseconds", elapsed);
+ visitor.record_value("elapsed_milliseconds", elapsed);
}
}
}
|
2024-04-22T11:05:13Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Handle stack overflows when restricted keys are being recorded in spans
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- enable debug/trace logging and create payments
- there shouldn't be anymore stack overflows
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
7085a46271791ca3f1c7b86afa7c8b199b93c0cd
|
- enable debug/trace logging and create payments
- there shouldn't be anymore stack overflows
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4924
|
Bug: Add `is_connector_agnostic_mit_enabled` in the business profile APIs
`is_connector_agnostic_mit_enabled` this filed is used to make connector agnostic MIT payments. If set to `true` the recurring payments (MIT) can be routed to any other connector which supports network transaction id flow. If it `false` the subsequent MITs needs to be routed trough the same connector as CIT.
Hence adding support create and update the filed in business profile create, update and in business profile response.
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 58cb6fbf3e2..bd569b1febb 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -938,6 +938,12 @@ pub struct BusinessProfileCreate {
/// A boolean value to indicate if customer shipping details needs to be sent for wallets payments
pub collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// Indicates if the MIT (merchant initiated transaction) payments can be made connector
+ /// agnostic, i.e., MITs may be processed through different connector than CIT (customer
+ /// initiated transaction) based on the routing rules.
+ /// If set to `false`, MIT will go through the same connector as the CIT.
+ pub is_connector_agnostic_mit_enabled: Option<bool>,
}
#[derive(Clone, Debug, ToSchema, Serialize)]
@@ -1016,6 +1022,12 @@ pub struct BusinessProfileResponse {
/// A boolean value to indicate if customer shipping details needs to be sent for wallets payments
pub collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// Indicates if the MIT (merchant initiated transaction) payments can be made connector
+ /// agnostic, i.e., MITs may be processed through different connector than CIT (customer
+ /// initiated transaction) based on the routing rules.
+ /// If set to `false`, MIT will go through the same connector as the CIT.
+ pub is_connector_agnostic_mit_enabled: Option<bool>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
@@ -1086,6 +1098,12 @@ pub struct BusinessProfileUpdate {
/// A boolean value to indicate if customer shipping details needs to be sent for wallets payments
pub collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// Indicates if the MIT (merchant initiated transaction) payments can be made connector
+ /// agnostic, i.e., MITs may be processed through different connector than CIT (customer
+ /// initiated transaction) based on the routing rules.
+ /// If set to `false`, MIT will go through the same connector as the CIT.
+ pub is_connector_agnostic_mit_enabled: Option<bool>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index fb1b62e5436..872bb0c09d6 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -124,6 +124,7 @@ pub enum BusinessProfileUpdate {
extended_card_info_config: Option<pii::SecretSerdeValue>,
use_billing_as_payment_method_billing: Option<bool>,
collect_shipping_details_from_wallet_connector: Option<bool>,
+ is_connector_agnostic_mit_enabled: Option<bool>,
},
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: Option<bool>,
@@ -157,6 +158,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
extended_card_info_config,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
+ is_connector_agnostic_mit_enabled,
} => Self {
profile_name,
modified_at,
@@ -178,6 +180,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
extended_card_info_config,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
+ is_connector_agnostic_mit_enabled,
..Default::default()
},
BusinessProfileUpdate::ExtendedCardInfoUpdate {
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index f9da9908d95..bd1b122f57c 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -442,6 +442,7 @@ pub async fn update_business_profile_cascade(
extended_card_info_config: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
+ is_connector_agnostic_mit_enabled: None,
};
let update_futures = business_profiles.iter().map(|business_profile| async {
@@ -1728,6 +1729,7 @@ pub async fn update_business_profile(
use_billing_as_payment_method_billing: request.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: request
.collect_shipping_details_from_wallet_connector,
+ is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled,
};
let updated_business_profile = db
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 2e1032e8e4c..c77802a1503 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -277,6 +277,7 @@ pub async fn update_business_profile_active_algorithm_ref(
extended_card_info_config: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
+ is_connector_agnostic_mit_enabled: None,
};
db.update_business_profile_by_profile_id(current_business_profile, business_profile_update)
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index b79819ed634..09c362c1164 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -87,6 +87,7 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf
.transpose()?,
collect_shipping_details_from_wallet_connector: item
.collect_shipping_details_from_wallet_connector,
+ is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
})
}
}
@@ -183,7 +184,7 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "authentication_connector_details",
})?,
- is_connector_agnostic_mit_enabled: None,
+ is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
use_billing_as_payment_method_billing: request
|
2024-06-10T07:21:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
`is_connector_agnostic_mit_enabled` this field is used to make connector agnostic MIT payments. If set to `true` the recurring payments (MIT) can be routed to any other connector which supports network transaction id flow. If it `false` the subsequent MITs needs to be routed trough the same connector as CIT.
Hence adding support create and update the filed in business profile create, update and in business profile response.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant account
-> Create a business profile under the above merchant account
```
curl --location 'http://localhost:8080/account/merchant_1718004259/business_profile' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"profile_name": "Pg_agnostic_mit",
"collect_shipping_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": true
}'
```
Business profile create response
<img width="926" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/42dbde60-18da-4d41-8fff-84fb2a19aa6e">
Field update in the db

-> Update business profile
```
curl --location 'http://localhost:8080/account/merchant_1718004259/business_profile/pro_xmsxiQK2NBWahvXgWbmv' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"is_connector_agnostic_mit_enabled": false
}'
```
Update business profile response
<img width="574" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/275778c6-085a-4b6f-be0c-4eadfc66ba38">
Field updated in the db

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ff93981ec776031af1de946cd6e9f90d2f410cd2
|
-> Create a merchant account
-> Create a business profile under the above merchant account
```
curl --location 'http://localhost:8080/account/merchant_1718004259/business_profile' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"profile_name": "Pg_agnostic_mit",
"collect_shipping_details_from_wallet_connector": true,
"is_connector_agnostic_mit_enabled": true
}'
```
Business profile create response
<img width="926" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/42dbde60-18da-4d41-8fff-84fb2a19aa6e">
Field update in the db

-> Update business profile
```
curl --location 'http://localhost:8080/account/merchant_1718004259/business_profile/pro_xmsxiQK2NBWahvXgWbmv' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"is_connector_agnostic_mit_enabled": false
}'
```
Update business profile response
<img width="574" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/275778c6-085a-4b6f-be0c-4eadfc66ba38">
Field updated in the db

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4914
|
Bug: fix(payments): populate payments method data in list
Populate payment method data in payments list to get details of card network.
|
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 49319dff3a2..abc1bdd0a1c 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -966,6 +966,15 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
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
+ }
+ }
+ }),
..Default::default()
}
}
|
2024-06-07T13:24:40Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Populate payment method data in payments list to get card network details.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#4914](https://github.com/juspay/hyperswitch/issues/4914)
## How did you test it?
Tested with curl for payments list
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ; Cookie_1=value' \
--header 'Authorization: Bearer HWT' \
--data '{
"amount_filter": {
"start_amount": 12600,
"end_amount": 12600
}
}'
```
Response
```
{
"count": 1,
"total_count": 1,
"data": [
{
"payment_id": "test_JUwD6r4ImcpnW9RhkWcN",
"merchant_id": "merchant_1715344934",
"status": "succeeded",
"amount": 12600,
"net_amount": 0,
"amount_capturable": 12600,
"amount_received": null,
"connector": "paypal_test",
"client_secret": "test_JUwD6r4ImcpnW9RhkWcN_secret_IRO8wJMTouwAUjAVcBg9",
"created": "2024-06-02T05:43:07.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"customer": null,
"description": "This is a sample payment",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "John",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "test_JUwD6r4ImcpnW9RhkWcN_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_IF0OamH2WybnNqqbgYWx",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": null,
"charges": null,
"frm_metadata": null
}
]
}
```
<img width="802" alt="Screenshot 2024-06-07 at 6 52 30 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/12432d43-5678-4025-a090-d1810b3d91c7">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d784fcb5e65060eb35424448b4762f09f83d532b
|
Tested with curl for payments list
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ; Cookie_1=value' \
--header 'Authorization: Bearer HWT' \
--data '{
"amount_filter": {
"start_amount": 12600,
"end_amount": 12600
}
}'
```
Response
```
{
"count": 1,
"total_count": 1,
"data": [
{
"payment_id": "test_JUwD6r4ImcpnW9RhkWcN",
"merchant_id": "merchant_1715344934",
"status": "succeeded",
"amount": 12600,
"net_amount": 0,
"amount_capturable": 12600,
"amount_received": null,
"connector": "paypal_test",
"client_secret": "test_JUwD6r4ImcpnW9RhkWcN_secret_IRO8wJMTouwAUjAVcBg9",
"created": "2024-06-02T05:43:07.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"customer": null,
"description": "This is a sample payment",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": "CREDIT",
"card_network": "Visa",
"card_issuer": "STRIPE PAYMENTS UK LIMITED",
"card_issuing_country": "UNITEDKINGDOM",
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "John",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "test_JUwD6r4ImcpnW9RhkWcN_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_IF0OamH2WybnNqqbgYWx",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": null,
"charges": null,
"frm_metadata": null
}
]
}
```
<img width="802" alt="Screenshot 2024-06-07 at 6 52 30 PM" src="https://github.com/juspay/hyperswitch/assets/64925866/12432d43-5678-4025-a090-d1810b3d91c7">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4905
|
Bug: fix(opensearch): handle index not present errors in search api
Currently in the self deployment mode we rely on fluentd to automatically create the index,
in this case when we spin up the local setup the msearch API errors out since the index is not present,
with the following json response
```json
{
"took": 17,
"responses": [
{
"took": 15,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"status": 200
},
{
"took": 12,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 0,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"status": 200
},
{
"error": {
"root_cause": [
{
"type": "index_not_found_exception",
"reason": "no such index [hyperswitch-refund-events]",
"index": "hyperswitch-refund-events",
"resource.id": "hyperswitch-refund-events",
"resource.type": "index_or_alias",
"index_uuid": "_na_"
}
],
"type": "index_not_found_exception",
"reason": "no such index [hyperswitch-refund-events]",
"index": "hyperswitch-refund-events",
"resource.id": "hyperswitch-refund-events",
"resource.type": "index_or_alias",
"index_uuid": "_na_"
},
"status": 404
},
{
"error": {
"root_cause": [
{
"type": "index_not_found_exception",
"reason": "no such index [hyperswitch-dispute-events]",
"index": "hyperswitch-dispute-events",
"resource.id": "hyperswitch-dispute-events",
"resource.type": "index_or_alias",
"index_uuid": "_na_"
}
],
"type": "index_not_found_exception",
"reason": "no such index [hyperswitch-dispute-events]",
"index": "hyperswitch-dispute-events",
"resource.id": "hyperswitch-dispute-events",
"resource.type": "index_or_alias",
"index_uuid": "_na_"
},
"status": 404
}
]
}
```
In this case it would be better if we treat missing index as 0 hits and log the corresponding errors.
|
diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md
index b822edd810e..da9a3c79f1f 100644
--- a/crates/analytics/docs/README.md
+++ b/crates/analytics/docs/README.md
@@ -101,4 +101,18 @@ Here's an example of how to do this:
[default.features]
audit_trail=true
system_metrics=true
-```
\ No newline at end of file
+global_search=true
+```
+
+## Viewing the data on OpenSearch Dashboard
+
+To view the data on the OpenSearch dashboard perform the following steps:
+
+- Go to the OpenSearch Dashboard home and click on `Stack Management` under the Management tab
+- Select `Index Patterns`
+- Click on `Create index pattern`
+- Define an index pattern with the same name that matches your indices and click on `Next Step`
+- Select a time field that will be used for time-based queries
+- Save the index pattern
+
+Now, head on to the `Discover` tab, to select the newly created index pattern and query the data
\ No newline at end of file
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 7b19ba0ed06..e8f87aaef2e 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -76,6 +76,8 @@ pub enum OpenSearchError {
ResponseError,
#[error("Opensearch query building error")]
QueryBuildingError,
+ #[error("Opensearch deserialisation error")]
+ DeserialisationError,
}
impl ErrorSwitch<OpenSearchError> for QueryBuildingError {
@@ -111,6 +113,12 @@ impl ErrorSwitch<ApiErrorResponse> for OpenSearchError {
"Query building error",
None,
)),
+ Self::DeserialisationError => ApiErrorResponse::InternalServerError(ApiError::new(
+ "IR",
+ 0,
+ "Deserialisation error",
+ None,
+ )),
}
}
}
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index dc802ff6948..8810dc1e3a1 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -4,7 +4,7 @@ use api_models::analytics::search::{
};
use common_utils::errors::{CustomResult, ReportSwitchExt};
use error_stack::ResultExt;
-use serde_json::Value;
+use router_env::tracing;
use strum::IntoEnumIterator;
use crate::opensearch::{
@@ -22,27 +22,59 @@ pub async fn msearch_results(
.add_filter_clause("merchant_id".to_string(), merchant_id.to_string())
.switch()?;
- let response_body = client
+ let response_text: OpenMsearchOutput = client
.execute(query_builder)
.await
.change_context(OpenSearchError::ConnectionError)?
- .json::<OpenMsearchOutput<Value>>()
+ .text()
.await
- .change_context(OpenSearchError::ResponseError)?;
+ .change_context(OpenSearchError::ResponseError)
+ .and_then(|body: String| {
+ serde_json::from_str::<OpenMsearchOutput>(&body)
+ .change_context(OpenSearchError::DeserialisationError)
+ .attach_printable(body.clone())
+ })?;
+
+ let response_body: OpenMsearchOutput = response_text;
Ok(response_body
.responses
.into_iter()
.zip(SearchIndex::iter())
- .map(|(index_hit, index)| GetSearchResponse {
- count: index_hit.hits.total.value,
- index,
- hits: index_hit
- .hits
- .hits
- .into_iter()
- .map(|hit| hit._source)
- .collect(),
+ .map(|(index_hit, index)| match index_hit {
+ OpensearchOutput::Success(success) => {
+ if success.status == 200 {
+ GetSearchResponse {
+ count: success.hits.total.value,
+ index,
+ hits: success
+ .hits
+ .hits
+ .into_iter()
+ .map(|hit| hit.source)
+ .collect(),
+ }
+ } else {
+ tracing::error!("Unexpected status code: {}", success.status,);
+ GetSearchResponse {
+ count: 0,
+ index,
+ hits: Vec::new(),
+ }
+ }
+ }
+ OpensearchOutput::Error(error) => {
+ tracing::error!(
+ index = ?index,
+ error_response = ?error,
+ "Search error"
+ );
+ GetSearchResponse {
+ count: 0,
+ index,
+ hits: Vec::new(),
+ }
+ }
})
.collect())
}
@@ -65,22 +97,54 @@ pub async fn search_results(
.set_offset_n_count(search_req.offset, search_req.count)
.switch()?;
- let response_body = client
+ let response_text: OpensearchOutput = client
.execute(query_builder)
.await
.change_context(OpenSearchError::ConnectionError)?
- .json::<OpensearchOutput<Value>>()
+ .text()
.await
- .change_context(OpenSearchError::ResponseError)?;
+ .change_context(OpenSearchError::ResponseError)
+ .and_then(|body: String| {
+ serde_json::from_str::<OpensearchOutput>(&body)
+ .change_context(OpenSearchError::DeserialisationError)
+ .attach_printable(body.clone())
+ })?;
+
+ let response_body: OpensearchOutput = response_text;
- Ok(GetSearchResponse {
- count: response_body.hits.total.value,
- index: req.index,
- hits: response_body
- .hits
- .hits
- .into_iter()
- .map(|hit| hit._source)
- .collect(),
- })
+ match response_body {
+ OpensearchOutput::Success(success) => {
+ if success.status == 200 {
+ Ok(GetSearchResponse {
+ count: success.hits.total.value,
+ index: req.index,
+ hits: success
+ .hits
+ .hits
+ .into_iter()
+ .map(|hit| hit.source)
+ .collect(),
+ })
+ } else {
+ tracing::error!("Unexpected status code: {}", success.status);
+ Ok(GetSearchResponse {
+ count: 0,
+ index: req.index,
+ hits: Vec::new(),
+ })
+ }
+ }
+ OpensearchOutput::Error(error) => {
+ tracing::error!(
+ index = ?req.index,
+ error_response = ?error,
+ "Search error"
+ );
+ Ok(GetSearchResponse {
+ count: 0,
+ index: req.index,
+ hits: Vec::new(),
+ })
+ }
+ }
}
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index 6f6a3f22812..c29bb0e9f71 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -48,19 +48,40 @@ pub struct GetSearchResponse {
}
#[derive(Debug, serde::Deserialize)]
-pub struct OpenMsearchOutput<T> {
- pub responses: Vec<OpensearchOutput<T>>,
+pub struct OpenMsearchOutput {
+ pub responses: Vec<OpensearchOutput>,
}
#[derive(Debug, serde::Deserialize)]
-pub struct OpensearchOutput<T> {
- pub hits: OpensearchResults<T>,
+#[serde(untagged)]
+pub enum OpensearchOutput {
+ Success(OpensearchSuccess),
+ Error(OpensearchError),
}
#[derive(Debug, serde::Deserialize)]
-pub struct OpensearchResults<T> {
+pub struct OpensearchError {
+ pub error: OpensearchErrorDetails,
+ pub status: u16,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchErrorDetails {
+ #[serde(rename = "type")]
+ pub error_type: String,
+ pub reason: String,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchSuccess {
+ pub status: u16,
+ pub hits: OpensearchHits,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchHits {
pub total: OpensearchResultsTotal,
- pub hits: Vec<OpensearchHits<T>>,
+ pub hits: Vec<OpensearchHit>,
}
#[derive(Debug, serde::Deserialize)]
@@ -69,6 +90,7 @@ pub struct OpensearchResultsTotal {
}
#[derive(Debug, serde::Deserialize)]
-pub struct OpensearchHits<T> {
- pub _source: T,
+pub struct OpensearchHit {
+ #[serde(rename = "_source")]
+ pub source: Value,
}
|
2024-06-12T10:13:57Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Handled errors when index is not present, by logging the corresponding error message and treating the hits as 0.
- Changed the structure of `OpensearchOutput` and corresponding structs which are used to handle the error.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
The msearch API errors out since the index is not present, so handled the error.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Set up the global search locally
- Test the global search with any keyword
- Go through the log, and `5xx errors` should not be present anymore, with the errors logged, and handling of the index not found errors.

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a7ad7906d7e84fa59df3cfffd16dea8db300e675
|
- Set up the global search locally
- Test the global search with any keyword
- Go through the log, and `5xx errors` should not be present anymore, with the errors logged, and handling of the index not found errors.

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4931
|
Bug: [CHORE] : update apple pay metadata fields
### Feature Description
Currently apple pay iOS Certificate flow contains seven fields, in addition to that three more fields needs to be added.
### Possible Implementation
update the wasm to accept the fields
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 246eb566a91..5d4aea5d5dd 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -244,6 +244,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[adyen.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -360,6 +361,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[authorizedotnet.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -463,6 +465,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[bankofamerica.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -540,6 +543,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[bluesnap.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -772,6 +776,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[checkout.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -854,6 +859,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[cybersource.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1331,6 +1337,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[nexinets.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1402,6 +1409,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[nmi.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1469,6 +1477,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[noon.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1548,6 +1557,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[nuvei.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1869,6 +1879,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[rapyd.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2023,6 +2034,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[stripe.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2180,6 +2192,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[trustpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2347,6 +2360,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[worldpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 30b63249881..eb35dbf3df2 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -139,6 +139,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[adyen.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -248,6 +249,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[authorizedotnet.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -322,6 +324,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[bluesnap.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -476,6 +479,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[bankofamerica.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -651,6 +655,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[checkout.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -721,6 +726,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[cybersource.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1126,6 +1132,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[nexinets.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1383,6 +1390,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[rapyd.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1521,6 +1529,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[stripe.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1593,6 +1602,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[trustpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1701,6 +1711,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[worldpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index dee4e5e4fb6..acc422f3bd9 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -244,6 +244,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[adyen.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -360,6 +361,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[authorizedotnet.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -463,6 +465,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[bankofamerica.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -540,6 +543,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[bluesnap.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -772,6 +776,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[checkout.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -854,6 +859,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[cybersource.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1331,6 +1337,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[nexinets.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1402,6 +1409,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[nmi.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1469,6 +1477,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[noon.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1548,6 +1557,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[nuvei.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -1869,6 +1879,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[rapyd.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2023,6 +2034,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[stripe.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2180,6 +2192,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[trustpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
@@ -2347,6 +2360,7 @@ merchant_identifier="Apple Merchant Identifier"
display_name="Display Name"
initiative="Domain"
initiative_context="Domain Name"
+payment_processing_details_at="Connector"
[worldpay.metadata.apple_pay.payment_request_data]
supported_networks=["visa","masterCard","amex","discover"]
merchant_capabilities=["supports3DS"]
|
2024-06-10T10:39:57Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
update apple pay metadata
<img width="574" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/7ac299bf-99e7-4cfb-b0f4-224a028d3406">
<img width="557" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/a5d5826a-7865-4419-87c6-fa79cb4fe053">
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7085a46271791ca3f1c7b86afa7c8b199b93c0cd
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4933
|
Bug: Refactor `/payment_methods` to support a unified interface for vaulting use-cases
### Feature Description
We want a unified interface to `/payment_methods` create APIs for vaulting a payment method. Request/Response types and their behavior should be same across the vaulting APIs.
Involved APIs would be PM create and PM save.
### Possible Implementation
Can involve -
- refactoring of Req/Res (and other relevant types) for vaulting APIs
- refactoring of core logic for vaulting APIs
|
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 00c12b9255b..c16b1d9a418 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -20,7 +20,7 @@ v1 = ["common_utils/v1"]
v2 = ["common_utils/v2", "customer_v2"]
customer_v2 = ["common_utils/customer_v2"]
payment_v2 = []
-payment_methods_v2 = []
+payment_methods_v2 = ["common_utils/payment_methods_v2"]
[dependencies]
actix-web = { version = "4.5.1", optional = true }
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 58727a46cf3..13966c464d5 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -152,3 +152,21 @@ impl<T> ApiEventMetric for MetricsResponse<T> {
Some(ApiEventsType::Miscellaneous)
}
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl ApiEventMetric for PaymentMethodIntentConfirmInternal {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethod {
+ payment_method_id: self.id.clone(),
+ payment_method: Some(self.payment_method),
+ payment_method_type: Some(self.payment_method_type),
+ })
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl ApiEventMetric for PaymentMethodIntentCreate {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::PaymentMethodCreate)
+ }
+}
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index c6cf6380150..6c93b0bb5bd 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -160,8 +160,68 @@ pub struct PaymentMethodIntentConfirm {
/// Payment method data to be passed
pub payment_method_data: PaymentMethodCreateData,
+
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod,example = "card")]
+ pub payment_method: api_enums::PaymentMethod,
+
+ /// This is a sub-category of payment method.
+ #[schema(value_type = PaymentMethodType,example = "credit")]
+ pub payment_method_type: api_enums::PaymentMethodType,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethodIntentConfirm {
+ pub fn validate_payment_method_data_against_payment_method(
+ payment_method: api_enums::PaymentMethod,
+ payment_method_data: PaymentMethodCreateData,
+ ) -> bool {
+ match payment_method {
+ api_enums::PaymentMethod::Card => {
+ matches!(payment_method_data, PaymentMethodCreateData::Card(_))
+ }
+ _ => false,
+ }
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+pub struct PaymentMethodIntentConfirmInternal {
+ #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub id: String,
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod,example = "card")]
+ pub payment_method: api_enums::PaymentMethod,
+
+ /// This is a sub-category of payment method.
+ #[schema(value_type = PaymentMethodType,example = "credit")]
+ pub payment_method_type: api_enums::PaymentMethodType,
+
+ /// For SDK based calls, client_secret would be required
+ pub client_secret: String,
+
+ /// The unique identifier of the customer.
+ #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: Option<id_type::CustomerId>,
+
+ /// Payment method data to be passed
+ pub payment_method_data: PaymentMethodCreateData,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<PaymentMethodIntentConfirmInternal> for PaymentMethodIntentConfirm {
+ fn from(item: PaymentMethodIntentConfirmInternal) -> Self {
+ Self {
+ client_secret: item.client_secret,
+ payment_method: item.payment_method,
+ payment_method_type: item.payment_method_type,
+ customer_id: item.customer_id,
+ payment_method_data: item.payment_method_data.clone(),
+ }
+ }
+}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
/// This struct is only used by and internal api to migrate payment method
pub struct PaymentMethodMigrate {
@@ -276,11 +336,16 @@ impl PaymentMethodCreate {
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl PaymentMethodCreate {
- pub fn get_payment_method_create_from_payment_method_migrate(
- _card_number: CardNumber,
- _payment_method_migrate: &PaymentMethodMigrate,
- ) -> Self {
- todo!()
+ pub fn validate_payment_method_data_against_payment_method(
+ payment_method: api_enums::PaymentMethod,
+ payment_method_data: PaymentMethodCreateData,
+ ) -> bool {
+ match payment_method {
+ api_enums::PaymentMethod::Card => {
+ matches!(payment_method_data, PaymentMethodCreateData::Card(_))
+ }
+ _ => false,
+ }
}
}
@@ -332,12 +397,6 @@ pub enum PaymentMethodUpdateData {
#[serde(rename = "payment_method_data")]
pub enum PaymentMethodCreateData {
Card(CardDetail),
- #[cfg(feature = "payouts")]
- #[schema(value_type = Bank)]
- BankTransfer(payouts::Bank),
- #[cfg(feature = "payouts")]
- #[schema(value_type = Wallet)]
- Wallet(payouts::Wallet),
}
#[cfg(all(
@@ -577,9 +636,6 @@ impl CardDetailUpdate {
#[serde(rename = "payment_method_data")]
pub enum PaymentMethodResponseData {
Card(CardDetailFromLocker),
- #[cfg(feature = "payouts")]
- #[schema(value_type = Bank)]
- Bank(payouts::Bank),
}
#[cfg(all(
@@ -934,6 +990,25 @@ impl From<CardDetailsPaymentMethod> for CardDetailFromLocker {
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl From<CardDetail> for CardDetailsPaymentMethod {
+ fn from(item: CardDetail) -> Self {
+ Self {
+ issuer_country: item.card_issuing_country.map(|c| c.to_string()),
+ last4_digits: Some(item.card_number.get_last4()),
+ expiry_month: Some(item.card_exp_month),
+ expiry_year: Some(item.card_exp_year),
+ card_holder_name: item.card_holder_name,
+ nick_name: item.nick_name,
+ card_isin: None,
+ card_issuer: item.card_issuer,
+ card_network: item.card_network,
+ card_type: item.card_type.map(|card| card.to_string()),
+ saved_to_locker: true,
+ }
+ }
+}
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index c6e29801b2f..fdc9670045e 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -21,6 +21,7 @@ payouts = ["common_enums/payouts"]
v1 = []
v2 = []
customer_v2 = []
+payment_methods_v2 = []
[dependencies]
async-trait = { version = "0.1.79", optional = true }
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index 1e752a0f9b9..16d0fd9b30a 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -27,6 +27,8 @@ pub enum ApiEventsType {
payment_method: Option<PaymentMethod>,
payment_method_type: Option<PaymentMethodType>,
},
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ PaymentMethodCreate,
#[cfg(all(feature = "v2", feature = "customer_v2"))]
Customer {
id: String,
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs
index 14738811835..20dc423310a 100644
--- a/crates/common_utils/src/id_type.rs
+++ b/crates/common_utils/src/id_type.rs
@@ -12,6 +12,8 @@ mod profile;
mod routing;
mod global_id;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+mod payment_methods;
pub use customer::CustomerId;
use diesel::{
@@ -25,6 +27,8 @@ pub use merchant::MerchantId;
pub use merchant_connector_account::MerchantConnectorAccountId;
pub use organization::OrganizationId;
pub use payment::PaymentId;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub use payment_methods::GlobalPaymentMethodId;
pub use profile::ProfileId;
pub use routing::RoutingId;
use serde::{Deserialize, Serialize};
diff --git a/crates/common_utils/src/id_type/global_id.rs b/crates/common_utils/src/id_type/global_id.rs
index f04bfc3f92b..8efbc3636f9 100644
--- a/crates/common_utils/src/id_type/global_id.rs
+++ b/crates/common_utils/src/id_type/global_id.rs
@@ -21,6 +21,7 @@ pub(crate) struct GlobalId(LengthId<MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH>)
pub(crate) enum GlobalEntity {
Customer,
Payment,
+ PaymentMethod,
}
impl GlobalEntity {
@@ -28,6 +29,7 @@ impl GlobalEntity {
match self {
Self::Customer => "cus",
Self::Payment => "pay",
+ Self::PaymentMethod => "pm",
}
}
}
diff --git a/crates/common_utils/src/id_type/payment_methods.rs b/crates/common_utils/src/id_type/payment_methods.rs
new file mode 100644
index 00000000000..f5cc2150913
--- /dev/null
+++ b/crates/common_utils/src/id_type/payment_methods.rs
@@ -0,0 +1,85 @@
+use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types};
+use error_stack::ResultExt;
+
+use crate::{
+ errors,
+ errors::CustomResult,
+ id_type::global_id::{CellId, GlobalEntity, GlobalId, GlobalIdError},
+};
+
+#[derive(
+ Debug,
+ Clone,
+ Hash,
+ PartialEq,
+ Eq,
+ serde::Serialize,
+ serde::Deserialize,
+ diesel::expression::AsExpression,
+)]
+#[diesel(sql_type = diesel::sql_types::Text)]
+pub struct GlobalPaymentMethodId(GlobalId);
+
+#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
+pub enum GlobalPaymentMethodIdError {
+ #[error("Failed to construct GlobalPaymentMethodId")]
+ ConstructionError,
+}
+
+impl GlobalPaymentMethodId {
+ fn get_global_id(&self) -> &GlobalId {
+ &self.0
+ }
+ /// Create a new GlobalPaymentMethodId from celll id information
+ pub fn generate(cell_id: &str) -> error_stack::Result<Self, errors::ValidationError> {
+ let cell_id = CellId::from_string(cell_id.to_string())?;
+ let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod);
+ Ok(Self(global_id))
+ }
+
+ pub fn get_string_repr(&self) -> String {
+ todo!()
+ }
+
+ pub fn generate_from_string(value: String) -> CustomResult<Self, GlobalPaymentMethodIdError> {
+ let id = GlobalId::from_string(value)
+ .change_context(GlobalPaymentMethodIdError::ConstructionError)?;
+ Ok(Self(id))
+ }
+}
+
+impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodId
+where
+ DB: diesel::backend::Backend,
+ Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
+{
+ type Row = Self;
+ fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
+ Ok(row)
+ }
+}
+
+impl<DB> ToSql<sql_types::Text, DB> for GlobalPaymentMethodId
+where
+ DB: Backend,
+ GlobalId: ToSql<sql_types::Text, DB>,
+{
+ fn to_sql<'b>(
+ &'b self,
+ out: &mut diesel::serialize::Output<'b, '_, DB>,
+ ) -> diesel::serialize::Result {
+ let id = self.get_global_id();
+ id.to_sql(out)
+ }
+}
+
+impl<DB> FromSql<sql_types::Text, DB> for GlobalPaymentMethodId
+where
+ DB: Backend,
+ GlobalId: FromSql<sql_types::Text, DB>,
+{
+ fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
+ let global_id = GlobalId::from_sql(value)?;
+ Ok(Self(global_id))
+ }
+}
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index ca919eb15da..3ad58e62dcf 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -88,7 +88,7 @@ pub struct PaymentMethod {
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
- pub id: String,
+ pub id: common_utils::id_type::GlobalPaymentMethodId,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
@@ -105,7 +105,7 @@ impl PaymentMethod {
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
- pub fn get_id(&self) -> &String {
+ pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
@@ -179,7 +179,7 @@ pub struct PaymentMethodNew {
pub payment_method_billing_address: Option<Encryption>,
pub updated_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
- pub id: String,
+ pub id: common_utils::id_type::GlobalPaymentMethodId,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
@@ -200,7 +200,7 @@ impl PaymentMethodNew {
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
- pub fn get_id(&self) -> &String {
+ pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index 37c41c19dd9..321c7a6829c 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -211,7 +211,10 @@ impl PaymentMethod {
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl PaymentMethod {
- pub async fn find_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Self> {
+ pub async fn find_by_id(
+ conn: &PgPooledConn,
+ id: &common_utils::id_type::GlobalPaymentMethodId,
+ ) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, pm_id.eq(id.to_owned()))
.await
}
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs
index e7cbae9e88c..af3c657c34a 100644
--- a/crates/hyperswitch_domain_models/src/payment_methods.rs
+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs
@@ -77,7 +77,7 @@ pub struct PaymentMethod {
pub payment_method_billing_address: OptionalEncryptableValue,
pub updated_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
- pub id: String,
+ pub id: common_utils::id_type::GlobalPaymentMethodId,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
@@ -94,7 +94,7 @@ impl PaymentMethod {
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
- pub fn get_id(&self) -> &String {
+ pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId {
&self.id
}
}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 0c6e06cc42d..bae6243d2e6 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -37,7 +37,7 @@ v2 = ["customer_v2", "payment_methods_v2", "payment_v2", "common_default", "api_
v1 = ["common_default", "api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1"]
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2", "storage_impl/customer_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2", "storage_impl/payment_v2"]
-payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2"]
+payment_methods_v2 = ["api_models/payment_methods_v2", "diesel_models/payment_methods_v2", "hyperswitch_domain_models/payment_methods_v2", "storage_impl/payment_methods_v2", "common_utils/payment_methods_v2"]
# Partial Auth
# The feature reduces the overhead of the router authenticating the merchant for every request, and trusts on `x-merchant-id` header to be present in the request.
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 3d4a29e0f30..1f4fd00bbc5 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -135,3 +135,15 @@ pub const DEFAULT_UNIFIED_ERROR_MESSAGE: &str = "Something went wrong";
// Recon's feature tag
pub const RECON_FEATURE_TAG: &str = "RECONCILIATION AND SETTLEMENT";
+
+/// Vault Add request url
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const ADD_VAULT_REQUEST_URL: &str = "/vault/add";
+
+/// Vault Get Fingerprint request url
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/fingerprint";
+
+/// Vault Header content type
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json";
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index d8a28ebdf2e..c56bfaca913 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -148,6 +148,12 @@ pub enum VaultError {
SavePaymentMethodFailed,
#[error("Failed to generate fingerprint")]
GenerateFingerprintFailed,
+ #[error("Failed to encrypt vault request")]
+ RequestEncryptionFailed,
+ #[error("Failed to decrypt vault response")]
+ ResponseDecryptionFailed,
+ #[error("Failed to call vault")]
+ VaultAPIError,
#[error("Failed while calling locker API")]
ApiError,
}
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 72fbc3d3d4e..fa7ddfce997 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -21,9 +21,16 @@ use api_models::payment_methods;
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::ext_traits::Encode;
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-use common_utils::ext_traits::OptionExt;
use common_utils::{consts::DEFAULT_LOCALE, id_type::CustomerId};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use common_utils::{
+ crypto::{self, Encryptable},
+ ext_traits::{AsyncExt, Encode, ValueExt},
+ fp_utils::when,
+ generate_id, id_type,
+ request::RequestContent,
+ types as util_types,
+};
use diesel_models::{
enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData,
};
@@ -31,7 +38,11 @@ use error_stack::{report, ResultExt};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use masking::ExposeInterface;
use masking::PeekInterface;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use masking::Secret;
use router_env::{instrument, tracing};
use time::Duration;
@@ -39,11 +50,25 @@ use super::{
errors::{RouterResponse, StorageErrorExt},
pm_auth,
};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::{
+ configs::settings,
+ core::{payment_methods::transformers as pm_transforms, utils as core_utils},
+ headers, logger,
+ routes::payment_methods as pm_routes,
+ services::encryption,
+ types::{
+ api::{self, payment_methods::PaymentMethodCreateExt},
+ payment_methods as pm_types,
+ storage::PaymentMethodListContext,
+ },
+ utils::ext_traits::OptionExt,
+};
use crate::{
consts,
core::{
errors::{self, RouterResult},
- payments::helpers,
+ payments::helpers as payment_helpers,
},
routes::{app::StorageInterface, SessionState},
services,
@@ -67,7 +92,7 @@ pub async fn retrieve_payment_method(
) -> RouterResult<(Option<domain::PaymentMethodData>, Option<String>)> {
match pm_data {
pm_opt @ Some(pm @ domain::PaymentMethodData::Card(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -81,7 +106,7 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::BankDebit(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -104,7 +129,7 @@ pub async fn retrieve_payment_method(
pm @ Some(domain::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)),
pm_opt @ Some(pm @ domain::PaymentMethodData::BankTransfer(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -118,7 +143,7 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::Wallet(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -132,7 +157,7 @@ pub async fn retrieve_payment_method(
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::BankRedirect(_)) => {
- let payment_token = helpers::store_payment_method_data_in_vault(
+ let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
@@ -414,6 +439,10 @@ fn generate_task_id_for_payment_method_status_update_workflow(
format!("{runner}_{task}_{key_id}")
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn add_payment_method_status_update_task(
db: &dyn StorageInterface,
payment_method: &domain::PaymentMethod,
@@ -483,7 +512,10 @@ pub async fn retrieve_payment_method_with_token(
todo!()
}
-#[cfg(feature = "v1")]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_payment_method_with_token(
@@ -500,7 +532,7 @@ pub async fn retrieve_payment_method_with_token(
) -> RouterResult<storage::PaymentMethodDataWithId> {
let token = match token_data {
storage::PaymentTokenData::TemporaryGeneric(generic_token) => {
- helpers::retrieve_payment_method_with_temporary_token(
+ payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
@@ -519,7 +551,7 @@ pub async fn retrieve_payment_method_with_token(
}
storage::PaymentTokenData::Temporary(generic_token) => {
- helpers::retrieve_payment_method_with_temporary_token(
+ payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
@@ -538,7 +570,7 @@ pub async fn retrieve_payment_method_with_token(
}
storage::PaymentTokenData::Permanent(card_token) => {
- helpers::retrieve_card_with_permanent_token(
+ payment_helpers::retrieve_card_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
@@ -572,7 +604,7 @@ pub async fn retrieve_payment_method_with_token(
}
storage::PaymentTokenData::PermanentCard(card_token) => {
- helpers::retrieve_card_with_permanent_token(
+ payment_helpers::retrieve_card_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
@@ -793,3 +825,950 @@ pub(crate) async fn get_payment_method_create_request(
.attach_printable("PaymentMethodData required Or Card is already saved")),
}
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn create_payment_method(
+ state: &SessionState,
+ req: api::PaymentMethodCreate,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ req.validate()?;
+
+ let db = &*state.store;
+ let merchant_id = merchant_account.get_id();
+ let customer_id = req.customer_id.to_owned();
+
+ db.find_customer_by_merchant_reference_id_merchant_id(
+ &(state.into()),
+ &customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
+ .billing
+ .clone()
+ .async_map(|billing| cards::create_encrypted_data(state, key_store, billing))
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt Payment method billing address")?;
+
+ // create pm
+ let payment_method_id =
+ common_utils::id_type::GlobalPaymentMethodId::generate("random_cell_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,
+ key_store,
+ merchant_account.storage_scheme,
+ payment_method_billing_address.map(Into::into),
+ )
+ .await
+ .attach_printable("Failed to add Payment method to DB")?;
+
+ let vaulting_result =
+ vault_payment_method(state, &req.payment_method_data, merchant_account, key_store).await;
+
+ let response = match vaulting_result {
+ Ok(resp) => {
+ let pm_update = create_pm_additional_data_update(
+ &req.payment_method_data,
+ state,
+ key_store,
+ Some(resp.vault_id),
+ Some(req.payment_method),
+ Some(req.payment_method_type),
+ )
+ .await
+ .attach_printable("Unable to create Payment method data")?;
+
+ let payment_method = db
+ .update_payment_method(
+ &(state.into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ 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)?;
+
+ Ok(resp)
+ }
+ Err(e) => {
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(enums::PaymentMethodStatus::Inactive),
+ };
+
+ db.update_payment_method(
+ &(state.into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ Err(e)
+ }
+ }?;
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn payment_method_intent_create(
+ state: &SessionState,
+ req: api::PaymentMethodIntentCreate,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ let db = &*state.store;
+ let merchant_id = merchant_account.get_id();
+ let customer_id = req.customer_id.to_owned();
+
+ db.find_customer_by_merchant_reference_id_merchant_id(
+ &(state.into()),
+ &customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
+ .billing
+ .clone()
+ .async_map(|billing| cards::create_encrypted_data(state, key_store, billing))
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt Payment method billing address")?;
+
+ // create pm entry
+
+ let payment_method_id =
+ common_utils::id_type::GlobalPaymentMethodId::generate("random_cell_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,
+ key_store,
+ merchant_account.storage_scheme,
+ payment_method_billing_address.map(Into::into),
+ )
+ .await
+ .attach_printable("Failed to add Payment method to DB")?;
+
+ let resp = pm_transforms::generate_payment_method_response(&payment_method)?;
+
+ Ok(services::ApplicationResponse::Json(resp))
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn payment_method_intent_confirm(
+ state: &SessionState,
+ req: api::PaymentMethodIntentConfirm,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ pm_id: String,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ req.validate()?;
+
+ let db = &*state.store;
+ let client_secret = req.client_secret.clone();
+ let pm_id = common_utils::id_type::GlobalPaymentMethodId::generate_from_string(pm_id)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
+ let payment_method = db
+ .find_payment_method(
+ &(state.into()),
+ &key_store,
+ &pm_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("Unable to find payment method")?;
+
+ when(
+ cards::authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?,
+ || Err(errors::ApiErrorResponse::ClientSecretExpired),
+ )?;
+
+ when(
+ payment_method.status != enums::PaymentMethodStatus::AwaitingData,
+ || {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid pm_id provided: This Payment method cannot be confirmed"
+ .to_string(),
+ })
+ },
+ )?;
+
+ let customer_id = payment_method.customer_id.to_owned();
+ db.find_customer_by_merchant_reference_id_merchant_id(
+ &(state.into()),
+ &customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let vaulting_result =
+ vault_payment_method(state, &req.payment_method_data, merchant_account, key_store).await;
+
+ let response = match vaulting_result {
+ Ok(resp) => {
+ let pm_update = create_pm_additional_data_update(
+ &req.payment_method_data,
+ state,
+ key_store,
+ Some(resp.vault_id),
+ Some(req.payment_method),
+ Some(req.payment_method_type),
+ )
+ .await
+ .attach_printable("Unable to create Payment method data")?;
+
+ let payment_method = db
+ .update_payment_method(
+ &(state.into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ 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)?;
+
+ Ok(resp)
+ }
+ Err(e) => {
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(enums::PaymentMethodStatus::Inactive),
+ };
+
+ db.update_payment_method(
+ &(state.into()),
+ &key_store,
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ Err(e)
+ }
+ }?;
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+pub async fn create_payment_method_in_db(
+ state: &SessionState,
+ req: &api::PaymentMethodCreate,
+ customer_id: &id_type::CustomerId,
+ payment_method_id: id_type::GlobalPaymentMethodId,
+ locker_id: Option<String>,
+ merchant_id: &id_type::MerchantId,
+ pm_metadata: Option<common_utils::pii::SecretSerdeValue>,
+ customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
+ payment_method_data: crypto::OptionalEncryptableValue,
+ key_store: &domain::MerchantKeyStore,
+ connector_mandate_details: Option<common_utils::pii::SecretSerdeValue>,
+ status: Option<enums::PaymentMethodStatus>,
+ network_transaction_id: Option<String>,
+ storage_scheme: enums::MerchantStorageScheme,
+ payment_method_billing_address: crypto::OptionalEncryptableValue,
+ card_scheme: Option<String>,
+) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
+ let db = &*state.store;
+ let client_secret = pm_types::PaymentMethodClientSecret::generate(&payment_method_id);
+ 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,
+ payment_method: Some(req.payment_method),
+ payment_method_type: Some(req.payment_method_type),
+ metadata: pm_metadata,
+ payment_method_data,
+ connector_mandate_details,
+ customer_acceptance,
+ client_secret: Some(client_secret),
+ status: status.unwrap_or(enums::PaymentMethodStatus::Active),
+ network_transaction_id: network_transaction_id.to_owned(),
+ created_at: current_time,
+ last_modified: current_time,
+ last_used_at: current_time,
+ payment_method_billing_address,
+ updated_by: None,
+ version: domain::consts::API_VERSION,
+ locker_fingerprint_id: None,
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ network_token_requestor_reference_id: None,
+ },
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
+
+ Ok(response)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_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::CustomerId,
+ payment_method_id: id_type::GlobalPaymentMethodId,
+ merchant_id: &id_type::MerchantId,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: enums::MerchantStorageScheme,
+ payment_method_billing_address: crypto::OptionalEncryptableValue,
+) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
+ let db = &*state.store;
+ let client_secret = pm_types::PaymentMethodClientSecret::generate(&payment_method_id);
+ 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: None,
+ payment_method_type: None,
+ metadata,
+ payment_method_data: None,
+ connector_mandate_details: None,
+ customer_acceptance: None,
+ client_secret: Some(client_secret),
+ 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: domain::consts::API_VERSION,
+ locker_fingerprint_id: None,
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ network_token_requestor_reference_id: None,
+ },
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
+
+ Ok(response)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn create_pm_additional_data_update(
+ pmd: &api::PaymentMethodCreateData,
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ vault_id: Option<String>,
+ payment_method: Option<api_enums::PaymentMethod>,
+ payment_method_type: Option<api_enums::PaymentMethodType>,
+) -> errors::RouterResult<storage::PaymentMethodUpdate> {
+ let card = match pmd.clone() {
+ api::PaymentMethodCreateData::Card(card) => api::PaymentMethodsData::Card(card.into()),
+ };
+
+ let pmd: Encryptable<Secret<serde_json::Value>> =
+ cards::create_encrypted_data(state, key_store, card)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to encrypt Payment method data")?;
+
+ let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {
+ status: Some(enums::PaymentMethodStatus::Active),
+ locker_id: vault_id,
+ payment_method,
+ payment_method_type,
+ payment_method_data: Some(pmd).map(Into::into),
+ network_token_requestor_reference_id: None,
+ network_token_locker_id: None,
+ network_token_payment_method_data: None,
+ };
+
+ Ok(pm_update)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn vault_payment_method(
+ state: &SessionState,
+ pmd: &api::PaymentMethodCreateData,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResult<pm_types::AddVaultResponse> {
+ let db = &*state.store;
+
+ // get fingerprint_id from locker
+ let fingerprint_id_from_locker = cards::get_fingerprint_id_from_locker(state, pmd)
+ .await
+ .attach_printable("Failed to get fingerprint_id from vault")?;
+
+ // throw back error if payment method is duplicated
+ when(
+ Some(
+ db.find_payment_method_by_fingerprint_id(
+ &(state.into()),
+ key_store,
+ &fingerprint_id_from_locker,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to find payment method by fingerprint_id")?,
+ )
+ .is_some(),
+ || {
+ Err(report!(errors::ApiErrorResponse::DuplicatePaymentMethod)
+ .attach_printable("Cannot vault duplicate payment method"))
+ },
+ )?;
+
+ let resp_from_locker =
+ cards::vault_payment_method_in_locker(state, merchant_account, pmd).await?;
+
+ Ok(resp_from_locker)
+}
+
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+async fn get_pm_list_context(
+ state: &SessionState,
+ payment_method: &enums::PaymentMethod,
+ _key_store: &domain::MerchantKeyStore,
+ pm: &domain::PaymentMethod,
+ _parent_payment_method_token: Option<String>,
+ is_payment_associated: bool,
+) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
+ let payment_method_retrieval_context = match payment_method {
+ enums::PaymentMethod::Card => {
+ let card_details = cards::get_card_details_with_locker_fallback(pm, state).await?;
+
+ card_details.as_ref().map(|card| PaymentMethodListContext {
+ card_details: Some(card.clone()),
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated.then_some(
+ storage::PaymentTokenData::permanent_card(
+ Some(pm.get_id().clone()),
+ pm.locker_id.clone().or(Some(pm.get_id().get_string_repr())),
+ pm.locker_id
+ .clone()
+ .unwrap_or(pm.get_id().get_string_repr()),
+ ),
+ ),
+ })
+ }
+
+ enums::PaymentMethod::BankDebit => {
+ // Retrieve the pm_auth connector details so that it can be tokenized
+ let bank_account_token_data = cards::get_bank_account_connector_details(pm)
+ .await
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ });
+
+ bank_account_token_data.map(|data| {
+ let token_data = storage::PaymentTokenData::AuthBankDebit(data);
+
+ PaymentMethodListContext {
+ card_details: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated.then_some(token_data),
+ }
+ })
+ }
+
+ _ => Some(PaymentMethodListContext {
+ card_details: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated.then_some(
+ storage::PaymentTokenData::temporary_generic(generate_id(
+ consts::ID_LENGTH,
+ "token",
+ )),
+ ),
+ }),
+ };
+
+ Ok(payment_method_retrieval_context)
+}
+
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+pub async fn list_customer_payment_method_util(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ req: Option<api::PaymentMethodListRequest>,
+ customer_id: Option<id_type::CustomerId>,
+ is_payment_associated: bool,
+) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
+ let limit = req.as_ref().and_then(|pml_req| pml_req.limit);
+
+ let (customer_id, payment_intent) = if is_payment_associated {
+ let cloned_secret = req.and_then(|r| r.client_secret.clone());
+ let payment_intent = payment_helpers::verify_payment_intent_time_and_client_secret(
+ &state,
+ &merchant_account,
+ &key_store,
+ cloned_secret,
+ )
+ .await?;
+
+ (
+ payment_intent
+ .as_ref()
+ .and_then(|pi| pi.customer_id.clone()),
+ payment_intent,
+ )
+ } else {
+ (customer_id, None)
+ };
+
+ let resp = if let Some(cust) = customer_id {
+ Box::pin(list_customer_payment_method(
+ &state,
+ merchant_account,
+ key_store,
+ payment_intent,
+ &cust,
+ limit,
+ is_payment_associated,
+ ))
+ .await?
+ } else {
+ let response = api::CustomerPaymentMethodsListResponse {
+ customer_payment_methods: Vec::new(),
+ is_guest_customer: Some(true),
+ };
+ services::ApplicationResponse::Json(response)
+ };
+
+ Ok(resp)
+}
+
+#[cfg(all(
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "customer_v2"
+))]
+pub async fn list_customer_payment_method(
+ state: &SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ payment_intent: Option<storage::PaymentIntent>,
+ customer_id: &id_type::CustomerId,
+ limit: Option<i64>,
+ is_payment_associated: bool,
+) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
+ let db = &*state.store;
+ let key_manager_state = &(state).into();
+ // let key = key_store.key.get_inner().peek();
+
+ let customer = db
+ .find_customer_by_merchant_reference_id_merchant_id(
+ key_manager_state,
+ customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let payments_info = payment_intent
+ .async_map(|pi| {
+ pm_types::SavedPMLPaymentsInfo::form_payments_info(
+ pi,
+ &merchant_account,
+ db,
+ key_manager_state,
+ &key_store,
+ )
+ })
+ .await
+ .transpose()?;
+
+ let saved_payment_methods = db
+ .find_payment_method_by_customer_id_merchant_id_status(
+ key_manager_state,
+ &key_store,
+ customer_id,
+ merchant_account.get_id(),
+ common_enums::PaymentMethodStatus::Active,
+ limit,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ let mut filtered_saved_payment_methods_ctx = Vec::new();
+ for pm in saved_payment_methods.into_iter() {
+ let payment_method = pm.payment_method.get_required_value("payment_method")?;
+ let parent_payment_method_token =
+ is_payment_associated.then(|| generate_id(consts::ID_LENGTH, "token"));
+
+ let pm_list_context = get_pm_list_context(
+ state,
+ &payment_method,
+ &key_store,
+ &pm,
+ parent_payment_method_token.clone(),
+ is_payment_associated,
+ )
+ .await?;
+
+ if let Some(ctx) = pm_list_context {
+ filtered_saved_payment_methods_ctx.push((ctx, parent_payment_method_token, pm));
+ }
+ }
+
+ let pm_list_futures = filtered_saved_payment_methods_ctx
+ .into_iter()
+ .map(|ctx| {
+ generate_saved_pm_response(
+ state,
+ &key_store,
+ &merchant_account,
+ ctx,
+ &customer,
+ payments_info.as_ref(),
+ )
+ })
+ .collect::<Vec<_>>();
+
+ let final_result = futures::future::join_all(pm_list_futures).await;
+
+ let mut customer_pms = Vec::new();
+ for result in final_result.into_iter() {
+ let pma = result.attach_printable("saved pm list failed")?;
+ customer_pms.push(pma);
+ }
+
+ let mut response = api::CustomerPaymentMethodsListResponse {
+ customer_payment_methods: customer_pms,
+ is_guest_customer: is_payment_associated.then_some(false), //to return this key only when the request is tied to a payment intent
+ };
+
+ if is_payment_associated {
+ Box::pin(cards::perform_surcharge_ops(
+ payments_info.as_ref().map(|pi| pi.payment_intent.clone()),
+ state,
+ merchant_account,
+ key_store,
+ payments_info.and_then(|pi| pi.business_profile),
+ &mut response,
+ ))
+ .await?;
+ }
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+async fn generate_saved_pm_response(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ merchant_account: &domain::MerchantAccount,
+ pm_list_context: (
+ PaymentMethodListContext,
+ Option<String>,
+ domain::PaymentMethod,
+ ),
+ customer: &domain::Customer,
+ payment_info: Option<&pm_types::SavedPMLPaymentsInfo>,
+) -> Result<api::CustomerPaymentMethod, error_stack::Report<errors::ApiErrorResponse>> {
+ let (pm_list_context, parent_payment_method_token, pm) = pm_list_context;
+ let payment_method = pm.payment_method.get_required_value("payment_method")?;
+
+ let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
+ cards::get_masked_bank_details(&pm)
+ .await
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ })
+ } else {
+ None
+ };
+
+ let payment_method_billing = pm
+ .payment_method_billing_address
+ .clone()
+ .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 details")?;
+
+ let connector_mandate_details = pm
+ .connector_mandate_details
+ .clone()
+ .map(|val| val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
+
+ let (is_connector_agnostic_mit_enabled, requires_cvv, off_session_payment_flag, profile_id) =
+ payment_info
+ .map(|pi| {
+ (
+ pi.is_connector_agnostic_mit_enabled,
+ pi.requires_cvv,
+ pi.off_session_payment_flag,
+ pi.business_profile
+ .as_ref()
+ .map(|profile| profile.get_id().to_owned()),
+ )
+ })
+ .unwrap_or((false, false, false, Default::default()));
+
+ let mca_enabled = cards::get_mca_status(
+ state,
+ key_store,
+ profile_id,
+ merchant_account.get_id(),
+ is_connector_agnostic_mit_enabled,
+ connector_mandate_details,
+ pm.network_transaction_id.as_ref(),
+ )
+ .await?;
+
+ let requires_cvv = if is_connector_agnostic_mit_enabled {
+ requires_cvv
+ && !(off_session_payment_flag
+ && (pm.connector_mandate_details.is_some() || pm.network_transaction_id.is_some()))
+ } else {
+ requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some())
+ };
+
+ let pmd = if let Some(card) = pm_list_context.card_details.as_ref() {
+ Some(api::PaymentMethodListData::Card(card.clone()))
+ } else if cfg!(feature = "payouts") {
+ pm_list_context
+ .bank_transfer_details
+ .clone()
+ .map(api::PaymentMethodListData::Bank)
+ } else {
+ None
+ };
+
+ let pma = api::CustomerPaymentMethod {
+ payment_token: parent_payment_method_token.clone(),
+ payment_method_id: pm.get_id().get_string_repr(),
+ customer_id: pm.customer_id.to_owned(),
+ payment_method,
+ payment_method_type: pm.payment_method_type,
+ payment_method_data: pmd,
+ metadata: pm.metadata.clone(),
+ recurring_enabled: mca_enabled,
+ created: Some(pm.created_at),
+ bank: bank_details,
+ surcharge_details: None,
+ requires_cvv: requires_cvv
+ && !(off_session_payment_flag && pm.connector_mandate_details.is_some()),
+ last_used_at: Some(pm.last_used_at),
+ is_default: customer.default_payment_method_id.is_some()
+ && customer.default_payment_method_id.as_ref() == Some(&pm.get_id().get_string_repr()),
+ billing: payment_method_billing,
+ };
+
+ payment_info
+ .async_map(|pi| {
+ pi.perform_payment_ops(state, parent_payment_method_token, &pma, pm_list_context)
+ })
+ .await
+ .transpose()?;
+
+ Ok(pma)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl pm_types::SavedPMLPaymentsInfo {
+ pub async fn form_payments_info(
+ payment_intent: storage::PaymentIntent,
+ merchant_account: &domain::MerchantAccount,
+ db: &dyn StorageInterface,
+ key_manager_state: &util_types::keymanager::KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ ) -> errors::RouterResult<Self> {
+ let requires_cvv = db
+ .find_config_by_key_unwrap_or(
+ format!(
+ "{}_requires_cvv",
+ merchant_account.get_id().get_string_repr()
+ )
+ .as_str(),
+ Some("true".to_string()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch requires_cvv config")?
+ .config
+ != "false";
+
+ let off_session_payment_flag = matches!(
+ payment_intent.setup_future_usage,
+ Some(common_enums::FutureUsage::OffSession)
+ );
+
+ 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 business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ key_manager_state,
+ key_store,
+ Some(profile_id).as_ref(),
+ merchant_account.get_id(),
+ )
+ .await?;
+
+ let is_connector_agnostic_mit_enabled = business_profile
+ .as_ref()
+ .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled)
+ .unwrap_or(false);
+
+ Ok(Self {
+ payment_intent,
+ business_profile,
+ requires_cvv,
+ 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::CustomerPaymentMethod,
+ pm_list_context: PaymentMethodListContext,
+ ) -> errors::RouterResult<()> {
+ let token = parent_payment_method_token
+ .as_ref()
+ .get_required_value("parent_payment_method_token")?;
+ let hyperswitch_token_data = pm_list_context
+ .hyperswitch_token_data
+ .get_required_value("PaymentTokenData")?;
+
+ let intent_fulfillment_time = self
+ .business_profile
+ .as_ref()
+ .and_then(|b_profile| b_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))
+ .insert(intent_fulfillment_time, hyperswitch_token_data, state)
+ .await?;
+
+ if let Some(metadata) = pma.metadata.clone() {
+ let pm_metadata_vec: pm_transforms::PaymentMethodMetadata = metadata
+ .parse_value("PaymentMethodMetadata")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to deserialize metadata to PaymentmethodMetadata struct",
+ )?;
+
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ for pm_metadata in pm_metadata_vec.payment_method_tokenization {
+ let key = format!(
+ "pm_token_{}_{}_{}",
+ token, pma.payment_method, pm_metadata.0
+ );
+
+ redis_conn
+ .set_key_with_expiry(&key, pm_metadata.1, intent_fulfillment_time)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add data in redis")?;
+ }
+ }
+
+ Ok(())
+ }
+}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 22350f77e69..79d1226f13a 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -69,8 +69,6 @@ use super::surcharge_decision_configs::{
use crate::routes::app::SessionStateInfo;
#[cfg(feature = "payouts")]
use crate::types::domain::types::AsyncLift;
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-use crate::utils::{self};
use crate::{
configs::{
defaults::{get_billing_required_fields, get_shipping_required_fields},
@@ -95,8 +93,14 @@ use crate::{
storage::{self, enums, PaymentMethodListContext, PaymentTokenData},
transformers::ForeignTryFrom,
},
+ utils,
utils::OptionExt,
};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::{
+ consts as router_consts, core::payment_methods as pm_core, headers,
+ types::payment_methods as pm_types, utils::ConnectorResponseExt,
+};
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -217,32 +221,35 @@ pub async fn create_payment_method(
Ok(response)
}
-#[cfg(all(
- feature = "v2",
- feature = "payment_methods_v2",
- feature = "customer_v2"
-))]
-#[instrument(skip_all)]
-#[allow(clippy::too_many_arguments)]
-pub async fn create_payment_method(
- _state: &routes::SessionState,
- _req: &api::PaymentMethodCreate,
- _customer_id: &id_type::CustomerId,
- _payment_method_id: &str,
- _locker_id: Option<String>,
- _merchant_id: &id_type::MerchantId,
- _pm_metadata: Option<serde_json::Value>,
- _customer_acceptance: Option<serde_json::Value>,
- _payment_method_data: Option<Encryption>,
- _key_store: &domain::MerchantKeyStore,
- _connector_mandate_details: Option<serde_json::Value>,
- _status: Option<enums::PaymentMethodStatus>,
- _network_transaction_id: Option<String>,
- _storage_scheme: MerchantStorageScheme,
- _payment_method_billing_address: Option<Encryption>,
- _card_scheme: Option<String>,
-) -> errors::CustomResult<domain::PaymentMethod, errors::ApiErrorResponse> {
- todo!()
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+async fn create_vault_request<R: pm_types::VaultingInterface>(
+ jwekey: &settings::Jwekey,
+ locker: &settings::Locker,
+ payload: Vec<u8>,
+) -> errors::CustomResult<services::Request, errors::VaultError> {
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
+
+ let jws = services::encryption::jws_sign_payload(
+ &payload,
+ &locker.locker_signing_key_id,
+ private_key,
+ )
+ .await
+ .change_context(errors::VaultError::RequestEncryptionFailed)?;
+
+ let jwe_payload = payment_methods::create_jwe_body_for_vault(jwekey, &jws).await?;
+
+ let mut url = locker.host.to_owned();
+ url.push_str(R::get_vaulting_request_url());
+ let mut request = services::Request::new(services::Method::Post, &url);
+ request.add_header(
+ headers::CONTENT_TYPE,
+ router_consts::VAULT_HEADER_CONTENT_TYPE.into(),
+ );
+ request.set_body(common_utils::request::RequestContent::Json(Box::new(
+ jwe_payload,
+ )));
+ Ok(request)
}
#[cfg(all(
@@ -911,17 +918,6 @@ pub async fn get_client_secret_or_add_payment_method(
}
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-#[instrument(skip_all)]
-pub async fn get_client_secret_or_add_payment_method(
- _state: &routes::SessionState,
- _req: api::PaymentMethodCreate,
- _merchant_account: &domain::MerchantAccount,
- _key_store: &domain::MerchantKeyStore,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
- todo!()
-}
-
#[instrument(skip_all)]
pub fn authenticate_pm_client_secret_and_check_expiry(
req_client_secret: &String,
@@ -1417,13 +1413,64 @@ pub async fn add_payment_method(
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
-pub async fn add_payment_method(
- _state: &routes::SessionState,
- _req: api::PaymentMethodCreate,
- _merchant_account: &domain::MerchantAccount,
- _key_store: &domain::MerchantKeyStore,
-) -> errors::RouterResponse<api::PaymentMethodResponse> {
- todo!()
+pub async fn get_fingerprint_id_from_locker<
+ D: pm_types::VaultingDataInterface + serde::Serialize,
+>(
+ state: &routes::SessionState,
+ data: &D,
+) -> errors::RouterResult<String> {
+ let key = data.get_vaulting_data_key();
+ let data = serde_json::to_value(data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode Vaulting data to value")?
+ .to_string();
+
+ let payload = pm_types::VaultFingerprintRequest { key, data }
+ .encode_to_vec()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode VaultFingerprintRequest")?;
+
+ let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get response from locker")?;
+
+ let fingerprint_resp: pm_types::VaultFingerprintResponse = resp
+ .parse_struct("VaultFingerprintResp")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse data into VaultFingerprintResp")?;
+
+ Ok(fingerprint_resp.fingerprint_id)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn vault_payment_method_in_locker(
+ state: &routes::SessionState,
+ merchant_account: &domain::MerchantAccount,
+ pmd: &api::PaymentMethodCreateData,
+) -> errors::RouterResult<pm_types::AddVaultResponse> {
+ let payload = pm_types::AddVaultRequest {
+ entity_id: merchant_account.get_id().to_owned(),
+ vault_id: uuid::Uuid::now_v7().to_string(),
+ data: pmd.clone(),
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
+ }
+ .encode_to_vec()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode AddVaultRequest")?;
+
+ let resp = call_to_vault::<pm_types::AddVault>(state, payload)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get response from locker")?;
+
+ let stored_pm_resp: pm_types::AddVaultResponse = resp
+ .parse_struct("AddVaultResponse")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse data into AddVaultResponse")?;
+
+ Ok(stored_pm_resp)
}
#[cfg(all(
@@ -1506,40 +1553,7 @@ pub async fn insert_payment_method(
storage_scheme: MerchantStorageScheme,
payment_method_billing_address: Option<Encryption>,
) -> errors::RouterResult<domain::PaymentMethod> {
- let pm_card_details = match &resp.payment_method_data {
- Some(api::PaymentMethodResponseData::Card(card_data)) => Some(PaymentMethodsData::Card(
- CardDetailsPaymentMethod::from(card_data.clone()),
- )),
- _ => None,
- };
-
- let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_card_details
- .clone()
- .async_map(|pm_card| create_encrypted_data(state, key_store, pm_card))
- .await
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to encrypt payment method data")?;
-
- create_payment_method(
- state,
- req,
- customer_id,
- &resp.payment_method_id,
- locker_id,
- merchant_id,
- pm_metadata,
- customer_acceptance,
- pm_data_encrypted.map(Into::into),
- key_store,
- connector_mandate_details,
- None,
- network_transaction_id,
- storage_scheme,
- payment_method_billing_address,
- None,
- )
- .await
+ todo!()
}
#[cfg(all(
@@ -2225,6 +2239,37 @@ pub async fn add_card_to_hs_locker(
Ok(stored_card)
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all)]
+pub async fn call_to_vault<V: pm_types::VaultingInterface>(
+ state: &routes::SessionState,
+ payload: Vec<u8>,
+) -> errors::CustomResult<String, errors::VaultError> {
+ let locker = &state.conf.locker;
+ let jwekey = state.conf.jwekey.get_inner();
+
+ let request = create_vault_request::<V>(jwekey, locker, payload).await?;
+ let response = services::call_connector_api(state, request, "vault_in_locker")
+ .await
+ .change_context(errors::VaultError::VaultAPIError);
+
+ let jwe_body: services::JweBody = response
+ .get_response_inner("JweBody")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)
+ .attach_printable("Failed to get JweBody from vault response")?;
+
+ let decrypted_payload = payment_methods::get_decrypted_vault_response_payload(
+ jwekey,
+ jwe_body,
+ locker.decryption_scheme.clone(),
+ )
+ .await
+ .change_context(errors::VaultError::ResponseDecryptionFailed)
+ .attach_printable("Error getting decrypted vault response payload")?;
+
+ Ok(decrypted_payload)
+}
+
#[instrument(skip_all)]
pub async fn call_locker_api<T>(
state: &routes::SessionState,
@@ -3819,6 +3864,10 @@ fn should_collect_shipping_or_billing_details_from_wallet_connector(
}
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2"),
+))]
async fn validate_payment_method_and_client_secret(
state: &routes::SessionState,
cs: &String,
@@ -4235,63 +4284,6 @@ fn filter_recurring_based(
recurring_enabled.map_or(true, |enabled| payment_method.recurring_enabled == enabled)
}
-#[cfg(all(
- feature = "v2",
- feature = "payment_methods_v2",
- feature = "customer_v2"
-))]
-pub async fn list_customer_payment_method_util(
- state: routes::SessionState,
- merchant_account: domain::MerchantAccount,
- key_store: domain::MerchantKeyStore,
- req: Option<api::PaymentMethodListRequest>,
- customer_id: Option<id_type::CustomerId>,
- is_payment_associated: bool,
-) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
- let limit = req.as_ref().and_then(|pml_req| pml_req.limit);
-
- let (customer_id, payment_intent) = if is_payment_associated {
- let cloned_secret = req.and_then(|r| r.client_secret.clone());
- let payment_intent = helpers::verify_payment_intent_time_and_client_secret(
- &state,
- &merchant_account,
- &key_store,
- cloned_secret,
- )
- .await?;
-
- (
- payment_intent
- .as_ref()
- .and_then(|pi| pi.customer_id.clone()),
- payment_intent,
- )
- } else {
- (customer_id, None)
- };
-
- let resp = if let Some(cust) = customer_id {
- Box::pin(list_customer_payment_method(
- &state,
- merchant_account,
- key_store,
- payment_intent,
- &cust,
- limit,
- is_payment_associated,
- ))
- .await?
- } else {
- let response = api::CustomerPaymentMethodsListResponse {
- customer_payment_methods: Vec::new(),
- is_guest_customer: Some(true),
- };
- services::ApplicationResponse::Json(response)
- };
-
- Ok(resp)
-}
-
#[cfg(all(
any(feature = "v2", feature = "v1"),
not(feature = "payment_methods_v2"),
@@ -4615,6 +4607,11 @@ pub async fn list_customer_payment_method(
Ok(services::ApplicationResponse::Json(response))
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2"),
+ not(feature = "customer_v2")
+))]
async fn get_pm_list_context(
state: &routes::SessionState,
payment_method: &enums::PaymentMethod,
@@ -4706,7 +4703,11 @@ async fn get_pm_list_context(
Ok(payment_method_retrieval_context)
}
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_v2"),
+ not(feature = "payment_methods_v2")
+))]
async fn perform_surcharge_ops(
payment_intent: Option<storage::PaymentIntent>,
state: &routes::SessionState,
@@ -4751,8 +4752,8 @@ async fn perform_surcharge_ops(
Ok(())
}
-#[cfg(all(feature = "v2", feature = "payment_v2"))]
-async fn perform_surcharge_ops(
+#[cfg(all(feature = "v2", feature = "payment_v2", feature = "payment_methods_v2"))]
+pub async fn perform_surcharge_ops(
_payment_intent: Option<storage::PaymentIntent>,
_state: &routes::SessionState,
_merchant_account: domain::MerchantAccount,
@@ -4763,370 +4764,6 @@ async fn perform_surcharge_ops(
todo!()
}
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-struct SavedPMLPaymentsInfo {
- pub payment_intent: storage::PaymentIntent,
- pub business_profile: Option<BusinessProfile>,
- pub requires_cvv: bool,
- pub off_session_payment_flag: bool,
- pub is_connector_agnostic_mit_enabled: bool,
-}
-
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-impl SavedPMLPaymentsInfo {
- pub async fn form_payments_info(
- payment_intent: storage::PaymentIntent,
- merchant_account: &domain::MerchantAccount,
- db: &dyn db::StorageInterface,
- key_manager_state: &KeyManagerState,
- key_store: &domain::MerchantKeyStore,
- ) -> errors::RouterResult<Self> {
- let requires_cvv = db
- .find_config_by_key_unwrap_or(
- format!(
- "{}_requires_cvv",
- merchant_account.get_id().get_string_repr()
- )
- .as_str(),
- Some("true".to_string()),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch requires_cvv config")?
- .config
- != "false";
-
- let off_session_payment_flag = matches!(
- payment_intent.setup_future_usage,
- Some(common_enums::FutureUsage::OffSession)
- );
-
- 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 business_profile = core_utils::validate_and_get_business_profile(
- db,
- key_manager_state,
- key_store,
- Some(profile_id).as_ref(),
- merchant_account.get_id(),
- )
- .await?;
-
- let is_connector_agnostic_mit_enabled = business_profile
- .as_ref()
- .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled)
- .unwrap_or(false);
-
- Ok(Self {
- payment_intent,
- business_profile,
- requires_cvv,
- off_session_payment_flag,
- is_connector_agnostic_mit_enabled,
- })
- }
-
- pub async fn perform_payment_ops(
- &self,
- state: &routes::SessionState,
- parent_payment_method_token: Option<String>,
- pma: &api::CustomerPaymentMethod,
- pm_list_context: PaymentMethodListContext,
- ) -> errors::RouterResult<()> {
- let token = parent_payment_method_token
- .as_ref()
- .get_required_value("parent_payment_method_token")?;
- let hyperswitch_token_data = pm_list_context
- .hyperswitch_token_data
- .get_required_value("PaymentTokenData")?;
-
- let intent_fulfillment_time = self
- .business_profile
- .as_ref()
- .and_then(|b_profile| b_profile.get_order_fulfillment_time())
- .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME);
-
- ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method))
- .insert(intent_fulfillment_time, hyperswitch_token_data, state)
- .await?;
-
- if let Some(metadata) = pma.metadata.clone() {
- let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata
- .parse_value("PaymentMethodMetadata")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(
- "Failed to deserialize metadata to PaymentmethodMetadata struct",
- )?;
-
- let redis_conn = state
- .store
- .get_redis_conn()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get redis connection")?;
-
- for pm_metadata in pm_metadata_vec.payment_method_tokenization {
- let key = format!(
- "pm_token_{}_{}_{}",
- token, pma.payment_method, pm_metadata.0
- );
-
- redis_conn
- .set_key_with_expiry(&key, pm_metadata.1, intent_fulfillment_time)
- .await
- .change_context(errors::StorageError::KVError)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to add data in redis")?;
- }
- }
-
- Ok(())
- }
-}
-
-#[cfg(all(
- feature = "v2",
- feature = "payment_methods_v2",
- feature = "customer_v2"
-))]
-pub async fn list_customer_payment_method(
- state: &routes::SessionState,
- merchant_account: domain::MerchantAccount,
- key_store: domain::MerchantKeyStore,
- payment_intent: Option<storage::PaymentIntent>,
- customer_id: &id_type::CustomerId,
- limit: Option<i64>,
- is_payment_associated: bool,
-) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
- let db = &*state.store;
- let key_manager_state = &(state).into();
- // let key = key_store.key.get_inner().peek();
-
- let customer = db
- .find_customer_by_merchant_reference_id_merchant_id(
- key_manager_state,
- customer_id,
- merchant_account.get_id(),
- &key_store,
- merchant_account.storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
-
- let payments_info = payment_intent
- .async_map(|pi| {
- SavedPMLPaymentsInfo::form_payments_info(
- pi,
- &merchant_account,
- db,
- key_manager_state,
- &key_store,
- )
- })
- .await
- .transpose()?;
-
- let saved_payment_methods = db
- .find_payment_method_by_customer_id_merchant_id_status(
- key_manager_state,
- &key_store,
- customer_id,
- merchant_account.get_id(),
- common_enums::PaymentMethodStatus::Active,
- limit,
- merchant_account.storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
-
- let mut filtered_saved_payment_methods_ctx = Vec::new();
- for pm in saved_payment_methods.into_iter() {
- logger::debug!(
- "Fetching payment method from locker for payment_method_id: {}",
- pm.id
- );
- let payment_method = pm.payment_method.get_required_value("payment_method")?;
- let parent_payment_method_token =
- is_payment_associated.then(|| generate_id(consts::ID_LENGTH, "token"));
-
- let pm_list_context = get_pm_list_context(
- state,
- &payment_method,
- &key_store,
- &pm,
- parent_payment_method_token.clone(),
- is_payment_associated,
- )
- .await?;
-
- if let Some(ctx) = pm_list_context {
- filtered_saved_payment_methods_ctx.push((ctx, parent_payment_method_token, pm));
- }
- }
-
- let pm_list_futures = filtered_saved_payment_methods_ctx
- .into_iter()
- .map(|ctx| {
- generate_saved_pm_response(
- state,
- &key_store,
- &merchant_account,
- ctx,
- &customer,
- payments_info.as_ref(),
- )
- })
- .collect::<Vec<_>>();
-
- let final_result = futures::future::join_all(pm_list_futures).await;
-
- let mut customer_pms = Vec::new();
- for result in final_result.into_iter() {
- let pma = result.attach_printable("saved pm list failed")?;
- customer_pms.push(pma);
- }
-
- let mut response = api::CustomerPaymentMethodsListResponse {
- customer_payment_methods: customer_pms,
- is_guest_customer: is_payment_associated.then_some(false), //to return this key only when the request is tied to a payment intent
- };
-
- if is_payment_associated {
- Box::pin(perform_surcharge_ops(
- payments_info.as_ref().map(|pi| pi.payment_intent.clone()),
- state,
- merchant_account,
- key_store,
- payments_info.and_then(|pi| pi.business_profile),
- &mut response,
- ))
- .await?;
- }
-
- Ok(services::ApplicationResponse::Json(response))
-}
-
-#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
-async fn generate_saved_pm_response(
- state: &routes::SessionState,
- key_store: &domain::MerchantKeyStore,
- merchant_account: &domain::MerchantAccount,
- pm_list_context: (
- PaymentMethodListContext,
- Option<String>,
- domain::PaymentMethod,
- ),
- customer: &domain::Customer,
- payment_info: Option<&SavedPMLPaymentsInfo>,
-) -> Result<api::CustomerPaymentMethod, error_stack::Report<errors::ApiErrorResponse>> {
- let (pm_list_context, parent_payment_method_token, pm) = pm_list_context;
- let payment_method = pm.payment_method.get_required_value("payment_method")?;
-
- let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
- get_masked_bank_details(&pm).await.unwrap_or_else(|err| {
- logger::error!(error=?err);
- None
- })
- } else {
- None
- };
-
- let payment_method_billing = pm
- .payment_method_billing_address
- .clone()
- .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 details")?;
-
- let connector_mandate_details = pm
- .connector_mandate_details
- .clone()
- .map(|val| val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
-
- let (is_connector_agnostic_mit_enabled, requires_cvv, off_session_payment_flag, profile_id) =
- payment_info
- .map(|pi| {
- (
- pi.is_connector_agnostic_mit_enabled,
- pi.requires_cvv,
- pi.off_session_payment_flag,
- pi.business_profile
- .as_ref()
- .map(|profile| profile.get_id().to_owned()),
- )
- })
- .unwrap_or((false, false, false, Default::default()));
-
- let mca_enabled = get_mca_status(
- state,
- key_store,
- profile_id,
- merchant_account.get_id(),
- is_connector_agnostic_mit_enabled,
- connector_mandate_details,
- pm.network_transaction_id.as_ref(),
- )
- .await?;
-
- let requires_cvv = if is_connector_agnostic_mit_enabled {
- requires_cvv
- && !(off_session_payment_flag
- && (pm.connector_mandate_details.is_some() || pm.network_transaction_id.is_some()))
- } else {
- requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some())
- };
-
- let pmd = if let Some(card) = pm_list_context.card_details.as_ref() {
- Some(api::PaymentMethodListData::Card(card.clone()))
- } else if cfg!(feature = "payouts") {
- pm_list_context
- .bank_transfer_details
- .clone()
- .map(api::PaymentMethodListData::Bank)
- } else {
- None
- };
-
- let pma = api::CustomerPaymentMethod {
- payment_token: parent_payment_method_token.clone(),
- payment_method_id: pm.get_id().clone(),
- customer_id: pm.customer_id.to_owned(),
- payment_method,
- payment_method_type: pm.payment_method_type,
- payment_method_data: pmd,
- metadata: pm.metadata.clone(),
- recurring_enabled: mca_enabled,
- created: Some(pm.created_at),
- bank: bank_details,
- surcharge_details: None,
- requires_cvv: requires_cvv
- && !(off_session_payment_flag && pm.connector_mandate_details.is_some()),
- last_used_at: Some(pm.last_used_at),
- is_default: customer.default_payment_method_id.is_some()
- && customer.default_payment_method_id.as_ref() == Some(pm.get_id()),
- billing: payment_method_billing,
- };
-
- payment_info
- .async_map(|pi| {
- pi.perform_payment_ops(state, parent_payment_method_token, &pma, pm_list_context)
- })
- .await
- .transpose()?;
-
- Ok(pma)
-}
-
pub async fn get_mca_status(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
@@ -5236,24 +4873,7 @@ pub async fn get_card_details_with_locker_fallback(
pm: &domain::PaymentMethod,
state: &routes::SessionState,
) -> errors::RouterResult<Option<api::CardDetailFromLocker>> {
- let card_decrypted = pm
- .payment_method_data
- .clone()
- .map(|x| x.into_inner().expose())
- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- });
-
- Ok(if let Some(crd) = card_decrypted {
- Some(crd)
- } else {
- logger::debug!(
- "Getting card details from locker as it is not found in payment methods table"
- );
- Some(get_card_details_from_locker(state, pm).await?)
- })
+ todo!()
}
#[cfg(all(
@@ -5290,25 +4910,13 @@ pub async fn get_card_details_without_locker_fallback(
pm: &domain::PaymentMethod,
state: &routes::SessionState,
) -> errors::RouterResult<api::CardDetailFromLocker> {
- let card_decrypted = pm
- .payment_method_data
- .clone()
- .map(|x| x.into_inner().expose())
- .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
- .and_then(|pmd| match pmd {
- PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
- _ => None,
- });
- Ok(if let Some(crd) = card_decrypted {
- crd
- } else {
- logger::debug!(
- "Getting card details from locker as it is not found in payment methods table"
- );
- get_card_details_from_locker(state, pm).await?
- })
+ todo!()
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn get_card_details_from_locker(
state: &routes::SessionState,
pm: &domain::PaymentMethod,
@@ -5328,6 +4936,10 @@ pub async fn get_card_details_from_locker(
.attach_printable("Get Card Details Failed")
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn get_lookup_key_from_locker(
state: &routes::SessionState,
payment_token: &str,
@@ -5348,7 +4960,7 @@ pub async fn get_lookup_key_from_locker(
Ok(resp)
}
-async fn get_masked_bank_details(
+pub async fn get_masked_bank_details(
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<MaskedBankDetails>> {
let payment_method_data = pm
@@ -5377,7 +4989,7 @@ async fn get_masked_bank_details(
}
}
-async fn get_bank_account_connector_details(
+pub async fn get_bank_account_connector_details(
pm: &domain::PaymentMethod,
) -> errors::RouterResult<Option<BankAccountTokenData>> {
let payment_method_data = pm
@@ -5604,8 +5216,16 @@ pub async fn get_bank_from_hs_locker(
}
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub struct TempLockerCardSupport;
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
impl TempLockerCardSupport {
#[instrument(skip_all)]
async fn create_payment_method_data_in_temp_locker(
@@ -5761,53 +5381,7 @@ pub async fn retrieve_payment_method(
key_store: domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
- let db = state.store.as_ref();
- let pm = db
- .find_payment_method(
- &((&state).into()),
- &key_store,
- &pm.payment_method_id,
- merchant_account.storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
-
- let card = if pm.payment_method == Some(enums::PaymentMethod::Card) {
- let card_detail = if state.conf.locker.locker_enabled {
- let card = get_card_from_locker(
- &state,
- &pm.customer_id,
- &pm.merchant_id,
- pm.locker_id.as_ref().unwrap_or(pm.get_id()),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error getting card from card vault")?;
- payment_methods::get_card_detail(&pm, card)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while getting card details from locker")?
- } else {
- get_card_details_without_locker_fallback(&pm, &state).await?
- };
- Some(card_detail)
- } else {
- None
- };
- Ok(services::ApplicationResponse::Json(
- api::PaymentMethodResponse {
- merchant_id: pm.merchant_id.to_owned(),
- customer_id: pm.customer_id.to_owned(),
- payment_method_id: pm.get_id().clone(),
- payment_method: pm.payment_method,
- payment_method_type: pm.payment_method_type,
- metadata: pm.metadata,
- created: Some(pm.created_at),
- recurring_enabled: false,
- payment_method_data: card.clone().map(api::PaymentMethodResponseData::Card),
- last_used_at: Some(pm.last_used_at),
- client_secret: pm.client_secret,
- },
- ))
+ todo!()
}
#[cfg(all(
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 17477141492..d0f63a2dc04 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -2,6 +2,8 @@
use std::str::FromStr;
use api_models::{enums as api_enums, payment_methods::Card};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use common_utils::ext_traits::ValueExt;
use common_utils::{
ext_traits::{Encode, StringExt},
id_type,
@@ -249,6 +251,92 @@ pub async fn get_decrypted_response_payload(
.attach_printable("Jws Decryption failed for JwsBody for vault")
}
+pub async fn get_decrypted_vault_response_payload(
+ jwekey: &settings::Jwekey,
+ jwe_body: encryption::JweBody,
+ decryption_scheme: settings::DecryptionScheme,
+) -> CustomResult<String, errors::VaultError> {
+ let public_key = jwekey.vault_encryption_key.peek().as_bytes();
+
+ let private_key = jwekey.vault_private_key.peek().as_bytes();
+
+ let jwt = get_dotted_jwe(jwe_body);
+ let alg = match decryption_scheme {
+ settings::DecryptionScheme::RsaOaep => jwe::RSA_OAEP,
+ settings::DecryptionScheme::RsaOaep256 => jwe::RSA_OAEP_256,
+ };
+
+ let jwe_decrypted = encryption::decrypt_jwe(
+ &jwt,
+ encryption::KeyIdCheck::SkipKeyIdCheck,
+ private_key,
+ alg,
+ )
+ .await
+ .change_context(errors::VaultError::SaveCardFailed)
+ .attach_printable("Jwe Decryption failed for JweBody for vault")?;
+
+ let jws = jwe_decrypted
+ .parse_struct("JwsBody")
+ .change_context(errors::VaultError::ResponseDeserializationFailed)?;
+ let jws_body = get_dotted_jws(jws);
+
+ encryption::verify_sign(jws_body, public_key)
+ .change_context(errors::VaultError::SaveCardFailed)
+ .attach_printable("Jws Decryption failed for JwsBody for vault")
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn create_jwe_body_for_vault(
+ jwekey: &settings::Jwekey,
+ jws: &str,
+) -> CustomResult<encryption::JweBody, errors::VaultError> {
+ let jws_payload: Vec<&str> = jws.split('.').collect();
+
+ let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
+ Some(encryption::JwsBody {
+ header: payload.first()?.to_string(),
+ payload: payload.get(1)?.to_string(),
+ signature: payload.get(2)?.to_string(),
+ })
+ };
+
+ let jws_body =
+ generate_jws_body(jws_payload).ok_or(errors::VaultError::RequestEncryptionFailed)?;
+
+ let payload = jws_body
+ .encode_to_vec()
+ .change_context(errors::VaultError::RequestEncodingFailed)?;
+
+ let public_key = jwekey.vault_encryption_key.peek().as_bytes();
+
+ let jwe_encrypted = encryption::encrypt_jwe(
+ &payload,
+ public_key,
+ encryption::EncryptionAlgorithm::A256GCM,
+ None,
+ )
+ .await
+ .change_context(errors::VaultError::SaveCardFailed)
+ .attach_printable("Error on jwe encrypt")?;
+ let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
+
+ let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
+ Some(encryption::JweBody {
+ header: payload.first()?.to_string(),
+ iv: payload.get(2)?.to_string(),
+ encrypted_payload: payload.get(3)?.to_string(),
+ tag: payload.get(4)?.to_string(),
+ encrypted_key: payload.get(1)?.to_string(),
+ })
+ };
+
+ let jwe_body =
+ generate_jwe_body(jwe_payload).ok_or(errors::VaultError::RequestEncodingFailed)?;
+
+ Ok(jwe_body)
+}
+
pub async fn mk_basilisk_req(
jwekey: &settings::Jwekey,
jws: &str,
@@ -428,14 +516,50 @@ pub fn mk_add_card_response_hs(
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub fn mk_add_card_response_hs(
- _card: api::CardDetail,
- _card_reference: String,
- _req: api::PaymentMethodCreate,
- _merchant_id: &id_type::MerchantId,
+ card: api::CardDetail,
+ card_reference: String,
+ req: api::PaymentMethodCreate,
+ merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
todo!()
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub fn generate_payment_method_response(
+ pm: &domain::PaymentMethod,
+) -> errors::RouterResult<api::PaymentMethodResponse> {
+ let pmd = pm
+ .payment_method_data
+ .clone()
+ .map(|data| data.into_inner().expose())
+ .map(|decrypted_value| decrypted_value.parse_value("PaymentMethodsData"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to parse PaymentMethodsData")?
+ .and_then(|data| match data {
+ api::PaymentMethodsData::Card(card) => {
+ Some(api::PaymentMethodResponseData::Card(card.into()))
+ }
+ _ => None,
+ });
+
+ let resp = api::PaymentMethodResponse {
+ merchant_id: pm.merchant_id.to_owned(),
+ customer_id: pm.customer_id.to_owned(),
+ payment_method_id: pm.id.get_string_repr(),
+ payment_method: pm.payment_method,
+ payment_method_type: pm.payment_method_type,
+ metadata: pm.metadata.clone(),
+ created: Some(pm.created_at),
+ recurring_enabled: false,
+ last_used_at: Some(pm.last_used_at),
+ client_secret: pm.client_secret.clone(),
+ payment_method_data: pmd,
+ };
+
+ Ok(resp)
+}
+
#[allow(clippy::too_many_arguments)]
pub async fn mk_get_card_request_hs(
jwekey: &settings::Jwekey,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 0ec14bd69ed..0af5bf6037a 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3807,6 +3807,25 @@ where
.await
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+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::ConnectorData>,
+ mandate_type: Option<api::MandateTransactionType>,
+ is_connector_agnostic_mit_enabled: Option<bool>,
+) -> RouterResult<ConnectorCallType>
+where
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+{
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[allow(clippy::too_many_arguments)]
pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone, D>(
state: &SessionState,
@@ -3970,6 +3989,26 @@ where
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[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::ConnectorData>,
+ is_connector_agnostic_mit_enabled: Option<bool>,
+ payment_method_info: &domain::PaymentMethod,
+) -> RouterResult<ConnectorCallType>
+where
+ D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
+{
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[allow(clippy::too_many_arguments)]
pub async fn decide_connector_for_normal_or_recurring_payment<F: Clone, D>(
state: &SessionState,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index a1d92d8a992..ce92c1ab007 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1781,6 +1781,23 @@ pub async fn retrieve_payment_method_with_temporary_token(
})
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn retrieve_card_with_permanent_token(
+ state: &SessionState,
+ locker_id: &str,
+ _payment_method_id: &common_utils::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!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_card_with_permanent_token(
state: &SessionState,
@@ -1986,6 +2003,20 @@ pub async fn fetch_card_details_from_locker(
Ok(domain::PaymentMethodData::Card(api_card.into()))
}
+#[cfg(all(feature = "v2", feature = "payment_methods_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(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn retrieve_payment_method_from_db_with_token_data(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
@@ -2082,6 +2113,27 @@ pub async fn retrieve_payment_token_data(
Ok(token_data)
}
+#[cfg(all(feature = "v2", feature = "payment_methods_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::BusinessProfile>,
+) -> RouterResult<(
+ BoxedOperation<'a, F, R, D>,
+ Option<domain::PaymentMethodData>,
+ Option<String>,
+)> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn make_pm_data<'a, F: Clone, R, D>(
operation: BoxedOperation<'a, F, R, D>,
state: &'a SessionState,
@@ -5100,6 +5152,21 @@ pub fn update_additional_payment_data_with_connector_response_pm_data(
.attach_printable("Failed to encode additional pm data")
}
+#[cfg(all(feature = "v2", feature = "payment_methods_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(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn get_payment_method_details_from_payment_token(
state: &SessionState,
payment_attempt: &PaymentAttempt,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index f397ecd8a2a..a9cd1ae4d84 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -978,6 +978,35 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>> f
}
impl PaymentCreate {
+ #[cfg(all(feature = "v2", feature = "payment_methods_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>,
+ ) -> RouterResult<(
+ storage::PaymentAttemptNew,
+ Option<api_models::payments::AdditionalPaymentData>,
+ )> {
+ todo!()
+ }
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn make_payment_attempt(
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index fb09b4d8b60..ae6ac330679 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -88,6 +88,26 @@ impl<F: Send + Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthor
Ok(payment_data)
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn save_pm_and_mandate<'b>(
+ &self,
+ state: &SessionState,
+ resp: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &mut PaymentData<F>,
+ business_profile: &domain::BusinessProfile,
+ ) -> CustomResult<(), errors::ApiErrorResponse>
+ where
+ F: 'b + Clone + Send + Sync,
+ {
+ todo!()
+ }
+
+ #[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn save_pm_and_mandate<'b>(
&self,
state: &SessionState,
@@ -1602,6 +1622,23 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_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,
+ is_connector_agnostic_mit_enabled: Option<bool>,
+) -> RouterResult<()> {
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
async fn update_payment_method_status_and_ntid<F: Clone>(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index d81258d6671..0760cd449fe 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -214,6 +214,28 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest
}
}
+#[cfg(all(feature = "v2", feature = "payment_methods_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_account: &domain::MerchantAccount,
+ _key_store: &domain::MerchantKeyStore,
+ _state: &SessionState,
+ _request: &api::PaymentsRetrieveRequest,
+ _operation: Op,
+ _storage_scheme: enums::MerchantStorageScheme,
+) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, PaymentData<F>>>
+{
+ todo!()
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
async fn get_tracker_for_sync<
'a,
F: Send + Clone,
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index f948d7faaf9..2a93f8c215d 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -489,7 +489,18 @@ async fn store_bank_details_in_payment_methods(
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?;
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
let pm_id = generate_id(consts::ID_LENGTH, "pm");
+
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ let pm_id = common_utils::id_type::GlobalPaymentMethodId::generate("random_cell_id")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to generate GlobalPaymentMethodId")?;
+
let now = common_utils::date_time::now();
#[cfg(all(
any(feature = "v1", feature = "v2"),
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 4dc77211857..8120ccc8089 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1821,6 +1821,10 @@ impl PaymentIntentInterface for KafkaStore {
#[async_trait::async_trait]
impl PaymentMethodInterface for KafkaStore {
+ #[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method(
&self,
state: &KeyManagerState,
@@ -1833,6 +1837,19 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ self.diesel_store
+ .find_payment_method(state, key_store, payment_method_id, storage_scheme)
+ .await
+ }
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index cf263def41c..6e052076799 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -14,6 +14,10 @@ use crate::{
#[async_trait::async_trait]
pub trait PaymentMethodInterface {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method(
&self,
state: &KeyManagerState,
@@ -22,6 +26,15 @@ pub trait PaymentMethodInterface {
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
+ #[cfg(all(feature = "v2", feature = "customer_v2"))]
+ async fn find_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError>;
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
@@ -231,7 +244,7 @@ mod storage {
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- payment_method_id: &str,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -251,7 +264,8 @@ mod storage {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("payment_method_{}", payment_method_id);
+ let lookup_id =
+ format!("payment_method_{}", payment_method_id.get_string_repr());
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -385,6 +399,38 @@ mod storage {
.map_err(|error| report!(errors::StorageError::from(error)))
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ #[instrument(skip_all)]
+ async fn insert_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method: domain::PaymentMethod,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_method_new = payment_method
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::DecryptionError)?;
+
+ let conn = connection::pg_connection_write(self).await?;
+ payment_method_new
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
@@ -591,77 +637,18 @@ mod storage {
.await
.change_context(errors::StorageError::DecryptionError)?;
- let merchant_id = payment_method.merchant_id.clone();
- let customer_id = payment_method.customer_id.clone();
- let key = PartitionKey::MerchantIdCustomerId {
- merchant_id: &merchant_id,
- customer_id: &customer_id,
- };
- let field = format!("payment_method_id_{}", payment_method.get_id());
- let storage_scheme =
- Box::pin(decide_storage_scheme::<_, storage_types::PaymentMethod>(
- self,
- storage_scheme,
- Op::Update(key.clone(), &field, payment_method.updated_by.as_deref()),
- ))
- .await;
- let pm = match storage_scheme {
- MerchantStorageScheme::PostgresOnly => {
- let conn = connection::pg_connection_write(self).await?;
- payment_method
- .update_with_id(
- &conn,
- payment_method_update.convert_to_payment_method_update(storage_scheme),
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
- MerchantStorageScheme::RedisKv => {
- let key_str = key.to_string();
-
- let p_update: PaymentMethodUpdateInternal =
- payment_method_update.convert_to_payment_method_update(storage_scheme);
- let updated_payment_method =
- p_update.clone().apply_changeset(payment_method.clone());
-
- let redis_value = serde_json::to_string(&updated_payment_method)
- .change_context(errors::StorageError::SerializationFailed)?;
-
- let redis_entry = kv::TypedSql {
- op: kv::DBOperation::Update {
- updatable: kv::Updateable::PaymentMethodUpdate(
- kv::PaymentMethodUpdateMems {
- orig: payment_method,
- update_data: p_update,
- },
- ),
- },
- };
-
- kv_wrapper::<(), _, _>(
- self,
- KvOperation::<diesel_models::PaymentMethod>::Hset(
- (&field, redis_value),
- redis_entry,
- ),
- key,
- )
- .await
- .map_err(|err| err.to_redis_failed_response(&key_str))?
- .try_into_hset()
- .change_context(errors::StorageError::KVError)?;
-
- Ok(updated_payment_method)
- }
- }?;
-
- pm.convert(
- state,
- key_store.key.get_inner(),
- key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
+ let conn = connection::pg_connection_write(self).await?;
+ payment_method
+ .update_with_id(&conn, payment_method_update.into())
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
#[cfg(all(
@@ -927,7 +914,7 @@ mod storage {
&self,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
- payment_method_id: &str,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -1258,6 +1245,10 @@ mod storage {
#[async_trait::async_trait]
impl PaymentMethodInterface for MockDb {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn find_payment_method(
&self,
state: &KeyManagerState,
@@ -1287,6 +1278,36 @@ impl PaymentMethodInterface for MockDb {
}
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ async fn find_payment_method(
+ &self,
+ state: &KeyManagerState,
+ key_store: &domain::MerchantKeyStore,
+ payment_method_id: &id_type::GlobalPaymentMethodId,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
+ let payment_methods = self.payment_methods.lock().await;
+ let payment_method = payment_methods
+ .iter()
+ .find(|pm| pm.get_id() == payment_method_id)
+ .cloned();
+
+ match payment_method {
+ Some(pm) => Ok(pm
+ .convert(
+ state,
+ key_store.key.get_inner(),
+ key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)?),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find payment method".to_string(),
+ )
+ .into()),
+ }
+ }
+
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 2bafe504dd9..aad5acbbade 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1064,6 +1064,24 @@ impl Payouts {
}
}
+#[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2",))]
+impl PaymentMethods {
+ pub fn server(state: AppState) -> Scope {
+ let mut route = web::scope("/v2/payment_methods").app_data(web::Data::new(state));
+ route = route
+ .service(web::resource("").route(web::post().to(create_payment_method_api)))
+ .service(
+ web::resource("/create-intent")
+ .route(web::post().to(create_payment_method_intent_api)),
+ )
+ .service(
+ web::resource("/{id}/confirm-intent")
+ .route(web::post().to(confirm_payment_method_intent_api)),
+ );
+
+ route
+ }
+}
pub struct PaymentMethods;
#[cfg(all(
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index e2cb50b0aa7..725d6af81af 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -12,6 +12,11 @@ use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
use router_env::{instrument, logger, tracing, Flow};
use super::app::{AppState, SessionState};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::core::payment_methods::{
+ create_payment_method, list_customer_payment_method_util, payment_method_intent_confirm,
+ payment_method_intent_create,
+};
use crate::{
core::{
api_locking, errors,
@@ -35,6 +40,10 @@ use crate::{
types::api::customers::CustomerRequest,
};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_api(
state: web::Data<AppState>,
@@ -63,6 +72,114 @@ pub async fn create_payment_method_api(
.await
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
+pub async fn create_payment_method_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_methods::PaymentMethodCreate>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodsCreate;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, auth, req, _| async move {
+ Box::pin(create_payment_method(
+ &state,
+ req,
+ &auth.merchant_account,
+ &auth.key_store,
+ ))
+ .await
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
+pub async fn create_payment_method_intent_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_methods::PaymentMethodIntentCreate>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodsCreate;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, auth, req, _| async move {
+ Box::pin(payment_method_intent_create(
+ &state,
+ req,
+ &auth.merchant_account,
+ &auth.key_store,
+ ))
+ .await
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
+pub async fn confirm_payment_method_intent_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_methods::PaymentMethodIntentConfirm>,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodsCreate;
+ let pm_id = path.into_inner();
+ let payload = json_payload.into_inner();
+
+ let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return api::log_and_return_error_response(e),
+ };
+
+ let inner_payload = payment_methods::PaymentMethodIntentConfirmInternal {
+ id: pm_id.clone(),
+ payment_method: payload.payment_method,
+ payment_method_type: payload.payment_method_type,
+ client_secret: payload.client_secret.clone(),
+ customer_id: payload.customer_id.to_owned(),
+ payment_method_data: payload.payment_method_data.clone(),
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ inner_payload,
+ |state, auth, req, _| {
+ let pm_id = pm_id.clone();
+ async move {
+ Box::pin(payment_method_intent_confirm(
+ &state,
+ req.into(),
+ &auth.merchant_account,
+ &auth.key_store,
+ pm_id,
+ ))
+ .await
+ }
+ },
+ &*auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))]
pub async fn migrate_payment_method_api(
state: web::Data<AppState>,
@@ -346,7 +463,7 @@ pub async fn list_customer_payment_method_for_payment(
&req,
payload,
|state, auth, req, _| {
- cards::list_customer_payment_method_util(
+ list_customer_payment_method_util(
state,
auth.merchant_account,
auth.key_store,
@@ -411,7 +528,7 @@ pub async fn list_customer_payment_method_api(
&req,
payload,
|state, auth, req, _| {
- cards::list_customer_payment_method_util(
+ list_customer_payment_method_util(
state,
auth.merchant_account,
auth.key_store,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 16a8ed1ccc4..bcc2046e24e 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -11,6 +11,7 @@ pub mod authentication;
pub mod domain;
#[cfg(feature = "frm")]
pub mod fraud_check;
+pub mod payment_methods;
pub mod pm_auth;
use masking::Secret;
pub mod storage;
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index 9262877a385..b3bcfa2a887 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -125,75 +125,7 @@ impl MandateResponseExt for MandateResponse {
mandate: storage::Mandate,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> RouterResult<Self> {
- let db = &*state.store;
- let payment_method = db
- .find_payment_method(
- &(state.into()),
- &key_store,
- &mandate.payment_method_id,
- storage_scheme,
- )
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
-
- let pm = payment_method
- .payment_method
- .get_required_value("payment_method")
- .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
- .attach_printable("payment_method not found")?;
-
- let card = if pm == storage_enums::PaymentMethod::Card {
- // if locker is disabled , decrypt the payment method data
- let card_details = if state.conf.locker.locker_enabled {
- let card = payment_methods::cards::get_card_from_locker(
- state,
- &payment_method.customer_id,
- &payment_method.merchant_id,
- payment_method
- .locker_id
- .as_ref()
- .unwrap_or(&payment_method.id),
- )
- .await?;
-
- payment_methods::transformers::get_card_detail(&payment_method, card)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed while getting card details")?
- } else {
- payment_methods::cards::get_card_details_without_locker_fallback(
- &payment_method,
- state,
- )
- .await?
- };
-
- Some(MandateCardDetails::from(card_details).into_inner())
- } else {
- None
- };
- let payment_method_type = payment_method
- .payment_method_type
- .map(|pmt| pmt.to_string());
- Ok(Self {
- mandate_id: mandate.mandate_id,
- customer_acceptance: Some(api::payments::CustomerAcceptance {
- acceptance_type: if mandate.customer_ip_address.is_some() {
- api::payments::AcceptanceType::Online
- } else {
- api::payments::AcceptanceType::Offline
- },
- accepted_at: mandate.customer_accepted_at,
- online: Some(api::payments::OnlineMandate {
- ip_address: mandate.customer_ip_address,
- user_agent: mandate.customer_user_agent.unwrap_or_default(),
- }),
- }),
- card,
- status: mandate.mandate_status,
- payment_method: pm.to_string(),
- payment_method_type,
- payment_method_id: mandate.payment_method_id,
- })
+ todo!()
}
}
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index f4d1492fb44..65111815b5c 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -5,8 +5,8 @@ pub use api_models::payment_methods::{
GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest,
PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate,
PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
- PaymentMethodIntentConfirm, PaymentMethodIntentCreate, PaymentMethodList,
- PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse,
+ PaymentMethodIntentConfirm, PaymentMethodIntentConfirmInternal, PaymentMethodIntentCreate,
+ PaymentMethodList, PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse,
PaymentMethodMigrate, PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate,
PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1,
TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
@@ -32,6 +32,8 @@ use crate::core::{
errors::{self, RouterResult},
payments::helpers::validate_payment_method_type_against_payment_method,
};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::utils;
pub(crate) trait PaymentMethodCreateExt {
fn validate(&self) -> RouterResult<()>;
@@ -61,15 +63,63 @@ impl PaymentMethodCreateExt for PaymentMethodCreate {
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl PaymentMethodCreateExt for PaymentMethodCreate {
fn validate(&self) -> RouterResult<()> {
- if !validate_payment_method_type_against_payment_method(
- self.payment_method,
- self.payment_method_type,
- ) {
- return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
- message: "Invalid 'payment_method_type' provided".to_string()
- })
- .attach_printable("Invalid payment method type"));
- }
+ utils::when(
+ !validate_payment_method_type_against_payment_method(
+ self.payment_method,
+ self.payment_method_type,
+ ),
+ || {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_type' provided".to_string()
+ })
+ .attach_printable("Invalid payment method type"));
+ },
+ );
+
+ utils::when(
+ !PaymentMethodCreate::validate_payment_method_data_against_payment_method(
+ self.payment_method,
+ self.payment_method_data.clone(),
+ ),
+ || {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_data' provided".to_string()
+ })
+ .attach_printable("Invalid payment method data"));
+ },
+ );
+ Ok(())
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethodCreateExt for PaymentMethodIntentConfirm {
+ fn validate(&self) -> RouterResult<()> {
+ utils::when(
+ !validate_payment_method_type_against_payment_method(
+ self.payment_method,
+ self.payment_method_type,
+ ),
+ || {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_type' provided".to_string()
+ })
+ .attach_printable("Invalid payment method type"));
+ },
+ );
+
+ utils::when(
+ !PaymentMethodIntentConfirm::validate_payment_method_data_against_payment_method(
+ self.payment_method,
+ self.payment_method_data.clone(),
+ ),
+ || {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_data' provided".to_string()
+ })
+ .attach_printable("Invalid payment method data"));
+ },
+ );
Ok(())
}
}
diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs
new file mode 100644
index 00000000000..933b8e73da8
--- /dev/null
+++ b/crates/router/src/types/payment_methods.rs
@@ -0,0 +1,103 @@
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use common_utils::generate_id;
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::{
+ consts,
+ types::{api, domain, storage},
+};
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+pub trait VaultingInterface {
+ fn get_vaulting_request_url() -> &'static str;
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+pub trait VaultingDataInterface {
+ fn get_vaulting_data_key(&self) -> String;
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultFingerprintRequest {
+ pub data: String,
+ pub key: String,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VaultFingerprintResponse {
+ pub fingerprint_id: String,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct AddVaultRequest<D> {
+ pub entity_id: common_utils::id_type::MerchantId,
+ pub vault_id: String,
+ pub data: D,
+ pub ttl: i64,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct AddVaultResponse {
+ pub entity_id: common_utils::id_type::MerchantId,
+ pub vault_id: String,
+ pub fingerprint_id: Option<String>,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct AddVault;
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct GetVaultFingerprint;
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+impl VaultingInterface for AddVault {
+ fn get_vaulting_request_url() -> &'static str {
+ consts::ADD_VAULT_REQUEST_URL
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+impl VaultingInterface for GetVaultFingerprint {
+ fn get_vaulting_request_url() -> &'static str {
+ consts::VAULT_FINGERPRINT_REQUEST_URL
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[async_trait::async_trait]
+impl VaultingDataInterface for api::PaymentMethodCreateData {
+ fn get_vaulting_data_key(&self) -> String {
+ match &self {
+ api::PaymentMethodCreateData::Card(card) => card.card_number.to_string(),
+ }
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub struct PaymentMethodClientSecret;
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl PaymentMethodClientSecret {
+ pub fn generate(payment_method_id: &common_utils::id_type::GlobalPaymentMethodId) -> String {
+ todo!()
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub struct SavedPMLPaymentsInfo {
+ pub payment_intent: storage::PaymentIntent,
+ pub business_profile: Option<domain::BusinessProfile>,
+ pub requires_cvv: bool,
+ pub off_session_payment_flag: bool,
+ pub is_connector_agnostic_mit_enabled: bool,
+}
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 5bbfd8483cd..34c5714e126 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -19,6 +19,10 @@ pub enum PaymentTokenKind {
Permanent,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
pub payment_method_id: Option<String>,
@@ -27,6 +31,14 @@ pub struct CardTokenData {
pub network_token_locker_id: Option<String>,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct CardTokenData {
+ pub payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>,
+ pub locker_id: Option<String>,
+ pub token: String,
+}
+
#[derive(Debug, Clone, serde::Serialize, Default, serde::Deserialize)]
pub struct PaymentMethodDataWithId {
pub payment_method: Option<enums::PaymentMethod>,
@@ -58,6 +70,10 @@ pub enum PaymentTokenData {
}
impl PaymentTokenData {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
pub fn permanent_card(
payment_method_id: Option<String>,
locker_id: Option<String>,
@@ -72,6 +88,19 @@ impl PaymentTokenData {
})
}
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ pub fn permanent_card(
+ payment_method_id: Option<common_utils::id_type::GlobalPaymentMethodId>,
+ locker_id: Option<String>,
+ token: String,
+ ) -> Self {
+ Self::PermanentCard(CardTokenData {
+ payment_method_id,
+ locker_id,
+ token,
+ })
+ }
+
pub fn temporary_generic(token: String) -> Self {
Self::TemporaryGeneric(GenericTokenData { token })
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 1442f5b8d48..a6f6d7c4c5a 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -129,19 +129,7 @@ impl
domain::PaymentMethod,
),
) -> Self {
- Self {
- merchant_id: item.merchant_id.to_owned(),
- customer_id: item.customer_id.to_owned(),
- payment_method_id: item.get_id().clone(),
- payment_method: item.payment_method,
- payment_method_type: item.payment_method_type,
- payment_method_data: card_details.map(payment_methods::PaymentMethodResponseData::Card),
- recurring_enabled: false,
- metadata: item.metadata,
- created: Some(item.created_at),
- last_used_at: None,
- client_secret: item.client_secret,
- }
+ todo!()
}
}
diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs
index abc30074cda..124417e3355 100644
--- a/crates/router/src/workflows/payment_method_status_update.rs
+++ b/crates/router/src/workflows/payment_method_status_update.rs
@@ -14,6 +14,10 @@ pub struct PaymentMethodStatusUpdateWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow {
+ #[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+ ))]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 6a796386777..cadb78944ee 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -437,7 +437,7 @@ impl UniqueConstraints for diesel_models::PaymentMethod {
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
impl UniqueConstraints for diesel_models::PaymentMethod {
fn unique_constraints(&self) -> Vec<String> {
- vec![format!("paymentmethod_{}", self.id)]
+ vec![self.id.get_string_repr()]
}
fn table_name(&self) -> &str {
"PaymentMethod"
|
2024-09-05T09:53:05Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Core logic for Payment method create API for v2
- Does not contain global_id (will raise separate PR for that)
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Vault dev is incomplete as of now so cannot test.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
97c8e98a48f514b0ba36b109971dd479ae84861e
|
Vault dev is incomplete as of now so cannot test.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4899
|
Bug: [BUG] : [BOA/CYBS] make AVS code optional
### Bug Description
AVS code is mandatory, but in some cases it is not sent
### Expected Behavior
AVS code must be optional
### Actual Behavior
Incases where, AVS code is not sent results in a de serialization error
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index 7446749e73c..edff5c251a5 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -835,7 +835,7 @@ pub struct ClientRiskInformationRules {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Avs {
- code: String,
+ code: Option<String>,
code_raw: Option<String>,
}
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 3250cb1ba81..ceb0b4ad47f 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -1766,7 +1766,7 @@ pub struct CardVerification {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Avs {
- code: String,
+ code: Option<String>,
code_raw: Option<String>,
}
|
2024-06-06T10:39:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Make AVS code optional
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Do a non 3ds payment - Sanity
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_K5SsEmIckmis20oeONswdh8Cu58ZuXrNLCLIzyXNhhJLiHeeo600vhMovaKi81F0' \
--data-raw '{
"amount": 10000000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "CustomerX",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "HK",
"first_name": "John",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "13.232.74.226"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "HK",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
}'
```
Response
```
{
"payment_id": "pay_tLDEYk3yTxDzmriMmZpO",
"merchant_id": "merchant_1717669788",
"status": "succeeded",
"amount": 10000000,
"net_amount": 10000000,
"amount_capturable": 0,
"amount_received": 10000000,
"connector": "bankofamerica",
"client_secret": "pay_tLDEYk3yTxDzmriMmZpO_secret_Tq8g1rglsndzsxSbzAdy",
"created": "2024-06-06T10:29:59.899Z",
"currency": "USD",
"customer_id": "CustomerX",
"customer": {
"id": "CustomerX",
"name": "John Doe",
"email": "abcdef123@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null,
"approval_code": "831000",
"consumer_authentication_response": null,
"cavv": null,
"eci": null,
"eci_raw": null
},
"authentication_data": {
"retrieval_reference_number": null,
"acs_transaction_id": null,
"system_trace_audit_number": null
}
},
"billing": null
},
"payment_token": "token_Pt4Kz5hHqT5uz2i73poe",
"shipping": {
"address": {
"city": "San Fransico",
"country": "HK",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "HK",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "CustomerX",
"created_at": 1717669799,
"expires": 1717673399,
"secret": "epk_e476f9f1f32843a387e66335a9720879"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7176698015826287804953",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_tLDEYk3yTxDzmriMmZpO_1",
"payment_link": null,
"profile_id": "pro_VeTh8fChUYxqqKXvsFPk",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_WvNBAlqHk4oB7Ke89Rwq",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-06T10:44:59.899Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "13.232.74.226",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_bqI6UMJ2WNmu1j6aYuhZ",
"payment_method_status": null,
"updated": "2024-06-06T10:30:04.394Z",
"charges": null,
"frm_metadata": null
}
```
_Note: Scenario when connector do not send avs code is random_
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
9903119e8b1f2c08ee99e630c1c64cdeb7c34df4
|
1. Do a non 3ds payment - Sanity
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_K5SsEmIckmis20oeONswdh8Cu58ZuXrNLCLIzyXNhhJLiHeeo600vhMovaKi81F0' \
--data-raw '{
"amount": 10000000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "CustomerX",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "HK",
"first_name": "John",
"last_name": "Doe"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "13.232.74.226"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "HK",
"first_name": "John",
"last_name": "Doe"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
}'
```
Response
```
{
"payment_id": "pay_tLDEYk3yTxDzmriMmZpO",
"merchant_id": "merchant_1717669788",
"status": "succeeded",
"amount": 10000000,
"net_amount": 10000000,
"amount_capturable": 0,
"amount_received": 10000000,
"connector": "bankofamerica",
"client_secret": "pay_tLDEYk3yTxDzmriMmZpO_secret_Tq8g1rglsndzsxSbzAdy",
"created": "2024-06-06T10:29:59.899Z",
"currency": "USD",
"customer_id": "CustomerX",
"customer": {
"id": "CustomerX",
"name": "John Doe",
"email": "abcdef123@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null,
"approval_code": "831000",
"consumer_authentication_response": null,
"cavv": null,
"eci": null,
"eci_raw": null
},
"authentication_data": {
"retrieval_reference_number": null,
"acs_transaction_id": null,
"system_trace_audit_number": null
}
},
"billing": null
},
"payment_token": "token_Pt4Kz5hHqT5uz2i73poe",
"shipping": {
"address": {
"city": "San Fransico",
"country": "HK",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "HK",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": null,
"email": null
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "CustomerX",
"created_at": 1717669799,
"expires": 1717673399,
"secret": "epk_e476f9f1f32843a387e66335a9720879"
},
"manual_retry_allowed": false,
"connector_transaction_id": "7176698015826287804953",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_tLDEYk3yTxDzmriMmZpO_1",
"payment_link": null,
"profile_id": "pro_VeTh8fChUYxqqKXvsFPk",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_WvNBAlqHk4oB7Ke89Rwq",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-06T10:44:59.899Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "13.232.74.226",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": "pm_bqI6UMJ2WNmu1j6aYuhZ",
"payment_method_status": null,
"updated": "2024-06-06T10:30:04.394Z",
"charges": null,
"frm_metadata": null
}
```
_Note: Scenario when connector do not send avs code is random_
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4901
|
Bug: refactor(user): Make password nullable for `users`
Currently `password` is required field in `users` table. This is causing us to create temporary passwords for `users` in some APIs which inserts `users` without password.
So, we have to make password nullable to solve this.
|
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 15e662fe438..a7d5a8c02bc 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1223,7 +1223,7 @@ diesel::table! {
#[max_length = 255]
name -> Varchar,
#[max_length = 255]
- password -> Varchar,
+ password -> Nullable<Varchar>,
is_verified -> Bool,
created_at -> Timestamp,
last_modified_at -> Timestamp,
diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs
index 6a040e41468..b1bbb66256c 100644
--- a/crates/diesel_models/src/user.rs
+++ b/crates/diesel_models/src/user.rs
@@ -17,7 +17,7 @@ pub struct User {
pub user_id: String,
pub email: pii::Email,
pub name: Secret<String>,
- pub password: Secret<String>,
+ pub password: Option<Secret<String>>,
pub is_verified: bool,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
@@ -37,7 +37,7 @@ pub struct UserNew {
pub user_id: String,
pub email: pii::Email,
pub name: Secret<String>,
- pub password: Secret<String>,
+ pub password: Option<Secret<String>>,
pub is_verified: bool,
pub created_at: Option<PrimitiveDateTime>,
pub last_modified_at: Option<PrimitiveDateTime>,
@@ -76,7 +76,7 @@ pub enum UserUpdate {
totp_recovery_codes: Option<Vec<Secret<String>>>,
},
PasswordUpdate {
- password: Option<Secret<String>>,
+ password: Secret<String>,
},
}
@@ -127,7 +127,7 @@ impl From<UserUpdate> for UserUpdateInternal {
},
UserUpdate::PasswordUpdate { password } => Self {
name: None,
- password,
+ password: Some(password),
is_verified: None,
last_modified_at,
preferred_merchant_id: None,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index a4bb4fb4b03..c78f2c8080f 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -368,7 +368,7 @@ pub async fn change_password(
.update_user_by_user_id(
user.get_user_id(),
diesel_models::user::UserUpdate::PasswordUpdate {
- password: Some(new_password_hash),
+ password: new_password_hash,
},
)
.await
@@ -459,7 +459,7 @@ pub async fn rotate_password(
.update_user_by_user_id(
&user_token.user_id,
storage_user::UserUpdate::PasswordUpdate {
- password: Some(hash_password),
+ password: hash_password,
},
)
.await
@@ -510,7 +510,7 @@ pub async fn reset_password_token_only_flow(
.get_email()
.change_context(UserErrors::InternalServerError)?,
storage_user::UserUpdate::PasswordUpdate {
- password: Some(hash_password),
+ password: hash_password,
},
)
.await
@@ -548,7 +548,7 @@ pub async fn reset_password(
.get_email()
.change_context(UserErrors::InternalServerError)?,
storage_user::UserUpdate::PasswordUpdate {
- password: Some(hash_password),
+ password: hash_password,
},
)
.await
@@ -838,11 +838,9 @@ async fn handle_new_user_invitation(
Ok(InviteMultipleUserResponse {
is_email_sent,
- password: if cfg!(not(feature = "email")) {
- Some(new_user.get_password().get_secret())
- } else {
- None
- },
+ password: new_user
+ .get_password()
+ .map(|password| password.get_secret()),
email: request.email.clone(),
error: None,
})
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index e8104e3a155..742944bd1e0 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -244,7 +244,7 @@ impl UserInterface for MockDb {
..user.to_owned()
},
storage::UserUpdate::PasswordUpdate { password } => storage::User {
- password: password.clone().unwrap_or(user.password.clone()),
+ password: Some(password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
..user.to_owned()
},
@@ -299,7 +299,7 @@ impl UserInterface for MockDb {
..user.to_owned()
},
storage::UserUpdate::PasswordUpdate { password } => storage::User {
- password: password.clone().unwrap_or(user.password.clone()),
+ password: Some(password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
..user.to_owned()
},
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index d9ef736347f..47f26ce04e5 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -1,8 +1,4 @@
-use std::{
- collections::HashSet,
- ops::{self, Not},
- str::FromStr,
-};
+use std::{collections::HashSet, ops, str::FromStr};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
@@ -517,9 +513,8 @@ pub struct NewUser {
user_id: String,
name: UserName,
email: UserEmail,
- password: UserPassword,
+ password: Option<UserPassword>,
new_merchant: NewUserMerchant,
- is_temporary_password: bool,
}
impl NewUser {
@@ -539,7 +534,7 @@ impl NewUser {
self.new_merchant.clone()
}
- pub fn get_password(&self) -> UserPassword {
+ pub fn get_password(&self) -> Option<UserPassword> {
self.password.clone()
}
@@ -623,7 +618,12 @@ impl TryFrom<NewUser> for storage_user::UserNew {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: NewUser) -> UserResult<Self> {
- let hashed_password = password::generate_password_hash(value.password.get_secret())?;
+ let hashed_password = value
+ .password
+ .as_ref()
+ .map(|password| password::generate_password_hash(password.get_secret()))
+ .transpose()?;
+
let now = common_utils::date_time::now();
Ok(Self {
user_id: value.get_user_id(),
@@ -637,7 +637,7 @@ impl TryFrom<NewUser> for storage_user::UserNew {
totp_status: TotpStatus::NotSet,
totp_secret: None,
totp_recovery_codes: None,
- last_password_modified_at: value.is_temporary_password.not().then_some(now),
+ last_password_modified_at: value.password.is_some().then_some(now),
})
}
}
@@ -655,10 +655,9 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser {
Ok(Self {
name,
email,
- password,
+ password: Some(password),
user_id,
new_merchant,
- is_temporary_password: false,
})
}
}
@@ -677,9 +676,8 @@ impl TryFrom<user_api::SignUpRequest> for NewUser {
user_id,
name,
email,
- password,
+ password: Some(password),
new_merchant,
- is_temporary_password: false,
})
}
}
@@ -691,16 +689,14 @@ impl TryFrom<user_api::ConnectAccountRequest> for NewUser {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
let name = UserName::try_from(value.email.clone())?;
- let password = UserPassword::new(password::get_temp_password())?;
let new_merchant = NewUserMerchant::try_from(value)?;
Ok(Self {
user_id,
name,
email,
- password,
+ password: None,
new_merchant,
- is_temporary_password: true,
})
}
}
@@ -721,9 +717,8 @@ impl TryFrom<(user_api::CreateInternalUserRequest, String)> for NewUser {
user_id,
name,
email,
- password,
+ password: Some(password),
new_merchant,
- is_temporary_password: false,
})
}
}
@@ -739,11 +734,12 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser {
user_id: user.0.user_id,
name: UserName::new(user.0.name)?,
email: user.0.email.clone().try_into()?,
- password: UserPassword::new_password_without_validation(user.0.password)?,
+ password: user
+ .0
+ .password
+ .map(UserPassword::new_password_without_validation)
+ .transpose()?,
new_merchant,
- // This is true because we are not creating a user with this request. And if it is set
- // to false, last_password_modified_at will be overwritten if this user is inserted.
- is_temporary_password: true,
})
}
}
@@ -754,7 +750,8 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.0.email.clone().try_into()?;
let name = UserName::new(value.0.name.clone())?;
- let password = UserPassword::new(password::get_temp_password())?;
+ let password = cfg!(not(feature = "email"))
+ .then_some(UserPassword::new(password::get_temp_password())?);
let new_merchant = NewUserMerchant::try_from(value)?;
Ok(Self {
@@ -763,7 +760,6 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser {
email,
password,
new_merchant,
- is_temporary_password: true,
})
}
}
@@ -783,10 +779,14 @@ impl UserFromStorage {
}
pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()> {
- match password::is_correct_password(candidate, &self.0.password) {
- Ok(true) => Ok(()),
- Ok(false) => Err(UserErrors::InvalidCredentials.into()),
- Err(e) => Err(e),
+ if let Some(password) = self.0.password.as_ref() {
+ match password::is_correct_password(candidate, password) {
+ Ok(true) => Ok(()),
+ Ok(false) => Err(UserErrors::InvalidCredentials.into()),
+ Err(e) => Err(e),
+ }
+ } else {
+ Err(UserErrors::InvalidCredentials.into())
}
}
diff --git a/migrations/2024-06-06-101812_user_optional_password/down.sql b/migrations/2024-06-06-101812_user_optional_password/down.sql
new file mode 100644
index 00000000000..acd0b1efca3
--- /dev/null
+++ b/migrations/2024-06-06-101812_user_optional_password/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE users ALTER COLUMN password SET NOT NULL;
diff --git a/migrations/2024-06-06-101812_user_optional_password/up.sql b/migrations/2024-06-06-101812_user_optional_password/up.sql
new file mode 100644
index 00000000000..e48b1b751ab
--- /dev/null
+++ b/migrations/2024-06-06-101812_user_optional_password/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE users ALTER COLUMN password DROP NOT NULL;
|
2024-06-06T14:12:11Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This API will make the password column in the `users` table nullable.
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #4901.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Create user with `connect_account` API
```
curl --location 'http://localhost:8080/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "unregistered email"
}'
```
2. Invite a unregistered user
```
curl --location 'http://localhost:8080/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data-raw '[
{
"email": "new user email",
"name": "name",
"role_id": "merchant_view_only"
}
]'
```
3. Check the DB entry for those users using the following query
```sql
select * from users where email = 'email used in previous API'
```
Password should be null in all the cases.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2f12cca7ae5a4875b50ca5ff5068500b5004eb6f
|
1. Create user with `connect_account` API
```
curl --location 'http://localhost:8080/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "unregistered email"
}'
```
2. Invite a unregistered user
```
curl --location 'http://localhost:8080/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data-raw '[
{
"email": "new user email",
"name": "name",
"role_id": "merchant_view_only"
}
]'
```
3. Check the DB entry for those users using the following query
```sql
select * from users where email = 'email used in previous API'
```
Password should be null in all the cases.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4893
|
Bug: Add `collect_shipping_details_from_wallet_connector` in the business profile response
Add `collect_shipping_details_from_wallet_connector` in the business profile response
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index dc64947bf08..58cb6fbf3e2 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -936,7 +936,7 @@ pub struct BusinessProfileCreate {
/// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
- /// A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments
+ /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments
pub collect_shipping_details_from_wallet_connector: Option<bool>,
}
@@ -1013,6 +1013,9 @@ pub struct BusinessProfileResponse {
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
+
+ /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments
+ pub collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
@@ -1081,7 +1084,7 @@ pub struct BusinessProfileUpdate {
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
- /// A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments
+ /// A boolean value to indicate if customer shipping details needs to be sent for wallets payments
pub collect_shipping_details_from_wallet_connector: Option<bool>,
}
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 20083afb1c9..b79819ed634 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -85,6 +85,8 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf
.extended_card_info_config
.map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
.transpose()?,
+ collect_shipping_details_from_wallet_connector: item
+ .collect_shipping_details_from_wallet_connector,
})
}
}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 76cbda10a18..a12df1d916a 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -6824,7 +6824,7 @@
},
"collect_shipping_details_from_wallet_connector": {
"type": "boolean",
- "description": "A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments",
+ "description": "A boolean value to indicate if customer shipping details needs to be sent for wallets payments",
"nullable": true
}
},
@@ -6957,6 +6957,11 @@
}
],
"nullable": true
+ },
+ "collect_shipping_details_from_wallet_connector": {
+ "type": "boolean",
+ "description": "A boolean value to indicate if customer shipping details needs to be sent for wallets payments",
+ "nullable": true
}
}
},
|
2024-06-05T13:36:45Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
add `collect_shipping_details_from_wallet_connector` in the business profile
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create merchant account
-> update the business profile with the below curl
```
curl --location 'http://localhost:8080/account/merchant_1717593917/business_profile/pro_eqCDCAfX7AA2WudlMDYP' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_shipping_details_from_wallet_connector": true
}'
```
<img width="940" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/ece087a0-e378-4f3c-84eb-228d9402d56d">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c5e28f2670d51bf6529eb729167c97ad301217ef
|
-> Create merchant account
-> update the business profile with the below curl
```
curl --location 'http://localhost:8080/account/merchant_1717593917/business_profile/pro_eqCDCAfX7AA2WudlMDYP' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_shipping_details_from_wallet_connector": true
}'
```
<img width="940" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/ece087a0-e378-4f3c-84eb-228d9402d56d">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4887
|
Bug: bug(user): Wrong Internal user `org_id`
Currently when an internal user is being created, a new user will be created and a `user_role` with `merchant_id` as `juspay000` will also be inserted.
As the merchant `juspay000` already has a `org_id`, we should use that and insert that `org_id` in `user_role`, but currently a new `org_id` is being generated and inserted everytime when this API is hit.
|
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index cfc01afb91b..65d605b3862 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1046,11 +1046,6 @@ pub async fn create_internal_user(
state: SessionState,
request: user_api::CreateInternalUserRequest,
) -> UserResponse<()> {
- let new_user = domain::NewUser::try_from(request)?;
-
- let mut store_user: storage_user::UserNew = new_user.clone().try_into()?;
- store_user.set_is_verified(true);
-
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
@@ -1066,7 +1061,7 @@ pub async fn create_internal_user(
}
})?;
- state
+ let internal_merchant = state
.store
.find_merchant_account_by_merchant_id(
consts::user_role::INTERNAL_USER_MERCHANT_ID,
@@ -1081,6 +1076,11 @@ pub async fn create_internal_user(
}
})?;
+ let new_user = domain::NewUser::try_from((request, internal_merchant.organization_id))?;
+
+ let mut store_user: storage_user::UserNew = new_user.clone().try_into()?;
+ store_user.set_is_verified(true);
+
state
.store
.insert_user(store_user)
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 60d75ce81d1..0ff9d651baf 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -284,9 +284,12 @@ impl From<user_api::ConnectAccountRequest> for NewUserOrganization {
}
}
-impl From<user_api::CreateInternalUserRequest> for NewUserOrganization {
- fn from(_value: user_api::CreateInternalUserRequest) -> Self {
- let new_organization = api_org::OrganizationNew::new(None);
+impl From<(user_api::CreateInternalUserRequest, String)> for NewUserOrganization {
+ fn from((_value, org_id): (user_api::CreateInternalUserRequest, String)) -> Self {
+ let new_organization = api_org::OrganizationNew {
+ org_id,
+ org_name: None,
+ };
let db_organization = ForeignFrom::foreign_from(new_organization);
Self(db_organization)
}
@@ -457,10 +460,10 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserMerchant {
}
}
-impl TryFrom<user_api::CreateInternalUserRequest> for NewUserMerchant {
+impl TryFrom<(user_api::CreateInternalUserRequest, String)> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
- fn try_from(value: user_api::CreateInternalUserRequest) -> UserResult<Self> {
+ fn try_from(value: (user_api::CreateInternalUserRequest, String)) -> UserResult<Self> {
let merchant_id =
MerchantId::new(consts::user_role::INTERNAL_USER_MERCHANT_ID.to_string())?;
let new_organization = NewUserOrganization::from(value);
@@ -702,15 +705,17 @@ impl TryFrom<user_api::ConnectAccountRequest> for NewUser {
}
}
-impl TryFrom<user_api::CreateInternalUserRequest> for NewUser {
+impl TryFrom<(user_api::CreateInternalUserRequest, String)> for NewUser {
type Error = error_stack::Report<UserErrors>;
- fn try_from(value: user_api::CreateInternalUserRequest) -> UserResult<Self> {
+ fn try_from(
+ (value, org_id): (user_api::CreateInternalUserRequest, String),
+ ) -> UserResult<Self> {
let user_id = uuid::Uuid::new_v4().to_string();
let email = value.email.clone().try_into()?;
let name = UserName::new(value.name.clone())?;
let password = UserPassword::new(value.password.clone())?;
- let new_merchant = NewUserMerchant::try_from(value)?;
+ let new_merchant = NewUserMerchant::try_from((value, org_id))?;
Ok(Self {
user_id,
|
2024-06-05T11:40:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Internal signup will now use the `org_id` of `juspay000` and insert it in `user_roles`.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #4887.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/internal_signup' \
--header 'api-key: admin-api-key' \
--header 'Content-Type: application/json' \
--data-raw '{
"name" : "name",
"email" : "email",
"password": "password"
}'
```
In `user_roles` table, the `org_id` is the correct one as the `juspay000` merchant account. These are the queries I've used to verify.
```sql
select organization_id from merchant_account where merchant_id = 'juspay000'
```
```sql
select org_id from user_roles where merchant_id = 'juspay000'
```
In both cases, `org_id` should be same for newly created user.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7ab65ac8834f47c4448b64899ce3e3656132fb63
|
```
curl --location 'http://localhost:8080/user/internal_signup' \
--header 'api-key: admin-api-key' \
--header 'Content-Type: application/json' \
--data-raw '{
"name" : "name",
"email" : "email",
"password": "password"
}'
```
In `user_roles` table, the `org_id` is the correct one as the `juspay000` merchant account. These are the queries I've used to verify.
```sql
select organization_id from merchant_account where merchant_id = 'juspay000'
```
```sql
select org_id from user_roles where merchant_id = 'juspay000'
```
In both cases, `org_id` should be same for newly created user.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4896
|
Bug: ci(postman): add test collection for users
Add testcases to test
- Singnin flow
- Singup flow (magic account)
Also include token only cases for sign in signup.
|
diff --git a/Cargo.lock b/Cargo.lock
index 228414c0194..77f9b33ddc4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7021,6 +7021,7 @@ dependencies = [
name = "test_utils"
version = "0.1.0"
dependencies = [
+ "anyhow",
"async-trait",
"base64 0.22.0",
"clap",
diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml
index 3b0dfe2b91d..6d8663c0300 100644
--- a/crates/test_utils/Cargo.toml
+++ b/crates/test_utils/Cargo.toml
@@ -14,6 +14,7 @@ payouts = []
[dependencies]
async-trait = "0.1.79"
+anyhow = "1.0.81"
base64 = "0.22.0"
clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] }
rand = "0.8.5"
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index 3ba321c174e..4b41506fe2d 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -76,6 +76,7 @@ pub struct ConnectorAuthentication {
pub zen: Option<HeaderKey>,
pub zsl: Option<BodyKey>,
pub automation_configs: Option<AutomationConfigs>,
+ pub users: Option<UsersConfigs>,
}
impl Default for ConnectorAuthentication {
@@ -339,3 +340,12 @@ pub enum ConnectorAuthType {
#[default]
NoKey,
}
+
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct UsersConfigs {
+ pub user_email: String,
+ pub user_password: String,
+ pub wrong_password: String,
+ pub user_base_email_for_signup: String,
+ pub user_domain_for_signup: String,
+}
diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs
index ba0d2eb358b..5b56b9a0d1c 100644
--- a/crates/test_utils/src/main.rs
+++ b/crates/test_utils/src/main.rs
@@ -1,9 +1,10 @@
use std::process::{exit, Command};
+use anyhow::Result;
use test_utils::newman_runner;
-fn main() {
- let mut runner = newman_runner::generate_newman_command();
+fn main() -> Result<()> {
+ let mut runner = newman_runner::generate_runner()?;
// Execute the newman command
let output = runner.newman_command.spawn();
diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs
index c90292683ff..29c15789cce 100644
--- a/crates/test_utils/src/newman_runner.rs
+++ b/crates/test_utils/src/newman_runner.rs
@@ -6,14 +6,23 @@ use std::{
process::{exit, Command},
};
-use clap::{arg, command, Parser};
+use anyhow::{Context, Result};
+use clap::{arg, command, Parser, ValueEnum};
use masking::PeekInterface;
use regex::Regex;
-use crate::connector_auth::{ConnectorAuthType, ConnectorAuthenticationMap};
+use crate::connector_auth::{
+ ConnectorAuthType, ConnectorAuthentication, ConnectorAuthenticationMap,
+};
+
+#[derive(ValueEnum, Clone, Copy)]
+pub enum Module {
+ Connector,
+ Users,
+}
#[derive(Parser)]
#[command(version, about = "Postman collection runner using newman!", long_about = None)]
-struct Args {
+pub struct Args {
/// Admin API Key of the environment
#[arg(short, long)]
admin_api_key: String,
@@ -22,7 +31,10 @@ struct Args {
base_url: String,
/// Name of the connector
#[arg(short, long)]
- connector_name: String,
+ connector_name: Option<String>,
+ /// Name of the module
+ #[arg(short, long)]
+ module_name: Option<Module>,
/// Custom headers
#[arg(short = 'H', long = "header")]
custom_headers: Option<Vec<String>>,
@@ -38,6 +50,13 @@ struct Args {
verbose: bool,
}
+impl Args {
+ /// Getter for the `module_name` field
+ pub fn get_module_name(&self) -> Option<Module> {
+ self.module_name
+ }
+}
+
pub struct ReturnArgs {
pub newman_command: Command,
pub modified_file_paths: Vec<Option<String>>,
@@ -82,10 +101,93 @@ where
Ok(())
}
-pub fn generate_newman_command() -> ReturnArgs {
+// This function gives runner for connector or a module
+pub fn generate_runner() -> Result<ReturnArgs> {
+ let args = Args::parse();
+
+ match args.get_module_name() {
+ Some(Module::Users) => generate_newman_command_for_users(),
+ Some(Module::Connector) => generate_newman_command_for_connector(),
+ // Running connector tests when no module is passed to keep the previous test behavior same
+ None => generate_newman_command_for_connector(),
+ }
+}
+
+pub fn generate_newman_command_for_users() -> Result<ReturnArgs> {
+ let args = Args::parse();
+ let base_url = args.base_url;
+ let admin_api_key = args.admin_api_key;
+
+ let path = env::var("CONNECTOR_AUTH_FILE_PATH")
+ .with_context(|| "connector authentication file path not set")?;
+
+ let authentication: ConnectorAuthentication = toml::from_str(
+ &fs::read_to_string(path)
+ .with_context(|| "connector authentication config file not found")?,
+ )
+ .with_context(|| "connector authentication file path not set")?;
+
+ let users_configs = authentication
+ .users
+ .with_context(|| "user configs not found in authentication file")?;
+ let collection_path = get_collection_path("users");
+
+ let mut newman_command = Command::new("newman");
+ newman_command.args(["run", &collection_path]);
+ newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
+ newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
+ newman_command.args([
+ "--env-var",
+ &format!("user_email={}", users_configs.user_email),
+ ]);
+ newman_command.args([
+ "--env-var",
+ &format!(
+ "user_base_email_for_signup={}",
+ users_configs.user_base_email_for_signup
+ ),
+ ]);
+ newman_command.args([
+ "--env-var",
+ &format!(
+ "user_domain_for_signup={}",
+ users_configs.user_domain_for_signup
+ ),
+ ]);
+ newman_command.args([
+ "--env-var",
+ &format!("user_password={}", users_configs.user_password),
+ ]);
+ newman_command.args([
+ "--env-var",
+ &format!("wrong_password={}", users_configs.wrong_password),
+ ]);
+
+ newman_command.args([
+ "--delay-request",
+ format!("{}", &args.delay_request).as_str(),
+ ]);
+
+ newman_command.arg("--color").arg("on");
+
+ if args.verbose {
+ newman_command.arg("--verbose");
+ }
+
+ Ok(ReturnArgs {
+ newman_command,
+ modified_file_paths: vec![],
+ collection_path,
+ })
+}
+
+pub fn generate_newman_command_for_connector() -> Result<ReturnArgs> {
let args = Args::parse();
- let connector_name = args.connector_name;
+ let connector_name = args
+ .connector_name
+ .with_context(|| "invalid parameters: connector/module name not found in arguments")?;
+
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
@@ -216,11 +318,11 @@ pub fn generate_newman_command() -> ReturnArgs {
newman_command.arg("--verbose");
}
- ReturnArgs {
+ Ok(ReturnArgs {
newman_command,
modified_file_paths: vec![modified_collection_file_paths, custom_header_exist],
collection_path,
- }
+ })
}
pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> {
diff --git a/postman/collection-dir/users/.event.meta.json b/postman/collection-dir/users/.event.meta.json
new file mode 100644
index 00000000000..2df9d47d936
--- /dev/null
+++ b/postman/collection-dir/users/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.prerequest.js",
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/users/.info.json b/postman/collection-dir/users/.info.json
new file mode 100644
index 00000000000..68f1e83b8ef
--- /dev/null
+++ b/postman/collection-dir/users/.info.json
@@ -0,0 +1,9 @@
+{
+ "info": {
+ "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9",
+ "name": "users",
+ "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)",
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
+ "_exporter_id": "26710321"
+ }
+}
diff --git a/postman/collection-dir/users/.meta.json b/postman/collection-dir/users/.meta.json
new file mode 100644
index 00000000000..91b6a65c5bc
--- /dev/null
+++ b/postman/collection-dir/users/.meta.json
@@ -0,0 +1,6 @@
+{
+ "childrenOrder": [
+ "Health check",
+ "Flow Testcases"
+ ]
+}
diff --git a/postman/collection-dir/users/.variable.json b/postman/collection-dir/users/.variable.json
new file mode 100644
index 00000000000..fba5b17b2fd
--- /dev/null
+++ b/postman/collection-dir/users/.variable.json
@@ -0,0 +1,126 @@
+{
+ "variable": [
+ {
+ "key": "baseUrl",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "admin_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "merchant_id",
+ "value": ""
+ },
+ {
+ "key": "payment_id",
+ "value": ""
+ },
+ {
+ "key": "customer_id",
+ "value": ""
+ },
+ {
+ "key": "mandate_id",
+ "value": ""
+ },
+ {
+ "key": "payment_method_id",
+ "value": ""
+ },
+ {
+ "key": "refund_id",
+ "value": ""
+ },
+ {
+ "key": "merchant_connector_id",
+ "value": ""
+ },
+ {
+ "key": "client_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "publishable_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "payment_token",
+ "value": ""
+ },
+ {
+ "key": "gateway_merchant_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate_keys",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key1",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key2",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_email",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_password",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "wrong_password",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_base_email_for_signup",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_domain_for_signup",
+ "value": "",
+ "type": "string"
+ }
+ ]
+}
diff --git a/postman/collection-dir/users/Flow Testcases/.meta.json b/postman/collection-dir/users/Flow Testcases/.meta.json
new file mode 100644
index 00000000000..3e649dae4eb
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/.meta.json
@@ -0,0 +1,6 @@
+{
+ "childrenOrder": [
+ "Sign Up",
+ "Sign In"
+ ]
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json
new file mode 100644
index 00000000000..84ed2cb9494
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/.meta.json
@@ -0,0 +1,8 @@
+{
+ "childrenOrder": [
+ "Signin",
+ "Signin Wrong",
+ "Signin Token Only",
+ "Signin Token Only Wrong"
+ ]
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js
new file mode 100644
index 00000000000..16fca64a141
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/event.test.js
@@ -0,0 +1,16 @@
+// Validate status 4xx
+pm.test("[POST]::/user/v2/signin?token_only=true - Status code is 401", function () {
+ pm.response.to.have.status(401);
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::user/v2/signin?token_only=true - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::user/v2/signin?token_only=true - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
\ No newline at end of file
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json
new file mode 100644
index 00000000000..7fee4c465c8
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/request.json
@@ -0,0 +1,37 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw_json_formatted": {
+ "email": "{{user_email}}",
+ "password": "{{wrong_password}}"
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ],
+ "query": [
+ {
+ "key": "token_only",
+ "value": "true"
+ }
+ ]
+ }
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only Wrong/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js
new file mode 100644
index 00000000000..a8b3658e5ff
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/event.test.js
@@ -0,0 +1,23 @@
+// Validate status 2xx
+pm.test("[POST]::user/v2/signin?token_only=true - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::user/v2/signin?token_only=true - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::user/v2/signin?token_only=true - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Validate specific JSON response content
+pm.test("[POST]::user/v2/signin?token_only=true - Response contains token", function () {
+ var jsonData = pm.response.json();
+ pm.expect(jsonData).to.have.property("token");
+ pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty;
+});
\ No newline at end of file
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json
new file mode 100644
index 00000000000..62028501a50
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/request.json
@@ -0,0 +1,37 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw_json_formatted": {
+ "email": "{{user_email}}",
+ "password": "{{user_password}}"
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ],
+ "query": [
+ {
+ "key": "token_only",
+ "value": "true"
+ }
+ ]
+ }
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Token Only/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js
new file mode 100644
index 00000000000..e0149290da6
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/event.test.js
@@ -0,0 +1,16 @@
+// Validate status code is 4xx Bad Request
+pm.test("[POST]::/user/v2/signin - Status code is 401", function () {
+ pm.response.to.have.status(401);
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/user/v2/signin - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/user/v2/signin - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
\ No newline at end of file
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json
new file mode 100644
index 00000000000..775b0972d57
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/request.json
@@ -0,0 +1,31 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw_json_formatted": {
+ "email": "{{user_email}}",
+ "password": "{{wrong_password}}"
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ]
+ }
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin Wrong/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/.event.meta.json
new file mode 100644
index 00000000000..4ac527d834a
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.test.js",
+ "event.prerequest.js"
+ ]
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.prerequest.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.prerequest.js
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js
new file mode 100644
index 00000000000..174cbd8e5e2
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/event.test.js
@@ -0,0 +1,23 @@
+// Validate status 2xx
+pm.test("[POST]::/user/v2/signin - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/user/v2/signin - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/user/v2/signin - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Validate specific JSON response content
+pm.test("[POST]::/user/v2/signin - Response contains token", function () {
+ var jsonData = pm.response.json();
+ pm.expect(jsonData).to.have.property("token");
+ pm.expect(jsonData.token).to.be.a("string").and.to.not.be.empty;
+});
\ No newline at end of file
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json
new file mode 100644
index 00000000000..1d23f6e9652
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/request.json
@@ -0,0 +1,31 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw_json_formatted": {
+ "email": "{{user_email}}",
+ "password": "{{user_password}}"
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ]
+ }
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign In/Signin/response.json b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign In/Signin/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/.meta.json b/postman/collection-dir/users/Flow Testcases/Sign Up/.meta.json
new file mode 100644
index 00000000000..07d803fb1ca
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign Up/.meta.json
@@ -0,0 +1,5 @@
+{
+ "childrenOrder": [
+ "Connect Account"
+ ]
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/.event.meta.json b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/.event.meta.json
new file mode 100644
index 00000000000..4ac527d834a
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.test.js",
+ "event.prerequest.js"
+ ]
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.prerequest.js b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.prerequest.js
new file mode 100644
index 00000000000..7f16342a8ad
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.prerequest.js
@@ -0,0 +1,8 @@
+
+var baseEmail = pm.environment.get('user_base_email_for_signup');
+var emailDomain = pm.environment.get("user_domain_for_signup");
+
+// Generate a unique email address
+var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;
+// Set the unique email address as an environment variable
+pm.environment.set('unique_email', uniqueEmail);
diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js
new file mode 100644
index 00000000000..6dbed06b0f6
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/event.test.js
@@ -0,0 +1,23 @@
+// Validate status 2xx
+pm.test("[POST]::/user/connect_account - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/user/connect_account - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/user/connect_account - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Validate specific JSON response content
+pm.test("[POST]::/user/connect_account - Response contains is_email_sent", function () {
+ var jsonData = pm.response.json();
+ pm.expect(jsonData).to.have.property("is_email_sent");
+ pm.expect(jsonData.is_email_sent).to.be.true;
+});
diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/request.json b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/request.json
new file mode 100644
index 00000000000..d5f2433ad7a
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/request.json
@@ -0,0 +1,29 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw_json_formatted": {
+ "email": "{{unique_email}}"
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/connect_account",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "connect_account"
+ ]
+ }
+}
diff --git a/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/response.json b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/users/Flow Testcases/Sign Up/Connect Account/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/users/Health check/.meta.json b/postman/collection-dir/users/Health check/.meta.json
new file mode 100644
index 00000000000..66ee7e50cab
--- /dev/null
+++ b/postman/collection-dir/users/Health check/.meta.json
@@ -0,0 +1,5 @@
+{
+ "childrenOrder": [
+ "New Request"
+ ]
+}
diff --git a/postman/collection-dir/users/Health check/New Request/.event.meta.json b/postman/collection-dir/users/Health check/New Request/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/users/Health check/New Request/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/users/Health check/New Request/event.test.js b/postman/collection-dir/users/Health check/New Request/event.test.js
new file mode 100644
index 00000000000..5e5505dfa3b
--- /dev/null
+++ b/postman/collection-dir/users/Health check/New Request/event.test.js
@@ -0,0 +1,4 @@
+// Validate status 2xx
+pm.test("[POST]::/health - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
diff --git a/postman/collection-dir/users/Health check/New Request/request.json b/postman/collection-dir/users/Health check/New Request/request.json
new file mode 100644
index 00000000000..4e1e0a0d9e6
--- /dev/null
+++ b/postman/collection-dir/users/Health check/New Request/request.json
@@ -0,0 +1,13 @@
+{
+ "method": "GET",
+ "header": [],
+ "url": {
+ "raw": "{{baseUrl}}/health",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "health"
+ ]
+ }
+}
diff --git a/postman/collection-dir/users/Health check/New Request/response.json b/postman/collection-dir/users/Health check/New Request/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/users/Health check/New Request/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/users/event.prerequest.js b/postman/collection-dir/users/event.prerequest.js
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/postman/collection-dir/users/event.test.js b/postman/collection-dir/users/event.test.js
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/postman/collection-json/users.postman_collection.json b/postman/collection-json/users.postman_collection.json
new file mode 100644
index 00000000000..943d37d22d3
--- /dev/null
+++ b/postman/collection-json/users.postman_collection.json
@@ -0,0 +1,556 @@
+{
+ "event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "item": [
+ {
+ "name": "Health check",
+ "item": [
+ {
+ "name": "New Request",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/health - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [],
+ "url": {
+ "raw": "{{baseUrl}}/health",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "health"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Flow Testcases",
+ "item": [
+ {
+ "name": "Sign Up",
+ "item": [
+ {
+ "name": "Connect Account",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/user/connect_account - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/user/connect_account - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/user/connect_account - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Validate specific JSON response content",
+ "pm.test(\"[POST]::/user/connect_account - Response contains is_email_sent\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData).to.have.property(\"is_email_sent\");",
+ " pm.expect(jsonData.is_email_sent).to.be.true;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "",
+ "var baseEmail = pm.environment.get('user_base_email_for_signup');",
+ "var emailDomain = pm.environment.get(\"user_domain_for_signup\");",
+ "",
+ "// Generate a unique email address",
+ "var uniqueEmail = baseEmail + new Date().getTime() + emailDomain;",
+ "// Set the unique email address as an environment variable",
+ "pm.environment.set('unique_email', uniqueEmail);",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\"email\":\"{{unique_email}}\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/connect_account",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "connect_account"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Sign In",
+ "item": [
+ {
+ "name": "Signin",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/user/v2/signin - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Validate specific JSON response content",
+ "pm.test(\"[POST]::/user/v2/signin - Response contains token\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData).to.have.property(\"token\");",
+ " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Signin Wrong",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status code is 4xx Bad Request",
+ "pm.test(\"[POST]::/user/v2/signin - Status code is 401\", function () {",
+ " pm.response.to.have.status(401);",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/user/v2/signin - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/user/v2/signin - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Signin Token Only",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::user/v2/signin?token_only=true - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Validate specific JSON response content",
+ "pm.test(\"[POST]::user/v2/signin?token_only=true - Response contains token\", function () {",
+ " var jsonData = pm.response.json();",
+ " pm.expect(jsonData).to.have.property(\"token\");",
+ " pm.expect(jsonData.token).to.be.a(\"string\").and.to.not.be.empty;",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{user_password}}\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ],
+ "query": [
+ {
+ "key": "token_only",
+ "value": "true"
+ }
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Signin Token Only Wrong",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 4xx",
+ "pm.test(\"[POST]::/user/v2/signin?token_only=true - Status code is 401\", function () {",
+ " pm.response.to.have.status(401);",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::user/v2/signin?token_only=true - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::user/v2/signin?token_only=true - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Cookie",
+ "value": "Cookie_1=value"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\"email\":\"{{user_email}}\",\"password\":\"{{wrong_password}}\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/user/v2/signin?token_only=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "user",
+ "v2",
+ "signin"
+ ],
+ "query": [
+ {
+ "key": "token_only",
+ "value": "true"
+ }
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "info": {
+ "_postman_id": "b5b40c9a-7e58-42c7-8b89-0adb208c45c9",
+ "name": "users",
+ "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [support@juspay.in](mailto:support@juspay.in)",
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
+ "_exporter_id": "26710321"
+ },
+ "variable": [
+ {
+ "key": "baseUrl",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "admin_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "merchant_id",
+ "value": ""
+ },
+ {
+ "key": "payment_id",
+ "value": ""
+ },
+ {
+ "key": "customer_id",
+ "value": ""
+ },
+ {
+ "key": "mandate_id",
+ "value": ""
+ },
+ {
+ "key": "payment_method_id",
+ "value": ""
+ },
+ {
+ "key": "refund_id",
+ "value": ""
+ },
+ {
+ "key": "merchant_connector_id",
+ "value": ""
+ },
+ {
+ "key": "client_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "publishable_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "payment_token",
+ "value": ""
+ },
+ {
+ "key": "gateway_merchant_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate_keys",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key1",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key2",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_email",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_password",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "wrong_password",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_base_email_for_signup",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "user_domain_for_signup",
+ "value": "",
+ "type": "string"
+ }
+ ]
+}
|
2024-06-06T09:29:26Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
Added test for:
**Health check**
Health Check: expects 200 Ok
Flow Check
**Signup**
Connect account - checks for 200 Ok, content type application/json, response has json body and is_email sent is true
**SignIn**
1. SignIn with correct password: checks for 200 Ok, content type application/json, response has json body and contains token
2. SignIn with wrong password: checks for 401 bad request, content type application/json, response has json body
3. SignIn with correct password token only flow: checks for 200 Ok, content type application/json, response has json body and contains token
4. SignIn with wrong password token only flow: checks for 401 bad request, content type application/json, response has json body
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
closes [#4896](https://github.com/juspay/hyperswitch/issues/4896)
## How did you test it?
Use command to test user module:
```
cargo run --bin test_utils -- --module-name="users" --base-url="http://localhost:8080" --admin-api-key="admin_api_key"
```


The previous working for connector commands remains same, just use connector-name instead of module name:
```
cargo run --bin test_utils -- --connector-name="connector_name" --base-url="http://localhost:8080" --admin-api-key="admin_api_key"
```
The previous command is running test cases for connector mentioned.

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ff93981ec776031af1de946cd6e9f90d2f410cd2
|
Use command to test user module:
```
cargo run --bin test_utils -- --module-name="users" --base-url="http://localhost:8080" --admin-api-key="admin_api_key"
```


The previous working for connector commands remains same, just use connector-name instead of module name:
```
cargo run --bin test_utils -- --connector-name="connector_name" --base-url="http://localhost:8080" --admin-api-key="admin_api_key"
```
The previous command is running test cases for connector mentioned.

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4879
|
Bug: Setup for Opensearch services and global search feature on control center
Add documentation to setup globalsearch & use it in local deployment mode.
|
diff --git a/config/dashboard.toml b/config/dashboard.toml
index 9bb2b6bf336..c00b167315a 100644
--- a/config/dashboard.toml
+++ b/config/dashboard.toml
@@ -31,7 +31,7 @@ surcharge=false
dispute_evidence_upload=false
paypal_automatic_flow=false
threeds_authenticator=false
-global_search=false
+global_search=true
dispute_analytics=true
configure_pmts=false
branding=false
diff --git a/config/prometheus.yaml b/config/prometheus.yaml
index 574c9dcce7a..85f6335c838 100644
--- a/config/prometheus.yaml
+++ b/config/prometheus.yaml
@@ -35,3 +35,11 @@ scrape_configs:
static_configs:
- targets: ["otel-collector:8888"]
+
+ - job_name: "vector"
+
+ # metrics_path defaults to '/metrics'
+ # scheme defaults to 'http'.
+
+ static_configs:
+ - targets: ["vector:9598"]
\ No newline at end of file
diff --git a/config/vector.yaml b/config/vector.yaml
new file mode 100644
index 00000000000..d8f5da34666
--- /dev/null
+++ b/config/vector.yaml
@@ -0,0 +1,134 @@
+acknowledgements:
+ enabled: true
+
+api:
+ enabled: true
+ address: 0.0.0.0:8686
+
+sources:
+ kafka_tx_events:
+ type: kafka
+ bootstrap_servers: kafka0:29092
+ group_id: sessionizer
+ topics:
+ - hyperswitch-payment-attempt-events
+ - hyperswitch-payment-intent-events
+ - hyperswitch-refund-events
+ - hyperswitch-dispute-events
+ decoding:
+ codec: json
+
+ app_logs:
+ type: docker_logs
+ include_labels:
+ - "logs=promtail"
+
+ vector_metrics:
+ type: internal_metrics
+
+ node_metrics:
+ type: host_metrics
+
+transforms:
+ plus_1_events:
+ type: filter
+ inputs:
+ - kafka_tx_events
+ condition: ".sign_flag == 1"
+
+ hs_server_logs:
+ type: filter
+ inputs:
+ - app_logs
+ condition: '.labels."com.docker.compose.service" == "hyperswitch-server"'
+
+ parsed_hs_server_logs:
+ type: remap
+ inputs:
+ - app_logs
+ source: |-
+ .message = parse_json!(.message)
+
+ events:
+ type: remap
+ inputs:
+ - plus_1_events
+ source: |-
+ .timestamp = from_unix_timestamp!(.created_at, unit: "seconds")
+
+sinks:
+ opensearch_events:
+ type: elasticsearch
+ inputs:
+ - events
+ endpoints:
+ - "https://opensearch:9200"
+ id_key: message_key
+ api_version: v7
+ tls:
+ verify_certificate: false
+ verify_hostname: false
+ auth:
+ strategy: basic
+ user: admin
+ password: 0penS3arc#
+ encoding:
+ except_fields:
+ - message_key
+ - offset
+ - partition
+ - topic
+ bulk:
+ # Add a date prefixed index for better grouping
+ # index: "vector-{{ .topic }}-%Y-%m-%d"
+ index: "{{ .topic }}"
+
+ opensearch_logs:
+ type: elasticsearch
+ inputs:
+ - parsed_hs_server_logs
+ endpoints:
+ - "https://opensearch:9200"
+ api_version: v7
+ tls:
+ verify_certificate: false
+ verify_hostname: false
+ auth:
+ strategy: basic
+ user: admin
+ password: 0penS3arc#
+ bulk:
+ # Add a date prefixed index for better grouping
+ # index: "vector-{{ .topic }}-%Y-%m-%d"
+ index: "logs-{{ .container_name }}-%Y-%m-%d"
+
+ log_events:
+ type: loki
+ inputs:
+ - kafka_tx_events
+ endpoint: http://loki:3100
+ labels:
+ source: vector
+ topic: "{{ .topic }}"
+ job: kafka
+ encoding:
+ codec: json
+
+ log_app_loki:
+ type: loki
+ inputs:
+ - parsed_hs_server_logs
+ endpoint: http://loki:3100
+ labels:
+ source: vector
+ job: app_logs
+ container: "{{ .container_name }}"
+ stream: "{{ .stream }}"
+ encoding:
+ codec: json
+
+ metrics:
+ type: prometheus_exporter
+ inputs:
+ - vector_metrics
+ - node_metrics
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index 64064c09c88..ef5efddbe99 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -263,6 +263,7 @@ impl TryInto<RefundFilterRow> for serde_json::Value {
))
}
}
+
impl TryInto<DisputeMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
diff --git a/docker-compose.yml b/docker-compose.yml
index c993262e744..6211148f39e 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -221,18 +221,6 @@ services:
- ./config/grafana.ini:/etc/grafana/grafana.ini
- ./config/grafana-datasource.yaml:/etc/grafana/provisioning/datasources/datasource.yml
- promtail:
- image: grafana/promtail:latest
- volumes:
- - ./logs:/var/log/router
- - ./config:/etc/promtail
- - /var/run/docker.sock:/var/run/docker.sock
- command: -config.file=/etc/promtail/promtail.yaml
- profiles:
- - monitoring
- networks:
- - router_net
-
loki:
image: grafana/loki:latest
ports:
@@ -361,21 +349,13 @@ services:
soft: 262144
hard: 262144
- fluentd:
- build: ./docker/fluentd
- volumes:
- - ./docker/fluentd/conf:/fluentd/etc
- networks:
- - router_net
- profiles:
- - olap
-
opensearch:
- image: public.ecr.aws/opensearchproject/opensearch:1.3.14
+ image: opensearchproject/opensearch:2
container_name: opensearch
hostname: opensearch
environment:
- "discovery.type=single-node"
+ - OPENSEARCH_INITIAL_ADMIN_PASSWORD=0penS3arc#
profiles:
- olap
ports:
@@ -384,7 +364,7 @@ services:
- router_net
opensearch-dashboards:
- image: opensearchproject/opensearch-dashboards:1.3.14
+ image: opensearchproject/opensearch-dashboards:2
ports:
- 5601:5601
profiles:
@@ -393,3 +373,18 @@ services:
OPENSEARCH_HOSTS: '["https://opensearch:9200"]'
networks:
- router_net
+
+ vector:
+ image: timberio/vector:latest-debian
+ ports:
+ - "8686"
+ - "9598"
+ profiles:
+ - olap
+ environment:
+ KAFKA_HOST: 'kafka0:29092'
+ networks:
+ - router_net
+ volumes:
+ - ./config/vector.yaml:/etc/vector/vector.yaml
+ - /var/run/docker.sock:/var/run/docker.sock
\ No newline at end of file
|
2024-06-18T09:59:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Adding a vector service to handle logs & kafka events
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Add a common service to handle all data transformation and transport
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Running it locally to check logs added in loki & opensearch
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
91c8af6ef6d74cc3e0cb55c5f26ca1eae6907709
|
- Running it locally to check logs added in loki & opensearch
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4873
|
Bug: [FEATURE] Integrate AdyenPlatform for processing payouts
### Feature Description
Adyen for Platforms is a marketplace solution which also provides paying out to third parties. This needs to be integrated in HyperSwitch as a payout processor for now.
### Possible Implementation
Integrate Adyen's "Payout to third parties"
ref - https://docs.adyen.com/payouts/payout-service/payout-to-users/
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8f6fb64a4a4..312544c05a0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,72 @@
+# 0.5.0 (2023-03-21)
+
+## Build System / Dependencies
+
+* **deps:** update deps (#734) (16bc886c)
+
+## Chores
+
+* **merchant_account:** remove `api_key` field (#713) (230fcdd4)
+* **config:** move connector base URLs under the `[connectors]` table (#723) (df8c8b5a)
+* address Rust 1.68 clippy lints (#728) (1ffabb40)
+
+## Continuous Integration
+
+* **release:** specify `fetch-depth` for code checkout and use official Docker GitHub actions (#722) (c451368f)
+
+## Documentation Changes
+
+* Update naming conventions and added examples (#709) (98415193)
+* **openapi:** document path parameters for API keys endpoints (#702) (9062dc80)
+
+## New Features
+
+* **connector:**
+ * [Mollie]: add authorize, void, refund, psync, rsync support for mollie connector (#740) (168fa32)
+ * [worldline] add webhook support for connector (#721) (13a8ce8e)
+ * [Trustpay] add authorize (cards 3ds, no3ds and bank redirects), refund, psync, rsync (#717) (e102cae7)
+ * [Fiserv] add Refunds, Cancel and Wallets flow along with Unit Tests (#593) (cd1c5409)
+ * Add support for complete authorize payment after 3DS redirection (#741) (ec2b1b18)
+* removing unnecessary logs from console (#753) (1021d1ae)
+* Time based deletion of temp card (#729) (db3d3164)
+* populate fields from payment attempt in payment list (#736) (b5b3d57c)
+* add generic in-memory cache interface (#737) (7f5e5d86)
+* Add HSTS headers to response (#725) (7ed665ec)
+* cache reverse lookup fetches on redis (#719) (1a27faca)
+* **compatibility:** add webhook support for stripe compatibility (#710) (79160504)
+
+## Bug Fixes
+
+* **docker-compose:** remove port for hyperswitch-server-init in docker-compose.yml (#763) (20b93276)
+* fixing docker compose setup & adding redisinsight (#748) (5c9bec9f)
+* **kms:** log KMS SDK errors using the `Debug` impl (#720) (468aa87f)
+* **errors:**
+ * Replace PaymentMethod with PaymentModethodData in test.rs (#716) (763ee094)
+ * use `Debug` impl instead of `Display` for error types wrapping `error_stack::Report` (#714) (45484752)
+
+## Other Changes
+
+* card_fingerprint not sent by basilisk_hs (#754) (5ae2f63f)
+
+## Refactors
+
+* **merchant_account:** add back `api_key` field for backward compatibility (#761) (661dd48a)
+* **connector:** update add_connector script (#762) (78794ed6)
+* **metrics:** use macros for constructing counter and histogram metrics (#755) (58106d91)
+* **kms:** share a KMS client for all KMS operations (#744) (a3ff2e8d)
+* Basilisk hs integration (#704) (585618e5)
+* Add service_name to get and delete request (#738) (8b7ae9c3)
+* Add secret to metadata (#706) (d36afbed)
+* **client:**
+ * simplify HTTP client construction (#731) (1756d1c4)
+ * remove dependence on `ROUTER_HTTP_PROXY` and `ROUTER_HTTPS_PROXY` env vars (#730) (c085e460)
+* **authentication:** authenticate merchant by API keys from API keys table (#712) (afd08d42)
+* **api_keys:** use a KMS encrypted API key hashing key and remove key ID prefix from plaintext API keys (#639) (3a3b33ac)
+
+## Tests
+
+* **masking:** add suitable feature gates for basic tests (#745) (4859b6e4)
+
# 0.3.0 (2023-03-05)
## Chores
diff --git a/config/Development.toml b/config/Development.toml
index 94bb5c0ad23..4a74b768959 100644
--- a/config/Development.toml
+++ b/config/Development.toml
@@ -17,6 +17,7 @@ host = "localhost"
port = 5432
dbname = "hyperswitch_db"
pool_size = 5
+connection_timeout = 10
[replica_database]
username = "replica_user"
@@ -79,71 +80,29 @@ validity = 1
[api_keys]
hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
-[connectors.aci]
-base_url = "https://eu-test.oppwa.com/"
-
-[connectors.adyen]
-base_url = "https://checkout-test.adyen.com/"
-
-[connectors.authorizedotnet]
-base_url = "https://apitest.authorize.net/xml/v1/request.api"
-
-[connectors.checkout]
-base_url = "https://api.sandbox.checkout.com/"
-
-[connectors.stripe]
-base_url = "https://api.stripe.com/"
-
-[connectors.braintree]
-base_url = "https://api.sandbox.braintreegateway.com/"
-
-[connectors.klarna]
-base_url = "https://api-na.playground.klarna.com/"
-
-[connectors.applepay]
-base_url = "https://apple-pay-gateway.apple.com/"
-
-[connectors.cybersource]
-base_url = "https://apitest.cybersource.com/"
-
-[connectors.shift4]
-base_url = "https://api.shift4.com/"
-
-[connectors.rapyd]
-base_url = "https://sandboxapi.rapyd.net"
-
-[connectors.fiserv]
-base_url = "https://cert.api.fiservapps.com/"
-
-[connectors.worldpay]
-base_url = "https://try.access.worldpay.com/"
-
-[connectors.payu]
-base_url = "https://secure.snd.payu.com/"
-
-[connectors.globalpay]
-base_url = "https://apis.sandbox.globalpay.com/ucp/"
-
-[connectors.worldline]
-base_url = "https://eu.sandbox.api-ingenico.com/"
-
-[connectors.bluesnap]
-base_url = "https://sandbox.bluesnap.com/"
-
-[connectors.nuvei]
-base_url = "https://ppp-test.nuvei.com/"
-
-[connectors.airwallex]
-base_url = "https://api-demo.airwallex.com/"
-
-[connectors.multisafepay]
-base_url = "https://testapi.multisafepay.com/"
-
-[connectors.dlocal]
-base_url = "https://sandbox.dlocal.com/"
-
-[connectors.bambora]
-base_url = "https://api.na.bambora.com"
+[connectors]
+aci.base_url = "https://eu-test.oppwa.com/"
+adyen.base_url = "https://checkout-test.adyen.com/"
+airwallex.base_url = "https://api-demo.airwallex.com/"
+applepay.base_url = "https://apple-pay-gateway.apple.com/"
+authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
+bambora.base_url = "https://api.na.bambora.com"
+bluesnap.base_url = "https://sandbox.bluesnap.com/"
+braintree.base_url = "https://api.sandbox.braintreegateway.com/"
+checkout.base_url = "https://api.sandbox.checkout.com/"
+cybersource.base_url = "https://apitest.cybersource.com/"
+dlocal.base_url = "https://sandbox.dlocal.com/"
+fiserv.base_url = "https://cert.api.fiservapps.com/"
+globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
+klarna.base_url = "https://api-na.playground.klarna.com/"
+multisafepay.base_url = "https://testapi.multisafepay.com/"
+nuvei.base_url = "https://ppp-test.nuvei.com/"
+payu.base_url = "https://secure.snd.payu.com/"
+rapyd.base_url = "https://sandboxapi.rapyd.net"
+shift4.base_url = "https://api.shift4.com/"
+stripe.base_url = "https://api.stripe.com/"
+worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
+worldpay.base_url = "https://try.access.worldpay.com/"
[scheduler]
stream = "SCHEDULER_STREAM"
@@ -153,12 +112,12 @@ disabled = false
consumer_group = "SCHEDULER_GROUP"
[bank_config.eps]
-stripe = {banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau"}
-adyen = {banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag"}
+stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" }
+adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_tirol_bank_ag,posojilnica_bank_e_gen,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag" }
[bank_config.ideal]
-stripe = {banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"}
-adyen = {banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"}
+stripe = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" }
+adyen = { banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot" }
[pm_filters.stripe]
google_pay = { country = "AL,DZ,AS,AO,AG,AR,AU,AT,AZ,BH,BY,BE,BR,BG,CA,CL,CO,HR,CZ,DK,DO,EG,EE,FI,FR,DE,GR,HK,HU,IN,ID,IE,IL,IT,JP,JO,KZ,KE,KW,LV,LB,LT,LU,MY,MX,NL,NZ,NO,OM,PK,PA,PE,PH,PL,PT,QA,RO,RU,SA,SG,SK,ZA,ES,LK,SE,CH,TW,TH,TR,UA,AE,GB,US,UY,VN" }
diff --git a/config/config.example.toml b/config/config.example.toml
index 176a309e067..60f9bdcc5d9 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -121,67 +121,31 @@ hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
# Examples provided here are sandbox/test base urls, can be replaced by live or mock
# base urls based on your need.
# Note: These are not optional attributes. hyperswitch request can fail due to invalid/empty values.
-[connectors.aci]
-base_url = "https://eu-test.oppwa.com/"
-
-[connectors.adyen]
-base_url = "https://checkout-test.adyen.com/"
-
-[connectors.authorizedotnet]
-base_url = "https://apitest.authorize.net/xml/v1/request.api"
-
-[connectors.checkout]
-base_url = "https://api.sandbox.checkout.com/"
-
-[connectors.stripe]
-base_url = "https://api.stripe.com/"
-
-[connectors.braintree]
-base_url = "https://api.sandbox.braintreegateway.com/"
-
-[connectors.klarna]
-base_url = "https://api-na.playground.klarna.com/"
-
-[connectors.applepay]
-base_url = "https://apple-pay-gateway.apple.com/"
-
-[connectors.cybersource]
-base_url = "https://apitest.cybersource.com/"
-
-[connectors.shift4]
-base_url = "https://api.shift4.com/"
-
-[connectors.rapyd]
-base_url = "https://sandboxapi.rapyd.net"
-
-[connectors.fiserv]
-base_url = "https://cert.api.fiservapps.com/"
-
-[connectors.worldpay]
-base_url = "https://try.access.worldpay.com/"
-
-[connectors.globalpay]
-base_url = "https://apis.sandbox.globalpay.com/ucp/"
-
-[connectors.bluesnap]
-base_url = "https://sandbox.bluesnap.com/"
-
-[connectors.nuvei]
-base_url = "https://ppp-test.nuvei.com/"
-
-[connectors.airwallex]
-base_url = "https://api-demo.airwallex.com/"
-
-[connectors.multisafepay]
-base_url = "https://testapi.multisafepay.com/"
-
-[connectors.dlocal]
-base_url = "https://sandbox.dlocal.com/"
+[connectors]
+aci.base_url = "https://eu-test.oppwa.com/"
+adyen.base_url = "https://checkout-test.adyen.com/"
+airwallex.base_url = "https://api-demo.airwallex.com/"
+applepay.base_url = "https://apple-pay-gateway.apple.com/"
+authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
+bambora.base_url = "https://api.na.bambora.com"
+bluesnap.base_url = "https://sandbox.bluesnap.com/"
+braintree.base_url = "https://api.sandbox.braintreegateway.com/"
+checkout.base_url = "https://api.sandbox.checkout.com/"
+cybersource.base_url = "https://apitest.cybersource.com/"
+dlocal.base_url = "https://sandbox.dlocal.com/"
+fiserv.base_url = "https://cert.api.fiservapps.com/"
+globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
+klarna.base_url = "https://api-na.playground.klarna.com/"
+multisafepay.base_url = "https://testapi.multisafepay.com/"
+nuvei.base_url = "https://ppp-test.nuvei.com/"
+payu.base_url = "https://secure.snd.payu.com/"
+rapyd.base_url = "https://sandboxapi.rapyd.net"
+shift4.base_url = "https://api.shift4.com/"
+stripe.base_url = "https://api.stripe.com/"
+worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
+worldpay.base_url = "https://try.access.worldpay.com/"
# This data is used to call respective connectors for wallets and cards
-[connectors.bambora]
-base_url = "https://api.na.bambora.com"
-
[connectors.supported]
wallets = ["klarna", "braintree", "applepay"]
cards = [
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index a0da848ddcf..e7128d3d6b3 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -66,69 +66,34 @@ max_age = 365
[api_keys]
hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
-[connectors.aci]
-base_url = "https://eu-test.oppwa.com/"
-
-[connectors.adyen]
-base_url = "https://checkout-test.adyen.com/"
-
-[connectors.authorizedotnet]
-base_url = "https://apitest.authorize.net/xml/v1/request.api"
-
-[connectors.checkout]
-base_url = "https://api.sandbox.checkout.com/"
-
-[connectors.stripe]
-base_url = "https://api.stripe.com/"
-
-[connectors.braintree]
-base_url = "https://api.sandbox.braintreegateway.com/"
-
-[connectors.klarna]
-base_url = "https://api-na.playground.klarna.com/"
-
-[connectors.applepay]
-base_url = "https://apple-pay-gateway.apple.com/"
-
-[connectors.cybersource]
-base_url = "https://apitest.cybersource.com/"
-
-[connectors.shift4]
-base_url = "https://api.shift4.com/"
-
-[connectors.rapyd]
-base_url = "https://sandboxapi.rapyd.net"
-
-[connectors.fiserv]
-base_url = "https://cert.api.fiservapps.com/"
-
-[connectors.worldpay]
-base_url = "https://try.access.worldpay.com/"
-
-[connectors.globalpay]
-base_url = "https://apis.sandbox.globalpay.com/ucp/"
-
-[connectors.bluesnap]
-base_url = "https://sandbox.bluesnap.com/"
-
-[connectors.nuvei]
-base_url = "https://ppp-test.nuvei.com/"
-
-[connectors.airwallex]
-base_url = "https://api-demo.airwallex.com/"
-
-[connectors.multisafepay]
-base_url = "https://testapi.multisafepay.com/"
-
-[connectors.dlocal]
-base_url = "https://sandbox.dlocal.com/"
-
-[connectors.bambora]
-base_url = "https://api.na.bambora.com"
+[connectors]
+aci.base_url = "https://eu-test.oppwa.com/"
+adyen.base_url = "https://checkout-test.adyen.com/"
+airwallex.base_url = "https://api-demo.airwallex.com/"
+applepay.base_url = "https://apple-pay-gateway.apple.com/"
+authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
+bambora.base_url = "https://api.na.bambora.com"
+bluesnap.base_url = "https://sandbox.bluesnap.com/"
+braintree.base_url = "https://api.sandbox.braintreegateway.com/"
+checkout.base_url = "https://api.sandbox.checkout.com/"
+cybersource.base_url = "https://apitest.cybersource.com/"
+dlocal.base_url = "https://sandbox.dlocal.com/"
+fiserv.base_url = "https://cert.api.fiservapps.com/"
+globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
+klarna.base_url = "https://api-na.playground.klarna.com/"
+multisafepay.base_url = "https://testapi.multisafepay.com/"
+nuvei.base_url = "https://ppp-test.nuvei.com/"
+payu.base_url = "https://secure.snd.payu.com/"
+rapyd.base_url = "https://sandboxapi.rapyd.net"
+shift4.base_url = "https://api.shift4.com/"
+stripe.base_url = "https://api.stripe.com/"
+worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
+worldpay.base_url = "https://try.access.worldpay.com/"
[connectors.supported]
wallets = ["klarna", "braintree", "applepay"]
cards = [
+ "aci",
"adyen",
"airwallex",
"authorizedotnet",
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 92a8bd773fe..f3ed6ff2681 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -66,6 +66,10 @@ pub struct MerchantAccountCreate {
/// An identifier for the vault used to store payment method information.
#[schema(example = "locker_abc123")]
pub locker_id: Option<String>,
+
+ ///Default business details for connector routing
+ #[schema(value_type = Option<PrimaryBusinessDetails>)]
+ pub primary_business_details: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Deserialize, ToSchema)]
@@ -127,6 +131,9 @@ pub struct MerchantAccountUpdate {
/// An identifier for the vault used to store payment method information.
#[schema(example = "locker_abc123")]
pub locker_id: Option<String>,
+
+ ///Default business details for connector routing
+ pub primary_business_details: Option<PrimaryBusinessDetails>,
}
#[derive(Clone, Debug, ToSchema, Serialize)]
@@ -190,6 +197,10 @@ pub struct MerchantAccountResponse {
/// An identifier for the vault used to store payment method information.
#[schema(example = "locker_abc123")]
pub locker_id: Option<String>,
+
+ ///Default business details for connector routing
+ #[schema(value_type = Option<PrimaryBusinessDetails>)]
+ pub primary_business_details: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
@@ -240,6 +251,13 @@ pub enum RoutingAlgorithm {
Single(api_enums::RoutableConnectors),
}
+#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct PrimaryBusinessDetails {
+ country: String,
+ business: String,
+}
+
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct WebhookDetails {
@@ -303,6 +321,15 @@ pub struct MerchantConnector {
/// Name of the Connector
#[schema(example = "stripe")]
pub connector_name: String,
+ /// Connector label for specific country and Business
+ #[schema(example = "stripe_US_travel")]
+ pub connector_label: String,
+ /// Country through which payment should be processed
+ #[schema(example = "US")]
+ pub business_country: String,
+ ///Business Type of the merchant
+ #[schema(example = "travel")]
+ pub business_label: String,
/// Unique ID of the connector
#[schema(example = "mca_5apGeP94tMts6rg3U3kR")]
pub merchant_connector_id: Option<String>,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 0cfb48650b5..3b7c256614d 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -34,19 +34,38 @@ pub async fn create_merchant_account(
let api_key = Some(create_merchant_api_key().into());
- let merchant_details = Some(
- utils::Encode::<api::MerchantDetails>::encode_to_value(&req.merchant_details)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "merchant_details",
- })?,
- );
-
- let webhook_details = Some(
- utils::Encode::<api::WebhookDetails>::encode_to_value(&req.webhook_details)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "webhook details",
- })?,
- );
+ let merchant_details = req
+ .merchant_details
+ .map(|md| {
+ utils::Encode::<api::MerchantDetails>::encode_to_value(&md).change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "merchant_details",
+ },
+ )
+ })
+ .transpose()?;
+
+ let webhook_details = req
+ .webhook_details
+ .map(|wd| {
+ utils::Encode::<api::WebhookDetails>::encode_to_value(&wd).change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "webhook details",
+ },
+ )
+ })
+ .transpose()?;
+
+ let primary_business_details = req
+ .primary_business_details
+ .map(|pbd| {
+ utils::Encode::<api::PrimaryBusinessDetails>::encode_to_value(&pbd).change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "default business details",
+ },
+ )
+ })
+ .transpose()?;
if let Some(ref routing_algorithm) = req.routing_algorithm {
let _: api::RoutingAlgorithm = routing_algorithm
@@ -79,6 +98,7 @@ pub async fn create_merchant_account(
publishable_key,
locker_id: req.locker_id,
metadata: req.metadata,
+ primary_business_details,
};
let merchant_account = db
@@ -171,6 +191,12 @@ pub async fn merchant_account_update(
metadata: req.metadata,
api_key: None,
publishable_key: None,
+ primary_business_details: req
+ .primary_business_details
+ .as_ref()
+ .map(utils::Encode::<api::PrimaryBusinessDetails>::encode_to_value)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
};
let response = db
@@ -292,6 +318,9 @@ pub async fn create_payment_connector(
test_mode: req.test_mode,
disabled: req.disabled,
metadata: req.metadata,
+ connector_label: Some(req.connector_label),
+ business_country: Some(req.business_country),
+ business_label: Some(req.business_label),
};
let mca = store
@@ -402,6 +431,9 @@ pub async fn update_payment_connector(
test_mode: req.test_mode,
disabled: req.disabled,
metadata: req.metadata,
+ connector_label: Some(req.connector_label),
+ business_country: Some(req.business_country),
+ business_label: Some(req.business_label),
};
let updated_mca = db
@@ -432,6 +464,9 @@ pub async fn update_payment_connector(
disabled: updated_mca.disabled,
payment_methods_enabled: updated_pm_enabled,
metadata: updated_mca.metadata,
+ connector_label: updated_mca.connector_label,
+ business_country: updated_mca.business_country,
+ business_label: updated_mca.business_label,
};
Ok(service_api::ApplicationResponse::Json(response))
}
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index de1d0d71f74..9cda9e9562f 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -1,10 +1,8 @@
-use common_utils::{date_time, errors::CustomResult, fp_utils};
+use common_utils::date_time;
use error_stack::{report, IntoReport, ResultExt};
-use masking::{PeekInterface, Secret, StrongSecret};
+use masking::{PeekInterface, StrongSecret};
use router_env::{instrument, tracing};
-#[cfg(feature = "kms")]
-use crate::services::kms;
use crate::{
configs::settings,
consts,
@@ -14,6 +12,8 @@ use crate::{
types::{api, storage, transformers::ForeignInto},
utils,
};
+#[cfg(feature = "kms")]
+use crate::{routes::metrics, services::kms};
pub static HASH_KEY: tokio::sync::OnceCell<StrongSecret<[u8; PlaintextApiKey::HASH_KEY_LEN]>> =
tokio::sync::OnceCell::const_new();
@@ -28,6 +28,10 @@ pub async fn get_hash_key(
api_key_config.kms_encrypted_hash_key.clone(),
)
.await
+ .map_err(|error| {
+ metrics::AWS_KMS_FAILURES.add(&metrics::CONTEXT, 1, &[]);
+ error
+ })
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to KMS decrypt API key hashing key")?;
@@ -49,11 +53,13 @@ pub async fn get_hash_key(
// 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(Secret<String>);
+pub struct PlaintextApiKey(StrongSecret<String>);
+
+#[derive(Debug, PartialEq, Eq)]
pub struct HashedApiKey(String);
impl PlaintextApiKey {
- pub const HASH_KEY_LEN: usize = 32;
+ const HASH_KEY_LEN: usize = 32;
const PREFIX_LEN: usize = 12;
@@ -107,22 +113,6 @@ impl PlaintextApiKey {
.to_string(),
)
}
-
- pub fn verify_hash(
- &self,
- key: &[u8; Self::HASH_KEY_LEN],
- stored_api_key: &HashedApiKey,
- ) -> CustomResult<(), errors::ApiKeyError> {
- // Converting both hashes to `blake3::Hash` since it provides constant-time equality checks
- let provided_api_key_hash = blake3::keyed_hash(key, self.0.peek().as_bytes());
- let stored_api_key_hash = blake3::Hash::from_hex(&stored_api_key.0)
- .into_report()
- .change_context(errors::ApiKeyError::FailedToReadHashFromHex)?;
-
- fp_utils::when(provided_api_key_hash != stored_api_key_hash, || {
- Err(errors::ApiKeyError::HashVerificationFailed).into_report()
- })
- }
}
#[instrument(skip_all)]
@@ -165,7 +155,7 @@ pub async fn retrieve_api_key(
key_id: &str,
) -> RouterResponse<api::RetrieveApiKeyResponse> {
let api_key = store
- .find_api_key_optional(key_id)
+ .find_api_key_by_key_id_optional(key_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve new API key")?
@@ -224,12 +214,30 @@ pub async fn list_api_keys(
Ok(ApplicationResponse::Json(api_keys))
}
+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)]
@@ -251,8 +259,7 @@ mod tests {
hashed_api_key.0.as_bytes()
);
- plaintext_api_key
- .verify_hash(hash_key.peek(), &hashed_api_key)
- .unwrap();
+ let new_hashed_api_key = plaintext_api_key.keyed_hash(hash_key.peek());
+ assert_eq!(hashed_api_key, new_hashed_api_key)
}
}
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index f3bd6c4a7d4..7c9bfa42306 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -414,11 +414,3 @@ pub enum WebhooksFlowError {
#[error("Resource not found")]
ResourceNotFound,
}
-
-#[derive(Debug, thiserror::Error)]
-pub enum ApiKeyError {
- #[error("Failed to read API key hash from hexadecimal string")]
- FailedToReadHashFromHex,
- #[error("Failed to verify provided API key hash against stored API key hash")]
- HashVerificationFailed,
-}
diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs
index 85aa26ee3ff..3fc17302854 100644
--- a/crates/router/src/db/api_keys.rs
+++ b/crates/router/src/db/api_keys.rs
@@ -22,11 +22,16 @@ pub trait ApiKeyInterface {
async fn revoke_api_key(&self, key_id: &str) -> CustomResult<bool, errors::StorageError>;
- async fn find_api_key_optional(
+ async fn find_api_key_by_key_id_optional(
&self,
key_id: &str,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>;
+ async fn find_api_key_by_hash_optional(
+ &self,
+ hashed_api_key: storage::HashedApiKey,
+ ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>;
+
async fn list_api_keys_by_merchant_id(
&self,
merchant_id: &str,
@@ -69,7 +74,7 @@ impl ApiKeyInterface for Store {
.into_report()
}
- async fn find_api_key_optional(
+ async fn find_api_key_by_key_id_optional(
&self,
key_id: &str,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
@@ -80,6 +85,17 @@ impl ApiKeyInterface for Store {
.into_report()
}
+ async fn find_api_key_by_hash_optional(
+ &self,
+ hashed_api_key: storage::HashedApiKey,
+ ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
+ let conn = pg_connection(&self.master_pool).await?;
+ storage::ApiKey::find_optional_by_hashed_api_key(&conn, hashed_api_key)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn list_api_keys_by_merchant_id(
&self,
merchant_id: &str,
@@ -118,7 +134,7 @@ impl ApiKeyInterface for MockDb {
Err(errors::StorageError::MockDbError)?
}
- async fn find_api_key_optional(
+ async fn find_api_key_by_key_id_optional(
&self,
_key_id: &str,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
@@ -126,6 +142,14 @@ impl ApiKeyInterface for MockDb {
Err(errors::StorageError::MockDbError)?
}
+ async fn find_api_key_by_hash_optional(
+ &self,
+ _hashed_api_key: storage::HashedApiKey,
+ ) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
+ // [#172]: Implement function for `MockDb`
+ Err(errors::StorageError::MockDbError)?
+ }
+
async fn list_api_keys_by_merchant_id(
&self,
_merchant_id: &str,
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index 83460fc7e9e..7c611aea428 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -215,6 +215,7 @@ impl MerchantAccountInterface for MockDb {
storage_scheme: enums::MerchantStorageScheme::PostgresOnly,
locker_id: merchant_account.locker_id,
metadata: merchant_account.metadata,
+ primary_business_details: merchant_account.primary_business_details,
};
accounts.push(account.clone());
Ok(account)
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 640a4dd503c..6f89ece579a 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -290,6 +290,9 @@ impl MerchantConnectorAccountInterface for MockDb {
connector_type: t
.connector_type
.unwrap_or(crate::types::storage::enums::ConnectorType::FinOperations),
+ connector_label: t.connector_label.unwrap_or_default(),
+ business_country: t.business_country.unwrap_or_default(),
+ business_label: t.business_label.unwrap_or_default(),
};
accounts.push(account.clone());
Ok(account)
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index d01e4c0090f..c2a60311ca4 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -5,11 +5,12 @@ use router_env::opentelemetry::{
Context,
};
+use crate::create_counter;
+
pub static CONTEXT: Lazy<Context> = Lazy::new(Context::current);
static GLOBAL_METER: Lazy<Meter> = Lazy::new(|| global::meter("ROUTER_API"));
-pub(crate) static HEALTH_METRIC: Lazy<Counter<u64>> =
- Lazy::new(|| GLOBAL_METER.u64_counter("HEALTH_API").init());
-
-pub(crate) static KV_MISS: Lazy<Counter<u64>> =
- Lazy::new(|| GLOBAL_METER.u64_counter("KV_MISS").init());
+create_counter!(HEALTH_METRIC, GLOBAL_METER); // No. of health API hits
+create_counter!(KV_MISS, GLOBAL_METER); // No. of KV misses
+#[cfg(feature = "kms")]
+create_counter!(AWS_KMS_FAILURES, GLOBAL_METER); // No. of AWS KMS API failures
diff --git a/crates/router/src/scheduler/metrics.rs b/crates/router/src/scheduler/metrics.rs
index aa4363c329b..3fe40a6d32e 100644
--- a/crates/router/src/scheduler/metrics.rs
+++ b/crates/router/src/scheduler/metrics.rs
@@ -11,6 +11,7 @@ static PT_METER: Lazy<Meter> = Lazy::new(|| global::meter("PROCESS_TRACKER"));
pub(crate) static CONSUMER_STATS: Lazy<Histogram<f64>> =
Lazy::new(|| PT_METER.f64_histogram("CONSUMER_OPS").init());
+#[macro_export]
macro_rules! create_counter {
($name:ident, $meter:ident) => {
pub(crate) static $name: Lazy<Counter<u64>> =
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index e56d3efbe1d..15e5fe2ff9f 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -1,11 +1,16 @@
use actix_web::http::header::HeaderMap;
use api_models::{payment_methods::PaymentMethodListRequest, payments::PaymentsRequest};
use async_trait::async_trait;
+use common_utils::date_time;
use error_stack::{report, IntoReport, ResultExt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
+use masking::PeekInterface;
use crate::{
- core::errors::{self, RouterResult},
+ core::{
+ api_keys,
+ errors::{self, RouterResult},
+ },
db::StorageInterface,
routes::{app::AppStateInfo, AppState},
services::api,
@@ -38,11 +43,45 @@ where
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<storage::MerchantAccount> {
- let api_key =
- get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
+ let api_key = get_api_key(request_headers)
+ .change_context(errors::ApiErrorResponse::Unauthorized)?
+ .trim();
+ if api_key.is_empty() {
+ return Err(errors::ApiErrorResponse::Unauthorized)
+ .into_report()
+ .attach_printable("API key is empty");
+ }
+
+ let api_key = api_keys::PlaintextApiKey::from(api_key);
+ let hash_key = {
+ let config = state.conf();
+ api_keys::HASH_KEY
+ .get_or_try_init(|| api_keys::get_hash_key(&config.api_keys))
+ .await?
+ };
+ let hashed_api_key = api_key.keyed_hash(hash_key.peek());
+
+ let stored_api_key = state
+ .store()
+ .find_api_key_by_hash_optional(hashed_api_key.into())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
+ .attach_printable("Failed to retrieve API key")?
+ .ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None`
+ .attach_printable("Merchant not authenticated")?;
+
+ if stored_api_key
+ .expires_at
+ .map(|expires_at| expires_at < date_time::now())
+ .unwrap_or(false)
+ {
+ return Err(report!(errors::ApiErrorResponse::Unauthorized))
+ .attach_printable("API key has expired");
+ }
+
state
.store()
- .find_merchant_account_by_api_key(api_key)
+ .find_merchant_account_by_merchant_id(&stored_api_key.merchant_id)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 0d353785bf0..e5758a9ae49 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -1,8 +1,8 @@
pub use api_models::admin::{
MerchantAccountCreate, MerchantAccountDeleteResponse, MerchantAccountResponse,
MerchantAccountUpdate, MerchantConnector, MerchantConnectorDeleteResponse, MerchantConnectorId,
- MerchantDetails, MerchantId, PaymentMethodsEnabled, RoutingAlgorithm, ToggleKVRequest,
- ToggleKVResponse, WebhookDetails,
+ MerchantDetails, MerchantId, PaymentMethodsEnabled, PrimaryBusinessDetails, RoutingAlgorithm,
+ ToggleKVRequest, ToggleKVResponse, WebhookDetails,
};
use crate::types::{storage, transformers::ForeignFrom};
@@ -26,6 +26,7 @@ impl ForeignFrom<storage::MerchantAccount> for MerchantAccountResponse {
publishable_key: item.publishable_key,
metadata: item.metadata,
locker_id: item.locker_id,
+ primary_business_details: item.primary_business_details,
}
}
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 1ad30bd3a60..f80ae964845 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -336,6 +336,9 @@ impl ForeignTryFrom<storage::MerchantConnectorAccount> for api_models::admin::Me
disabled: merchant_ca.disabled,
metadata: merchant_ca.metadata,
payment_methods_enabled,
+ connector_label: merchant_ca.connector_label,
+ business_country: merchant_ca.business_country,
+ business_label: merchant_ca.business_label,
})
}
}
diff --git a/crates/storage_models/src/api_keys.rs b/crates/storage_models/src/api_keys.rs
index 01df902e8ee..650ea0c7fa1 100644
--- a/crates/storage_models/src/api_keys.rs
+++ b/crates/storage_models/src/api_keys.rs
@@ -81,6 +81,12 @@ impl From<ApiKeyUpdate> for ApiKeyUpdateInternal {
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct HashedApiKey(String);
+impl HashedApiKey {
+ pub fn into_inner(self) -> String {
+ self.0
+ }
+}
+
impl From<String> for HashedApiKey {
fn from(hashed_api_key: String) -> Self {
Self(hashed_api_key)
diff --git a/crates/storage_models/src/merchant_account.rs b/crates/storage_models/src/merchant_account.rs
index 6a207bb194e..dcb638180a5 100644
--- a/crates/storage_models/src/merchant_account.rs
+++ b/crates/storage_models/src/merchant_account.rs
@@ -34,6 +34,7 @@ pub struct MerchantAccount {
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
+ pub primary_business_details: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)]
@@ -54,6 +55,7 @@ pub struct MerchantAccountNew {
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
+ pub primary_business_details: Option<serde_json::Value>,
}
#[derive(Debug)]
@@ -73,6 +75,7 @@ pub enum MerchantAccountUpdate {
locker_id: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
routing_algorithm: Option<serde_json::Value>,
+ primary_business_details: Option<serde_json::Value>,
},
StorageSchemeUpdate {
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -97,6 +100,7 @@ pub struct MerchantAccountUpdateInternal {
locker_id: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
routing_algorithm: Option<serde_json::Value>,
+ primary_business_details: Option<serde_json::Value>,
}
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
@@ -117,6 +121,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
publishable_key,
locker_id,
metadata,
+ primary_business_details,
} => Self {
merchant_name,
api_key,
@@ -132,6 +137,7 @@ impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
publishable_key,
locker_id,
metadata,
+ primary_business_details,
..Default::default()
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
diff --git a/crates/storage_models/src/merchant_connector_account.rs b/crates/storage_models/src/merchant_connector_account.rs
index 08d3fa21fa3..0f3560d01fc 100644
--- a/crates/storage_models/src/merchant_connector_account.rs
+++ b/crates/storage_models/src/merchant_connector_account.rs
@@ -28,6 +28,9 @@ pub struct MerchantConnectorAccount {
pub payment_methods_enabled: Option<Vec<serde_json::Value>>,
pub connector_type: storage_enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
+ pub connector_label: String,
+ pub business_country: String,
+ pub business_label: String,
}
#[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)]
@@ -42,6 +45,9 @@ pub struct MerchantConnectorAccountNew {
pub merchant_connector_id: String,
pub payment_methods_enabled: Option<Vec<serde_json::Value>>,
pub metadata: Option<pii::SecretSerdeValue>,
+ pub connector_label: Option<String>,
+ pub business_country: Option<String>,
+ pub business_label: Option<String>,
}
#[derive(Debug)]
@@ -56,6 +62,9 @@ pub enum MerchantConnectorAccountUpdate {
merchant_connector_id: Option<String>,
payment_methods_enabled: Option<Vec<serde_json::Value>>,
metadata: Option<pii::SecretSerdeValue>,
+ connector_label: Option<String>,
+ business_country: Option<String>,
+ business_label: Option<String>,
},
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -70,6 +79,9 @@ pub struct MerchantConnectorAccountUpdateInternal {
merchant_connector_id: Option<String>,
payment_methods_enabled: Option<Vec<serde_json::Value>>,
metadata: Option<pii::SecretSerdeValue>,
+ connector_label: Option<String>,
+ business_country: Option<String>,
+ business_label: Option<String>,
}
impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal {
@@ -85,6 +97,9 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
merchant_connector_id,
payment_methods_enabled,
metadata,
+ connector_label,
+ business_country,
+ business_label,
} => Self {
merchant_id,
connector_type,
@@ -95,6 +110,9 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
merchant_connector_id,
payment_methods_enabled,
metadata,
+ connector_label,
+ business_country,
+ business_label,
},
}
}
diff --git a/crates/storage_models/src/query/api_keys.rs b/crates/storage_models/src/query/api_keys.rs
index dde38dc6f82..4d1e317276c 100644
--- a/crates/storage_models/src/query/api_keys.rs
+++ b/crates/storage_models/src/query/api_keys.rs
@@ -3,7 +3,7 @@ use router_env::{instrument, tracing};
use super::generics;
use crate::{
- api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, ApiKeyUpdateInternal},
+ api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, ApiKeyUpdateInternal, HashedApiKey},
errors,
schema::api_keys::dsl,
PgPooledConn, StorageResult,
@@ -65,6 +65,18 @@ impl ApiKey {
.await
}
+ #[instrument(skip(conn))]
+ pub async fn find_optional_by_hashed_api_key(
+ conn: &PgPooledConn,
+ hashed_api_key: HashedApiKey,
+ ) -> StorageResult<Option<Self>> {
+ generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::hashed_api_key.eq(hashed_api_key),
+ )
+ .await
+ }
+
#[instrument(skip(conn))]
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
diff --git a/crates/storage_models/src/schema.rs b/crates/storage_models/src/schema.rs
index 37177412dee..d1da47b694e 100644
--- a/crates/storage_models/src/schema.rs
+++ b/crates/storage_models/src/schema.rs
@@ -177,6 +177,7 @@ diesel::table! {
locker_id -> Nullable<Varchar>,
metadata -> Nullable<Jsonb>,
routing_algorithm -> Nullable<Json>,
+ primary_business_details -> Nullable<Json>,
}
}
@@ -195,6 +196,9 @@ diesel::table! {
payment_methods_enabled -> Nullable<Array<Nullable<Json>>>,
connector_type -> ConnectorType,
metadata -> Nullable<Jsonb>,
+ connector_label -> Varchar,
+ business_country -> Varchar,
+ business_label -> Varchar,
}
}
diff --git a/loadtest/config/Development.toml b/loadtest/config/Development.toml
index dc13cba049f..b011c3866b6 100644
--- a/loadtest/config/Development.toml
+++ b/loadtest/config/Development.toml
@@ -52,59 +52,29 @@ outgoing_enabled = true
[api_keys]
hash_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
-[connectors.aci]
-base_url = "https://eu-test.oppwa.com/"
-
-[connectors.adyen]
-base_url = "https://checkout-test.adyen.com/"
-
-[connectors.authorizedotnet]
-base_url = "https://apitest.authorize.net/xml/v1/request.api"
-
-[connectors.checkout]
-base_url = "https://api.sandbox.checkout.com/"
-
-[connectors.stripe]
-base_url = "http://stripe-mock:12111/"
-
-[connectors.braintree]
-base_url = "https://api.sandbox.braintreegateway.com/"
-
-[connectors.cybersource]
-base_url = "https://apitest.cybersource.com/"
-
-[connectors.shift4]
-base_url = "https://api.shift4.com/"
-
-[connectors.worldpay]
-base_url = "https://try.access.worldpay.com/"
-
-[connectors.globalpay]
-base_url = "https://apis.sandbox.globalpay.com/ucp/"
-
-[connectors.applepay]
-base_url = "https://apple-pay-gateway.apple.com/"
-
-[connectors.klarna]
-base_url = "https://api-na.playground.klarna.com/"
-
-[connectors.bluesnap]
-base_url = "https://sandbox.bluesnap.com/"
-
-[connectors.nuvei]
-base_url = "https://ppp-test.nuvei.com/"
-
-[connectors.airwallex]
-base_url = "https://api-demo.airwallex.com/"
-
-[connectors.multisafepay]
-base_url = "https://testapi.multisafepay.com/"
-
-[connectors.dlocal]
-base_url = "https://sandbox.dlocal.com/"
-
-[connectors.bambora]
-base_url = "https://api.na.bambora.com"
+[connectors]
+aci.base_url = "https://eu-test.oppwa.com/"
+adyen.base_url = "https://checkout-test.adyen.com/"
+airwallex.base_url = "https://api-demo.airwallex.com/"
+applepay.base_url = "https://apple-pay-gateway.apple.com/"
+authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"
+bambora.base_url = "https://api.na.bambora.com"
+bluesnap.base_url = "https://sandbox.bluesnap.com/"
+braintree.base_url = "https://api.sandbox.braintreegateway.com/"
+checkout.base_url = "https://api.sandbox.checkout.com/"
+cybersource.base_url = "https://apitest.cybersource.com/"
+dlocal.base_url = "https://sandbox.dlocal.com/"
+fiserv.base_url = "https://cert.api.fiservapps.com/"
+globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
+klarna.base_url = "https://api-na.playground.klarna.com/"
+multisafepay.base_url = "https://testapi.multisafepay.com/"
+nuvei.base_url = "https://ppp-test.nuvei.com/"
+payu.base_url = "https://secure.snd.payu.com/"
+rapyd.base_url = "https://sandboxapi.rapyd.net"
+shift4.base_url = "https://api.shift4.com/"
+stripe.base_url = "https://api.stripe.com/"
+worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
+worldpay.base_url = "https://try.access.worldpay.com/"
[connectors.supported]
wallets = ["klarna", "braintree", "applepay"]
diff --git a/migrations/2023-02-20-101809_update_merchant_connector_account/down.sql b/migrations/2023-02-20-101809_update_merchant_connector_account/down.sql
new file mode 100644
index 00000000000..8f751101092
--- /dev/null
+++ b/migrations/2023-02-20-101809_update_merchant_connector_account/down.sql
@@ -0,0 +1,7 @@
+ALTER TABLE merchant_connector_account
+DROP COLUMN IF EXISTS connector_label,
+DROP COLUMN IF EXISTS business_country,
+DROP COLUMN IF EXISTS business_label;
+
+DROP INDEX IF EXISTS merchant_connector_account_merchant_id_connector_label_index;
+CREATE UNIQUE INDEX merchant_connector_account_merchant_id_connector_name_index ON merchant_connector_account (merchant_id, connector_name);
\ No newline at end of file
diff --git a/migrations/2023-02-20-101809_update_merchant_connector_account/up.sql b/migrations/2023-02-20-101809_update_merchant_connector_account/up.sql
new file mode 100644
index 00000000000..567c869041a
--- /dev/null
+++ b/migrations/2023-02-20-101809_update_merchant_connector_account/up.sql
@@ -0,0 +1,8 @@
+ALTER TABLE merchant_connector_account
+ADD COLUMN connector_label VARCHAR(255) NOT NULL,
+ADD COLUMN business_country VARCHAR(64) NOT NULL,
+ADD COLUMN business_label VARCHAR(255) NOT NULL;
+
+DROP INDEX merchant_connector_account_merchant_id_connector_name_index;
+
+CREATE UNIQUE INDEX merchant_connector_account_merchant_id_connector_label_index ON merchant_connector_account (merchant_id, connector_label);
\ No newline at end of file
diff --git a/migrations/2023-02-21-065628_update_merchant_account/down.sql b/migrations/2023-02-21-065628_update_merchant_account/down.sql
new file mode 100644
index 00000000000..7ed0ee435ce
--- /dev/null
+++ b/migrations/2023-02-21-065628_update_merchant_account/down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE merchant_account
+DROP COLUMN primary_business_details;
\ No newline at end of file
diff --git a/migrations/2023-02-21-065628_update_merchant_account/up.sql b/migrations/2023-02-21-065628_update_merchant_account/up.sql
new file mode 100644
index 00000000000..606d58b6603
--- /dev/null
+++ b/migrations/2023-02-21-065628_update_merchant_account/up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE merchant_account
+ADD COLUMN primary_business_details JSON;
\ No newline at end of file
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
old mode 100644
new mode 100755
index be5f201656e..061e3e5b71f
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -1,3 +1,5 @@
+#! /usr/bin/env bash
+
pg=$1;
pgc="$(tr '[:lower:]' '[:upper:]' <<< ${pg:0:1})${pg:1}"
src="crates/router/src"
@@ -9,41 +11,45 @@ if [[ -z "$pg" ]]; then
exit
fi
cd $SCRIPT/..
+
# remove template files if already created for this connector
rm -rf $conn/$pg $conn/$pg.rs
git checkout $conn.rs $src/types/api.rs $src/configs/settings.rs config/Development.toml config/docker_compose.toml config/config.example.toml loadtest/config/Development.toml crates/api_models/src/enums.rs
+
# add enum for this connector in required places
sed -i'' -e "s/pub use self::{/pub mod ${pg};\n\npub use self::{/" $conn.rs
sed -i'' -e "s/};/${pg}::${pgc},\n};/" $conn.rs
sed -i'' -e "s/_ => Err/\"${pg}\" => Ok(Box::new(\&connector::${pgc})),\n\t\t\t_ => Err/" $src/types/api.rs
sed -i'' -e "s/pub supported: SupportedConnectors,/pub supported: SupportedConnectors,\n\tpub ${pg}: ConnectorParams,/" $src/configs/settings.rs
-sed -i'' -e "s/\[scheduler\]/[connectors.${pg}]\nbase_url = \"\"\n\n[scheduler]/" config/Development.toml
-sed -r -i'' -e "s/cards = \[/cards = [\n\t\"${pg}\",/" config/Development.toml
-sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" config/docker_compose.toml
-sed -r -i'' -e "s/cards = \[/cards = [\n\t\"${pg}\",/" config/docker_compose.toml
-sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" config/config.example.toml
-sed -r -i'' -e "s/cards = \[/cards = [\n\t\"${pg}\",/" config/config.example.toml
-sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" loadtest/config/Development.toml
-sed -r -i'' -e "s/cards = \[/cards = [\n\t\"${pg}\",/" loadtest/config/Development.toml
+sed -i'' -e "s/\[connectors\]/[connectors]\n${pg}.base_url = \"\"/" config/Development.toml config/docker_compose.toml config/config.example.toml loadtest/config/Development.toml
+sed -r -i'' -e "s/cards = \[/cards = [\n \"${pg}\",/" config/Development.toml config/docker_compose.toml config/config.example.toml loadtest/config/Development.toml
sed -i'' -e "s/Dummy,/Dummy,\n\t${pgc},/" crates/api_models/src/enums.rs
sed -i'' -e "s/pub enum RoutableConnectors {/pub enum RoutableConnectors {\n\t${pgc},/" crates/api_models/src/enums.rs
+
# remove temporary files created in above step
rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/Development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/Development.toml-e crates/api_models/src/enums.rs-e
cd $conn/
+
# generate template files for the connector
cargo install cargo-generate
cargo gen-pg $pg
+
# move sub files and test files to appropriate folder
mv $pg/mod.rs $pg.rs
mv $pg/test.rs ${tests}/$pg.rs
+
# remove changes from tests if already done for this connector
git checkout ${tests}/main.rs ${tests}/connector_auth.rs
+
# add enum for this connector in test folder
sed -i'' -e "s/mod utils;/mod ${pg};\nmod utils;/" ${tests}/main.rs
sed -i'' -e "s/struct ConnectorAuthentication {/struct ConnectorAuthentication {\n\tpub ${pg}: Option<HeaderKey>,/" ${tests}/connector_auth.rs
+
# remove temporary files created in above step
rm ${tests}/main.rs-e ${tests}/connector_auth.rs-e
-cargo build
+cargo +nightly fmt --all
+cargo check
echo "Successfully created connector. Running the tests of "$pg.rs
+
# runs tests for the new connector
cargo test --package router --test connectors -- $pg
\ No newline at end of file
|
2023-03-21T08:56:47Z
|
# 0.5.0 (2023-03-21)
## Build System / Dependencies
* **deps:** update deps (#734) (16bc886c)
## Chores
* **merchant_account:** remove `api_key` field (#713) (230fcdd4)
* **config:** move connector base URLs under the `[connectors]` table (#723) (df8c8b5a)
* address Rust 1.68 clippy lints (#728) (1ffabb40)
## Continuous Integration
* **release:** specify `fetch-depth` for code checkout and use official Docker GitHub actions (#722) (c451368f)
## Documentation Changes
* Update naming conventions and added examples (#709) (98415193)
* **openapi:** document path parameters for API keys endpoints (#702) (9062dc80)
## New Features
* **connector:**
* [Mollie]: add authorize, void, refund, psync, rsync support for mollie connector (#740) (168fa32)
* [worldline] add webhook support for connector (#721) (13a8ce8e)
* [Trustpay] add authorize (cards 3ds, no3ds and bank redirects), refund, psync, rsync (#717) (e102cae7)
* [Fiserv] add Refunds, Cancel and Wallets flow along with Unit Tests (#593) (cd1c5409)
* Add support for complete authorize payment after 3DS redirection (#741) (ec2b1b18)
* removing unnecessary logs from console (#753) (1021d1ae)
* Time based deletion of temp card (#729) (db3d3164)
* populate fields from payment attempt in payment list (#736) (b5b3d57c)
* add generic in-memory cache interface (#737) (7f5e5d86)
* Add HSTS headers to response (#725) (7ed665ec)
* cache reverse lookup fetches on redis (#719) (1a27faca)
* **compatibility:** add webhook support for stripe compatibility (#710) (79160504)
## Bug Fixes
* **docker-compose:** remove port for hyperswitch-server-init in docker-compose.yml (#763) (20b93276)
* fixing docker compose setup & adding redisinsight (#748) (5c9bec9f)
* **kms:** log KMS SDK errors using the `Debug` impl (#720) (468aa87f)
* **errors:**
* Replace PaymentMethod with PaymentModethodData in test.rs (#716) (763ee094)
* use `Debug` impl instead of `Display` for error types wrapping `error_stack::Report` (#714) (45484752)
## Other Changes
* card_fingerprint not sent by basilisk_hs (#754) (5ae2f63f)
## Refactors
* **merchant_account:** add back `api_key` field for backward compatibility (#761) (661dd48a)
* **connector:** update add_connector script (#762) (78794ed6)
* **metrics:** use macros for constructing counter and histogram metrics (#755) (58106d91)
* **kms:** share a KMS client for all KMS operations (#744) (a3ff2e8d)
* Basilisk hs integration (#704) (585618e5)
* Add service_name to get and delete request (#738) (8b7ae9c3)
* Add secret to metadata (#706) (d36afbed)
* **client:**
* simplify HTTP client construction (#731) (1756d1c4)
* remove dependence on `ROUTER_HTTP_PROXY` and `ROUTER_HTTPS_PROXY` env vars (#730) (c085e460)
* **authentication:** authenticate merchant by API keys from API keys table (#712) (afd08d42)
* **api_keys:** use a KMS encrypted API key hashing key and remove key ID prefix from plaintext API keys (#639) (3a3b33ac)
## Tests
* **masking:** add suitable feature gates for basic tests (#745) (4859b6e4)
|
d302b286b8282488f6e0b3bb6259bb2c9930b3dd
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4883
|
Bug: [FEATURE] Add Moka Cache instead of Static Cache for 3DS Decision Manager and Surcharge Configs
### Feature Description
Add Moka Cache instead of Static Cache for 3DS Decision Manager and Surcharge Configs
### Possible Implementation
Add Moka Cache instead of Static Cache for 3DS Decision Manager and Surcharge Configs
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/euclid/src/backend/vir_interpreter.rs b/crates/euclid/src/backend/vir_interpreter.rs
index b7be62cf674..b8d14e228aa 100644
--- a/crates/euclid/src/backend/vir_interpreter.rs
+++ b/crates/euclid/src/backend/vir_interpreter.rs
@@ -1,5 +1,9 @@
pub mod types;
+use std::fmt::Debug;
+
+use serde::{Deserialize, Serialize};
+
use crate::{
backend::{self, inputs, EuclidBackend},
frontend::{
@@ -9,6 +13,7 @@ use crate::{
},
};
+#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VirInterpreterBackend<O> {
program: vir::ValuedProgram<O>,
}
diff --git a/crates/euclid/src/frontend/vir.rs b/crates/euclid/src/frontend/vir.rs
index 750ff4e61ff..6c8bc7ab2f1 100644
--- a/crates/euclid/src/frontend/vir.rs
+++ b/crates/euclid/src/frontend/vir.rs
@@ -1,13 +1,15 @@
//! Valued Intermediate Representation
+use serde::{Deserialize, Serialize};
+
use crate::types::{EuclidValue, Metadata};
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValuedComparisonLogic {
NegativeConjunction,
PositiveDisjunction,
}
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedComparison {
pub values: Vec<EuclidValue>,
pub logic: ValuedComparisonLogic,
@@ -16,20 +18,20 @@ pub struct ValuedComparison {
pub type ValuedIfCondition = Vec<ValuedComparison>;
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedIfStatement {
pub condition: ValuedIfCondition,
pub nested: Option<Vec<ValuedIfStatement>>,
}
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedRule<O> {
pub name: String,
pub connector_selection: O,
pub statements: Vec<ValuedIfStatement>,
}
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedProgram<O> {
pub default_selection: O,
pub rules: Vec<ValuedRule<O>>,
diff --git a/crates/euclid/src/types.rs b/crates/euclid/src/types.rs
index 904525d54b7..05d3fe6bb8e 100644
--- a/crates/euclid/src/types.rs
+++ b/crates/euclid/src/types.rs
@@ -1,7 +1,7 @@
pub mod transformers;
use euclid_macros::EnumNums;
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use strum::VariantNames;
use crate::{
@@ -143,7 +143,7 @@ impl EuclidKey {
enums::collect_variants!(EuclidKey);
-#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NumValueRefinement {
NotEqual,
@@ -178,18 +178,18 @@ impl From<NumValueRefinement> for ast::ComparisonType {
}
}
-#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize)]
+#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct StrValue {
pub value: String,
}
-#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize)]
+#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct MetadataValue {
pub key: String,
pub value: String,
}
-#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize)]
+#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct NumValue {
pub number: i64,
pub refinement: Option<NumValueRefinement>,
@@ -234,7 +234,7 @@ impl NumValue {
}
}
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EuclidValue {
PaymentMethod(enums::PaymentMethod),
CardBin(StrValue),
diff --git a/crates/router/src/core/conditional_config.rs b/crates/router/src/core/conditional_config.rs
index a8bc8a797dc..f740c6dfcc2 100644
--- a/crates/router/src/core/conditional_config.rs
+++ b/crates/router/src/core/conditional_config.rs
@@ -6,6 +6,7 @@ use common_utils::ext_traits::{Encode, StringExt, ValueExt};
use diesel_models::configs;
use error_stack::ResultExt;
use euclid::frontend::ast;
+use storage_impl::redis::cache;
use super::routing::helpers::{
get_payment_config_routing_id, update_merchant_active_algorithm_ref,
@@ -99,8 +100,9 @@ pub async fn upsert_conditional_config(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error serializing the config")?;
- algo_id.update_conditional_config_id(key);
- update_merchant_active_algorithm_ref(db, &key_store, algo_id)
+ algo_id.update_conditional_config_id(key.clone());
+ let config_key = cache::CacheKind::DecisionManager(key.into());
+ update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
@@ -134,8 +136,9 @@ pub async fn upsert_conditional_config(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching the config")?;
- algo_id.update_conditional_config_id(key);
- update_merchant_active_algorithm_ref(db, &key_store, algo_id)
+ algo_id.update_conditional_config_id(key.clone());
+ let config_key = cache::CacheKind::DecisionManager(key.into());
+ update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
@@ -164,7 +167,8 @@ pub async fn delete_conditional_config(
.attach_printable("Could not decode the conditional_config algorithm")?
.unwrap_or_default();
algo_id.config_algo_id = None;
- update_merchant_active_algorithm_ref(db, &key_store, algo_id)
+ let config_key = cache::CacheKind::DecisionManager(key.clone().into());
+ update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update deleted algorithm ref")?;
diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
index 14beb6be131..d708019fe14 100644
--- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
+++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
@@ -1,21 +1,21 @@
-use std::sync::Arc;
-
use api_models::{
payment_methods::SurchargeDetailsResponse,
payments, routing,
surcharge_decision_configs::{self, SurchargeDecisionConfigs, SurchargeDecisionManagerRecord},
};
-use common_utils::{ext_traits::StringExt, static_cache::StaticCache, types as common_utils_types};
+use common_utils::{ext_traits::StringExt, types as common_utils_types};
use error_stack::{self, ResultExt};
use euclid::{
backend,
backend::{inputs as dsl_inputs, EuclidBackend},
};
use router_env::{instrument, tracing};
+use serde::{Deserialize, Serialize};
+use storage_impl::redis::cache::{self, SURCHARGE_CACHE};
use crate::{
core::{
- errors::ConditionalConfigError as ConfigError,
+ errors::{self, ConditionalConfigError as ConfigError},
payments::{
conditional_configs::ConditionalConfigResult, routing::make_dsl_input_for_surcharge,
types, PaymentData,
@@ -29,9 +29,8 @@ use crate::{
SessionState,
};
-static CONF_CACHE: StaticCache<VirInterpreterBackendCacheWrapper> = StaticCache::new();
-
-struct VirInterpreterBackendCacheWrapper {
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct VirInterpreterBackendCacheWrapper {
cached_algorithm: backend::VirInterpreterBackend<SurchargeDecisionConfigs>,
merchant_surcharge_configs: surcharge_decision_configs::MerchantSurchargeConfigs,
}
@@ -53,7 +52,7 @@ impl TryFrom<SurchargeDecisionManagerRecord> for VirInterpreterBackendCacheWrapp
enum SurchargeSource {
/// Surcharge will be generated through the surcharge rules
- Generate(Arc<VirInterpreterBackendCacheWrapper>),
+ Generate(VirInterpreterBackendCacheWrapper),
/// Surcharge is predefined by the merchant through payment create request
Predetermined(payments::RequestSurchargeDetails),
}
@@ -116,19 +115,13 @@ pub async fn perform_surcharge_decision_management_for_payment_method_list(
surcharge_decision_configs::MerchantSurchargeConfigs::default(),
),
(None, Some(algorithm_id)) => {
- let key = ensure_algorithm_cached(
+ let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
- algorithm_ref.timestamp,
algorithm_id.as_str(),
)
.await?;
- let cached_algo = CONF_CACHE
- .retrieve(&key)
- .change_context(ConfigError::CacheMiss)
- .attach_printable(
- "Unable to retrieve cached routing algorithm even after refresh",
- )?;
+
let merchant_surcharge_config = cached_algo.merchant_surcharge_configs.clone();
(
SurchargeSource::Generate(cached_algo),
@@ -233,19 +226,13 @@ where
SurchargeSource::Predetermined(request_surcharge_details)
}
(None, Some(algorithm_id)) => {
- let key = ensure_algorithm_cached(
+ let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_data.payment_attempt.merchant_id,
- algorithm_ref.timestamp,
algorithm_id.as_str(),
)
.await?;
- let cached_algo = CONF_CACHE
- .retrieve(&key)
- .change_context(ConfigError::CacheMiss)
- .attach_printable(
- "Unable to retrieve cached routing algorithm even after refresh",
- )?;
+
SurchargeSource::Generate(cached_algo)
}
(None, None) => return Ok(surcharge_metadata),
@@ -291,19 +278,13 @@ pub async fn perform_surcharge_decision_management_for_saved_cards(
SurchargeSource::Predetermined(request_surcharge_details)
}
(None, Some(algorithm_id)) => {
- let key = ensure_algorithm_cached(
+ let cached_algo = ensure_algorithm_cached(
&*state.store,
&payment_attempt.merchant_id,
- algorithm_ref.timestamp,
algorithm_id.as_str(),
)
.await?;
- let cached_algo = CONF_CACHE
- .retrieve(&key)
- .change_context(ConfigError::CacheMiss)
- .attach_printable(
- "Unable to retrieve cached routing algorithm even after refresh",
- )?;
+
SurchargeSource::Generate(cached_algo)
}
(None, None) => return Ok(surcharge_metadata),
@@ -388,48 +369,31 @@ fn get_surcharge_details_from_surcharge_output(
pub async fn ensure_algorithm_cached(
store: &dyn StorageInterface,
merchant_id: &str,
- timestamp: i64,
algorithm_id: &str,
-) -> ConditionalConfigResult<String> {
+) -> ConditionalConfigResult<VirInterpreterBackendCacheWrapper> {
let key = format!("surcharge_dsl_{merchant_id}");
- let present = CONF_CACHE
- .present(&key)
- .change_context(ConfigError::DslCachePoisoned)
- .attach_printable("Error checking presence of DSL")?;
- let expired = CONF_CACHE
- .expired(&key, timestamp)
- .change_context(ConfigError::DslCachePoisoned)
- .attach_printable("Error checking presence of DSL")?;
- if !present || expired {
- refresh_surcharge_algorithm_cache(store, key.clone(), algorithm_id, timestamp).await?
- }
- Ok(key)
-}
-
-#[instrument(skip_all)]
-pub async fn refresh_surcharge_algorithm_cache(
- store: &dyn StorageInterface,
- key: String,
- algorithm_id: &str,
- timestamp: i64,
-) -> ConditionalConfigResult<()> {
- let config = store
- .find_config_by_key(algorithm_id)
- .await
- .change_context(ConfigError::DslMissingInDb)
- .attach_printable("Error parsing DSL from config")?;
- let record: SurchargeDecisionManagerRecord = config
- .config
- .parse_struct("Program")
- .change_context(ConfigError::DslParsingError)
- .attach_printable("Error parsing routing algorithm from configs")?;
- let value_to_cache = VirInterpreterBackendCacheWrapper::try_from(record)?;
- CONF_CACHE
- .save(key, value_to_cache, timestamp)
- .change_context(ConfigError::DslCachePoisoned)
- .attach_printable("Error saving DSL to cache")?;
- Ok(())
+ let value_to_cache = || async {
+ let config: diesel_models::Config = store.find_config_by_key(algorithm_id).await?;
+ let record: SurchargeDecisionManagerRecord = config
+ .config
+ .parse_struct("Program")
+ .change_context(errors::StorageError::DeserializationFailed)
+ .attach_printable("Error parsing routing algorithm from configs")?;
+ VirInterpreterBackendCacheWrapper::try_from(record)
+ .change_context(errors::StorageError::ValueNotFound("Program".to_string()))
+ .attach_printable("Error initializing DSL interpreter backend")
+ };
+ let interpreter = cache::get_or_populate_in_memory(
+ store.get_cache_store().as_ref(),
+ &key,
+ value_to_cache,
+ &SURCHARGE_CACHE,
+ )
+ .await
+ .change_context(ConfigError::CacheMiss)
+ .attach_printable("Unable to retrieve cached routing algorithm even after refresh")?;
+ Ok(interpreter)
}
pub fn execute_dsl_and_get_conditional_config(
diff --git a/crates/router/src/core/payments/conditional_configs.rs b/crates/router/src/core/payments/conditional_configs.rs
index c73fa3659b7..7ec9a749152 100644
--- a/crates/router/src/core/payments/conditional_configs.rs
+++ b/crates/router/src/core/payments/conditional_configs.rs
@@ -4,19 +4,17 @@ use api_models::{
conditional_configs::{ConditionalConfigs, DecisionManagerRecord},
routing,
};
-use common_utils::{ext_traits::StringExt, static_cache::StaticCache};
+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;
use crate::{
core::{errors, errors::ConditionalConfigError as ConfigError, payments},
routes,
};
-
-static CONF_CACHE: StaticCache<backend::VirInterpreterBackend<ConditionalConfigs>> =
- StaticCache::new();
pub type ConditionalConfigResult<O> = errors::CustomResult<O, ConfigError>;
#[instrument(skip_all)]
@@ -31,76 +29,40 @@ pub async fn perform_decision_management<F: Clone>(
} else {
return Ok(ConditionalConfigs::default());
};
+ let db = &*state.store;
+
+ let key = format!("dsl_{merchant_id}");
+
+ 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 key = ensure_algorithm_cached(
- state,
- merchant_id,
- algorithm_ref.timestamp,
- algorithm_id.as_str(),
+ let interpreter = cache::get_or_populate_in_memory(
+ db.get_cache_store().as_ref(),
+ &key,
+ find_key_from_db,
+ &DECISION_MANAGER_CACHE,
)
- .await?;
- let cached_algo = CONF_CACHE
- .retrieve(&key)
- .change_context(ConfigError::CacheMiss)
- .attach_printable("Unable to retrieve cached routing algorithm even after refresh")?;
+ .await
+ .change_context(ConfigError::DslCachePoisoned)?;
+
let backend_input =
make_dsl_input(payment_data).change_context(ConfigError::InputConstructionError)?;
- let interpreter = cached_algo.as_ref();
- execute_dsl_and_get_conditional_config(backend_input, interpreter).await
-}
-#[instrument(skip_all)]
-pub async fn ensure_algorithm_cached(
- state: &routes::SessionState,
- merchant_id: &str,
- timestamp: i64,
- algorithm_id: &str,
-) -> ConditionalConfigResult<String> {
- let key = format!("dsl_{merchant_id}");
- let present = CONF_CACHE
- .present(&key)
- .change_context(ConfigError::DslCachePoisoned)
- .attach_printable("Error checking presece of DSL")?;
- let expired = CONF_CACHE
- .expired(&key, timestamp)
- .change_context(ConfigError::DslCachePoisoned)
- .attach_printable("Error checking presence of DSL")?;
- if !present || expired {
- refresh_routing_cache(state, key.clone(), algorithm_id, timestamp).await?;
- };
- Ok(key)
-}
-
-#[instrument(skip_all)]
-pub async fn refresh_routing_cache(
- state: &routes::SessionState,
- key: String,
- algorithm_id: &str,
- timestamp: i64,
-) -> ConditionalConfigResult<()> {
- let config = state
- .store
- .find_config_by_key(algorithm_id)
- .await
- .change_context(ConfigError::DslMissingInDb)
- .attach_printable("Error parsing DSL from config")?;
- let rec: DecisionManagerRecord = config
- .config
- .parse_struct("Program")
- .change_context(ConfigError::DslParsingError)
- .attach_printable("Error parsing routing algorithm from configs")?;
- let interpreter: backend::VirInterpreterBackend<ConditionalConfigs> =
- backend::VirInterpreterBackend::with_program(rec.program)
- .change_context(ConfigError::DslBackendInitError)
- .attach_printable("Error initializing DSL interpreter backend")?;
- CONF_CACHE
- .save(key, interpreter, timestamp)
- .change_context(ConfigError::DslCachePoisoned)
- .attach_printable("Error saving DSL to cache")?;
- Ok(())
+ execute_dsl_and_get_conditional_config(backend_input, &interpreter)
}
-pub async fn execute_dsl_and_get_conditional_config(
+pub fn execute_dsl_and_get_conditional_config(
backend_input: dsl_inputs::BackendInput,
interpreter: &backend::VirInterpreterBackend<ConditionalConfigs>,
) -> ConditionalConfigResult<ConditionalConfigs> {
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 145800ebc6a..15eda58c913 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -558,9 +558,9 @@ pub async fn get_merchant_cgraph<'a>(
#[cfg(not(feature = "business_profile_routing"))]
let key = match transaction_type {
- api_enums::TransactionType::Payment => format!("kgraph_{}", merchant_id),
+ api_enums::TransactionType::Payment => format!("cgraph_{}", merchant_id),
#[cfg(feature = "payouts")]
- api_enums::TransactionType::Payout => format!("kgraph_po_{}", merchant_id),
+ api_enums::TransactionType::Payout => format!("cgraph_po_{}", merchant_id),
};
let cached_cgraph = CGRAPH_CACHE
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index a64dadaa35d..5314de4d2f8 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -15,6 +15,8 @@ use diesel_models::configs;
use diesel_models::routing_algorithm::RoutingAlgorithm;
use error_stack::ResultExt;
use rustc_hash::FxHashSet;
+#[cfg(not(feature = "business_profile_routing"))]
+use storage_impl::redis::cache;
use super::payments;
#[cfg(feature = "payouts")]
@@ -232,7 +234,11 @@ pub async fn create_routing_config(
if records_are_empty {
merchant_dictionary.active_id = Some(algorithm_id.clone());
algorithm_ref.update_algorithm_id(algorithm_id);
- helpers::update_merchant_active_algorithm_ref(db, &key_store, algorithm_ref).await?;
+ let key =
+ cache::CacheKind::Routing(format!("dsl_{}", &merchant_account.merchant_id).into());
+
+ helpers::update_merchant_active_algorithm_ref(db, &key_store, key, algorithm_ref)
+ .await?;
}
helpers::update_merchant_routing_dictionary(
@@ -363,7 +369,9 @@ pub async fn link_routing_config(
merchant_dictionary,
)
.await?;
- helpers::update_merchant_active_algorithm_ref(db, &key_store, routing_ref).await?;
+ let key =
+ cache::CacheKind::Routing(format!("dsl_{}", &merchant_account.merchant_id).into());
+ helpers::update_merchant_active_algorithm_ref(db, &key_store, key, routing_ref).await?;
metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 2e1032e8e4c..c89eb2b8579 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -188,6 +188,7 @@ pub async fn update_routing_algorithm(
pub async fn update_merchant_active_algorithm_ref(
db: &dyn StorageInterface,
key_store: &domain::MerchantKeyStore,
+ config_key: cache::CacheKind<'_>,
algorithm_id: routing_types::RoutingAlgorithmRef,
) -> RouterResult<()> {
let ref_value = algorithm_id
@@ -226,6 +227,11 @@ pub async fn update_merchant_active_algorithm_ref(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in merchant account")?;
+ cache::publish_into_redact_channel(db.get_cache_store().as_ref(), [config_key])
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to invalidate the config cache")?;
+
Ok(())
}
diff --git a/crates/router/src/core/surcharge_decision_config.rs b/crates/router/src/core/surcharge_decision_config.rs
index 7f451e6008f..b35d7c5ad28 100644
--- a/crates/router/src/core/surcharge_decision_config.rs
+++ b/crates/router/src/core/surcharge_decision_config.rs
@@ -9,6 +9,7 @@ use common_utils::ext_traits::{Encode, StringExt, ValueExt};
use diesel_models::configs;
use error_stack::ResultExt;
use euclid::frontend::ast;
+use storage_impl::redis::cache;
use super::routing::helpers::{
get_payment_method_surcharge_routing_id, update_merchant_active_algorithm_ref,
@@ -88,8 +89,9 @@ pub async fn upsert_surcharge_decision_config(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error serializing the config")?;
- algo_id.update_surcharge_config_id(key);
- update_merchant_active_algorithm_ref(db, &key_store, algo_id)
+ algo_id.update_surcharge_config_id(key.clone());
+ let config_key = cache::CacheKind::Surcharge(key.into());
+ update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
@@ -124,8 +126,9 @@ pub async fn upsert_surcharge_decision_config(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error fetching the config")?;
- algo_id.update_surcharge_config_id(key);
- update_merchant_active_algorithm_ref(db, &key_store, algo_id)
+ algo_id.update_surcharge_config_id(key.clone());
+ let config_key = cache::CacheKind::Surcharge(key.clone().into());
+ update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref")?;
@@ -154,7 +157,8 @@ pub async fn delete_surcharge_decision_config(
.attach_printable("Could not decode the surcharge conditional_config algorithm")?
.unwrap_or_default();
algo_id.surcharge_config_algo_id = None;
- update_merchant_active_algorithm_ref(db, &key_store, algo_id)
+ let config_key = cache::CacheKind::Surcharge(key.clone().into());
+ update_merchant_active_algorithm_ref(db, &key_store, config_key, algo_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update deleted algorithm ref")?;
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index 9b82ef414ce..39d63080a4b 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -514,10 +514,10 @@ async fn publish_and_redact_merchant_account_cache(
.map(|publishable_key| CacheKind::Accounts(publishable_key.into()));
#[cfg(feature = "business_profile_routing")]
- let kgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| {
+ let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| {
CacheKind::CGraph(
format!(
- "kgraph_{}_{}",
+ "cgraph_{}_{}",
merchant_account.merchant_id.clone(),
profile_id,
)
@@ -526,8 +526,8 @@ async fn publish_and_redact_merchant_account_cache(
});
#[cfg(not(feature = "business_profile_routing"))]
- let kgraph_key = Some(CacheKind::CGraph(
- format!("kgraph_{}", merchant_account.merchant_id.clone()).into(),
+ let cgraph_key = Some(CacheKind::CGraph(
+ format!("cgraph_{}", merchant_account.merchant_id.clone()).into(),
));
let mut cache_keys = vec![CacheKind::Accounts(
@@ -535,7 +535,7 @@ async fn publish_and_redact_merchant_account_cache(
)];
cache_keys.extend(publishable_key.into_iter());
- cache_keys.extend(kgraph_key.into_iter());
+ cache_keys.extend(cgraph_key.into_iter());
cache::publish_into_redact_channel(store.get_cache_store().as_ref(), cache_keys).await?;
Ok(())
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 9d1df7b67eb..e4efab0da33 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -28,6 +28,12 @@ const ACCOUNTS_CACHE_PREFIX: &str = "accounts";
/// Prefix for routing cache key
const ROUTING_CACHE_PREFIX: &str = "routing";
+/// Prefix for three ds decision manager cache key
+const DECISION_MANAGER_CACHE_PREFIX: &str = "decision_manager";
+
+/// Prefix for surcharge cache key
+const SURCHARGE_CACHE_PREFIX: &str = "surcharge";
+
/// Prefix for cgraph cache key
const CGRAPH_CACHE_PREFIX: &str = "cgraph";
@@ -57,6 +63,14 @@ pub static ACCOUNTS_CACHE: Lazy<Cache> =
pub static ROUTING_CACHE: Lazy<Cache> =
Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
+/// 3DS Decision Manager Cache
+pub static DECISION_MANAGER_CACHE: Lazy<Cache> =
+ Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
+
+/// Surcharge Cache
+pub static SURCHARGE_CACHE: Lazy<Cache> =
+ Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
+
/// CGraph Cache
pub static CGRAPH_CACHE: Lazy<Cache> =
Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
@@ -74,6 +88,8 @@ pub enum CacheKind<'a> {
Config(Cow<'a, str>),
Accounts(Cow<'a, str>),
Routing(Cow<'a, str>),
+ DecisionManager(Cow<'a, str>),
+ Surcharge(Cow<'a, str>),
CGraph(Cow<'a, str>),
PmFiltersCGraph(Cow<'a, str>),
All(Cow<'a, str>),
@@ -85,6 +101,8 @@ impl<'a> From<CacheKind<'a>> for RedisValue {
CacheKind::Config(s) => format!("{CONFIG_CACHE_PREFIX},{s}"),
CacheKind::Accounts(s) => format!("{ACCOUNTS_CACHE_PREFIX},{s}"),
CacheKind::Routing(s) => format!("{ROUTING_CACHE_PREFIX},{s}"),
+ CacheKind::DecisionManager(s) => format!("{DECISION_MANAGER_CACHE_PREFIX},{s}"),
+ CacheKind::Surcharge(s) => format!("{SURCHARGE_CACHE_PREFIX},{s}"),
CacheKind::CGraph(s) => format!("{CGRAPH_CACHE_PREFIX},{s}"),
CacheKind::PmFiltersCGraph(s) => format!("{PM_FILTERS_CGRAPH_CACHE_PREFIX},{s}"),
CacheKind::All(s) => format!("{ALL_CACHE_PREFIX},{s}"),
@@ -105,10 +123,15 @@ impl<'a> TryFrom<RedisValue> for CacheKind<'a> {
ACCOUNTS_CACHE_PREFIX => Ok(Self::Accounts(Cow::Owned(split.1.to_string()))),
CONFIG_CACHE_PREFIX => Ok(Self::Config(Cow::Owned(split.1.to_string()))),
ROUTING_CACHE_PREFIX => Ok(Self::Routing(Cow::Owned(split.1.to_string()))),
+ DECISION_MANAGER_CACHE_PREFIX => {
+ Ok(Self::DecisionManager(Cow::Owned(split.1.to_string())))
+ }
+ SURCHARGE_CACHE_PREFIX => Ok(Self::Surcharge(Cow::Owned(split.1.to_string()))),
CGRAPH_CACHE_PREFIX => Ok(Self::CGraph(Cow::Owned(split.1.to_string()))),
PM_FILTERS_CGRAPH_CACHE_PREFIX => {
Ok(Self::PmFiltersCGraph(Cow::Owned(split.1.to_string())))
}
+
ALL_CACHE_PREFIX => Ok(Self::All(Cow::Owned(split.1.to_string()))),
_ => Err(validation_err.into()),
}
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index e83546c0f8d..7c4bd93681f 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -3,8 +3,8 @@ use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue};
use router_env::{logger, tracing::Instrument};
use crate::redis::cache::{
- CacheKey, CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, PM_FILTERS_CGRAPH_CACHE,
- ROUTING_CACHE,
+ CacheKey, CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, DECISION_MANAGER_CACHE,
+ PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE, SURCHARGE_CACHE,
};
#[async_trait::async_trait]
@@ -119,6 +119,24 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
.await;
key
}
+ CacheKind::DecisionManager(key) => {
+ DECISION_MANAGER_CACHE
+ .remove(CacheKey {
+ key: key.to_string(),
+ prefix: self.key_prefix.clone(),
+ })
+ .await;
+ key
+ }
+ CacheKind::Surcharge(key) => {
+ SURCHARGE_CACHE
+ .remove(CacheKey {
+ key: key.to_string(),
+ prefix: self.key_prefix.clone(),
+ })
+ .await;
+ key
+ }
CacheKind::All(key) => {
CONFIG_CACHE
.remove(CacheKey {
@@ -150,6 +168,19 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
prefix: self.key_prefix.clone(),
})
.await;
+ DECISION_MANAGER_CACHE
+ .remove(CacheKey {
+ key: key.to_string(),
+ prefix: self.key_prefix.clone(),
+ })
+ .await;
+ SURCHARGE_CACHE
+ .remove(CacheKey {
+ key: key.to_string(),
+ prefix: self.key_prefix.clone(),
+ })
+ .await;
+
key
}
};
|
2024-05-29T11:36:14Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
refactor conditional_configs to use Moka Cache instead of Static Cache
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
Cannot be tested
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
05105321caceb14f99f0ec0f8ccefd9db9b02bb6
|
Cannot be tested
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4869
|
Bug: [BUG] Paypal payment experience
### Bug Description
Paypal payment experience is getting duplicated
<img width="1721" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/ec53d1fd-596c-4be3-90c3-3c0f0c06dc50">
### Expected Behavior
Paypal payment experience shouldn't get duplicated
### Actual Behavior
Paypal payment experience shouldn't get duplicated
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index 87d1e3e810b..976068c98b6 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -71,24 +71,27 @@ impl DashboardRequestPayload {
api_models::enums::PaymentExperience::RedirectToUrl,
api_models::enums::PaymentExperience::InvokeSdkClient,
];
-
+ let default_provider = Provider {
+ payment_method_type: Paypal,
+ accepted_currencies: None,
+ accepted_countries: None,
+ };
+ let provider = providers.first().unwrap_or(&default_provider);
let mut payment_method_types = Vec::new();
for experience in payment_experiences {
- for provider in &providers {
- let data = payment_methods::RequestPaymentMethodTypes {
- payment_method_type: provider.payment_method_type,
- card_networks: None,
- minimum_amount: Some(0),
- maximum_amount: Some(68607706),
- recurring_enabled: true,
- installment_payment_enabled: false,
- accepted_currencies: provider.accepted_currencies.clone(),
- accepted_countries: provider.accepted_countries.clone(),
- payment_experience: Some(experience),
- };
- payment_method_types.push(data);
- }
+ let data = payment_methods::RequestPaymentMethodTypes {
+ payment_method_type: provider.payment_method_type,
+ card_networks: None,
+ minimum_amount: Some(0),
+ maximum_amount: Some(68607706),
+ recurring_enabled: true,
+ installment_payment_enabled: false,
+ accepted_currencies: provider.accepted_currencies.clone(),
+ accepted_countries: provider.accepted_countries.clone(),
+ payment_experience: Some(experience),
+ };
+ payment_method_types.push(data);
}
payment_method_types
|
2024-06-04T12:22:52Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
<img width="1382" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/28dcf3da-317f-4e40-b91f-0197d0db3410">
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
1d36798399c118f7cb7af93935123634e1afd6a0
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4860
|
Bug: [BUG] Avoid overrides in auto generated OpenAPI specification
### Bug Description
If there are types defined with duplicate names, the entry which is specified at the end overrides any previous entries with the same name. This is identified for payments and payouts - Card struct. This is being overriden for payments as it's specified earlier in the list.
This is inconsistent and leads to incorrect generation of the OpenAPI spec.
### Expected Behavior
There should not be any duplicate types specified in OpenAPI spec.
### Actual Behavior
There are duplicate types (Card) specified in OpenAPI spec.
### Steps To Reproduce
Check `payment_method_data.card` https://api-reference.hyperswitch.io/api-reference/payments/payments--create
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 69c50da79c2..2df40bd6757 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -153,19 +153,19 @@ pub struct PayoutCreateRequest {
#[derive(Debug, Clone, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum PayoutMethodData {
- Card(Card),
+ Card(CardPayout),
Bank(Bank),
Wallet(Wallet),
}
impl Default for PayoutMethodData {
fn default() -> Self {
- Self::Card(Card::default())
+ Self::Card(CardPayout::default())
}
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
-pub struct Card {
+pub struct CardPayout {
/// The card number
#[schema(value_type = String, example = "4242424242424242")]
pub card_number: CardNumber,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 237cddcf94e..c15704afa3b 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -440,7 +440,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GiftCardData,
api_models::payments::GiftCardDetails,
api_models::payments::Address,
- api_models::payouts::Card,
+ api_models::payouts::CardPayout,
api_models::payouts::Wallet,
api_models::payouts::Paypal,
api_models::payouts::Venmo,
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 6737bbf3af0..873e6f18d23 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -1202,7 +1202,7 @@ pub trait CardData {
}
#[cfg(feature = "payouts")]
-impl CardData for payouts::Card {
+impl CardData for payouts::CardPayout {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.expiry_year.clone();
let year = binding.peek();
diff --git a/crates/router/src/types/api/payouts.rs b/crates/router/src/types/api/payouts.rs
index d4417c5f1cc..dfe7e949aa1 100644
--- a/crates/router/src/types/api/payouts.rs
+++ b/crates/router/src/types/api/payouts.rs
@@ -1,5 +1,5 @@
pub use api_models::payouts::{
- AchBankTransfer, BacsBankTransfer, Bank as BankPayout, Card as CardPayout, PayoutActionRequest,
+ AchBankTransfer, BacsBankTransfer, Bank as BankPayout, CardPayout, PayoutActionRequest,
PayoutCreateRequest, PayoutCreateResponse, PayoutListConstraints, PayoutListFilterConstraints,
PayoutListFilters, PayoutListResponse, PayoutMethodData, PayoutRequest, PayoutRetrieveBody,
PayoutRetrieveRequest, PixBankTransfer, SepaBankTransfer, Wallet as WalletPayout,
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index f42481798a4..195fb7ed00e 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -7054,9 +7054,10 @@
"type": "object",
"required": [
"card_number",
- "expiry_month",
- "expiry_year",
- "card_holder_name"
+ "card_exp_month",
+ "card_exp_year",
+ "card_holder_name",
+ "card_cvc"
],
"properties": {
"card_number": {
@@ -7064,18 +7065,60 @@
"description": "The card number",
"example": "4242424242424242"
},
- "expiry_month": {
+ "card_exp_month": {
"type": "string",
- "description": "The card's expiry month"
+ "description": "The card's expiry month",
+ "example": "24"
},
- "expiry_year": {
+ "card_exp_year": {
"type": "string",
- "description": "The card's expiry year"
+ "description": "The card's expiry year",
+ "example": "24"
},
"card_holder_name": {
"type": "string",
"description": "The card holder's name",
- "example": "John Doe"
+ "example": "John Test"
+ },
+ "card_cvc": {
+ "type": "string",
+ "description": "The CVC number for the card",
+ "example": "242"
+ },
+ "card_issuer": {
+ "type": "string",
+ "description": "The name of the issuer of card",
+ "example": "chase",
+ "nullable": true
+ },
+ "card_network": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CardNetwork"
+ }
+ ],
+ "nullable": true
+ },
+ "card_type": {
+ "type": "string",
+ "example": "CREDIT",
+ "nullable": true
+ },
+ "card_issuing_country": {
+ "type": "string",
+ "example": "INDIA",
+ "nullable": true
+ },
+ "bank_code": {
+ "type": "string",
+ "example": "JP_AMEX",
+ "nullable": true
+ },
+ "nick_name": {
+ "type": "string",
+ "description": "The card holder's nick name",
+ "example": "John Test",
+ "nullable": true
}
}
},
@@ -7256,6 +7299,35 @@
"Maestro"
]
},
+ "CardPayout": {
+ "type": "object",
+ "required": [
+ "card_number",
+ "expiry_month",
+ "expiry_year",
+ "card_holder_name"
+ ],
+ "properties": {
+ "card_number": {
+ "type": "string",
+ "description": "The card number",
+ "example": "4242424242424242"
+ },
+ "expiry_month": {
+ "type": "string",
+ "description": "The card's expiry month"
+ },
+ "expiry_year": {
+ "type": "string",
+ "description": "The card's expiry year"
+ },
+ "card_holder_name": {
+ "type": "string",
+ "description": "The card holder's name",
+ "example": "John Doe"
+ }
+ }
+ },
"CardRedirectData": {
"oneOf": [
{
@@ -16752,7 +16824,7 @@
],
"properties": {
"card": {
- "$ref": "#/components/schemas/Card"
+ "$ref": "#/components/schemas/CardPayout"
}
}
},
|
2024-06-04T06:12:38Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Fixes https://github.com/juspay/hyperswitch/issues/4860
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
e9be4e22411d218009e6cd6c1a5ef9dc8fc430b7
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4889
|
Bug: feat(connector): [DATATRANS] add Connector Template Code
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 81516ee8b6b..7372f93044c 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -186,6 +186,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
+datatrans.base_url = "https://api.sandbox.datatrans.com/"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
@@ -276,6 +277,7 @@ cards = [
"braintree",
"checkout",
"cybersource",
+ "datatrans",
"globalpay",
"globepay",
"gocardless",
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 5abbc870fd0..f5f69568da6 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -40,6 +40,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
+datatrans.base_url = "https://api.sandbox.datatrans.com/"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index b4e02172dfc..bbaf22067b5 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -44,6 +44,7 @@ checkout.base_url = "https://api.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business.cryptopay.me/"
cybersource.base_url = "https://api.cybersource.com/"
+datatrans.base_url = "https://api.datatrans.com/"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index a8ddbc55f5f..de274ad9411 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -44,6 +44,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
+datatrans.base_url = "https://api.sandbox.datatrans.com/"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
diff --git a/config/development.toml b/config/development.toml
index 9a40a99cfce..fcdc2dee136 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -109,6 +109,7 @@ cards = [
"coinbase",
"cryptopay",
"cybersource",
+ "datatrans",
"dlocal",
"dummyconnector",
"ebanx",
@@ -188,6 +189,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
+datatrans.base_url = "https://api.sandbox.datatrans.com"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 2cd93eade01..e5075d4ea45 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -125,6 +125,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
+datatrans.base_url = "https://api.sandbox.datatrans.com/"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
@@ -202,6 +203,7 @@ cards = [
"coinbase",
"cryptopay",
"cybersource",
+ "datatrans",
"dlocal",
"dummyconnector",
"ebanx",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 1b976d68a19..514e44337c1 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -89,6 +89,7 @@ pub enum Connector {
Coinbase,
Cryptopay,
Cybersource,
+ // Datatrans,
Dlocal,
Ebanx,
Fiserv,
@@ -251,6 +252,7 @@ impl Connector {
| Self::Plaid
| Self::Riskified
| Self::Threedsecureio
+ // | Self::Datatrans
| Self::Netcetera
| Self::Noon
| Self::Stripe => false,
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 5d6b9c14895..f3a3b02155d 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -128,6 +128,7 @@ pub enum RoutableConnectors {
Coinbase,
Cryptopay,
Cybersource,
+ // Datatrans,
Dlocal,
Ebanx,
Fiserv,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index e99e216463a..ac8689d21b4 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -568,6 +568,7 @@ pub struct Connectors {
pub coinbase: ConnectorParams,
pub cryptopay: ConnectorParams,
pub cybersource: ConnectorParams,
+ pub datatrans: ConnectorParams,
pub dlocal: ConnectorParams,
#[cfg(feature = "dummy_connector")]
pub dummyconnector: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index a423decdb9b..4b89b12734e 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -15,6 +15,7 @@ pub mod checkout;
pub mod coinbase;
pub mod cryptopay;
pub mod cybersource;
+pub mod datatrans;
pub mod dlocal;
#[cfg(feature = "dummy_connector")]
pub mod dummyconnector;
@@ -71,12 +72,12 @@ pub use self::{
authorizedotnet::Authorizedotnet, bambora::Bambora, bankofamerica::Bankofamerica,
billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap, boku::Boku, braintree::Braintree,
cashtocode::Cashtocode, checkout::Checkout, coinbase::Coinbase, cryptopay::Cryptopay,
- cybersource::Cybersource, dlocal::Dlocal, ebanx::Ebanx, fiserv::Fiserv, forte::Forte,
- globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, gpayments::Gpayments,
- helcim::Helcim, iatapay::Iatapay, klarna::Klarna, mifinity::Mifinity, mollie::Mollie,
- multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi, noon::Noon,
- nuvei::Nuvei, opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, payone::Payone,
- paypal::Paypal, payu::Payu, placetopay::Placetopay, powertranz::Powertranz,
+ cybersource::Cybersource, datatrans::Datatrans, dlocal::Dlocal, ebanx::Ebanx, fiserv::Fiserv,
+ forte::Forte, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless,
+ gpayments::Gpayments, helcim::Helcim, iatapay::Iatapay, klarna::Klarna, mifinity::Mifinity,
+ mollie::Mollie, multisafepay::Multisafepay, netcetera::Netcetera, nexinets::Nexinets, nmi::Nmi,
+ noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme,
+ payone::Payone, paypal::Paypal, payu::Payu, placetopay::Placetopay, powertranz::Powertranz,
prophetpay::Prophetpay, rapyd::Rapyd, riskified::Riskified, shift4::Shift4, signifyd::Signifyd,
square::Square, stax::Stax, stripe::Stripe, threedsecureio::Threedsecureio, trustpay::Trustpay,
tsys::Tsys, volt::Volt, wise::Wise, worldline::Worldline, worldpay::Worldpay, zen::Zen,
diff --git a/crates/router/src/connector/datatrans.rs b/crates/router/src/connector/datatrans.rs
new file mode 100644
index 00000000000..90c6b38d2fb
--- /dev/null
+++ b/crates/router/src/connector/datatrans.rs
@@ -0,0 +1,563 @@
+pub mod transformers;
+
+use std::fmt::Debug;
+
+use error_stack::{report, ResultExt};
+use masking::ExposeInterface;
+use transformers as datatrans;
+
+use crate::{
+ configs::settings,
+ core::errors::{self, CustomResult},
+ events::connector_api_logs::ConnectorEvent,
+ headers,
+ services::{
+ self,
+ request::{self, Mask},
+ ConnectorIntegration, ConnectorValidation,
+ },
+ types::{
+ self,
+ api::{self, ConnectorCommon, ConnectorCommonExt},
+ ErrorResponse, RequestContent, Response,
+ },
+ utils::BytesExt,
+};
+
+#[derive(Debug, Clone)]
+pub struct Datatrans;
+
+impl api::Payment for Datatrans {}
+impl api::PaymentSession for Datatrans {}
+impl api::ConnectorAccessToken for Datatrans {}
+impl api::MandateSetup for Datatrans {}
+impl api::PaymentAuthorize for Datatrans {}
+impl api::PaymentSync for Datatrans {}
+impl api::PaymentCapture for Datatrans {}
+impl api::PaymentVoid for Datatrans {}
+impl api::Refund for Datatrans {}
+impl api::RefundExecute for Datatrans {}
+impl api::RefundSync for Datatrans {}
+impl api::PaymentToken for Datatrans {}
+
+impl
+ ConnectorIntegration<
+ api::PaymentMethodToken,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ > for Datatrans
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Datatrans
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &types::RouterData<Flow, Request, Response>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string().into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Datatrans {
+ fn id(&self) -> &'static str {
+ "datatrans"
+ }
+
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.datatrans.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ let auth = datatrans::DatatransAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: datatrans::DatatransErrorResponse = res
+ .response
+ .parse_struct("DatatransErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+}
+
+impl ConnectorValidation for Datatrans {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Datatrans
+{
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Datatrans
+{
+}
+
+impl
+ ConnectorIntegration<
+ api::SetupMandate,
+ types::SetupMandateRequestData,
+ types::PaymentsResponseData,
+ > for Datatrans
+{
+}
+
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Datatrans
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_router_data = datatrans::DatatransRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let connector_req = datatrans::DatatransPaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: datatrans::DatatransPaymentsResponse = res
+ .response
+ .parse_struct("Datatrans PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Datatrans
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: datatrans::DatatransPaymentsResponse = res
+ .response
+ .parse_struct("datatrans PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Datatrans
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: datatrans::DatatransPaymentsResponse = res
+ .response
+ .parse_struct("Datatrans PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Datatrans
+{
+}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
+ for Datatrans
+{
+ fn get_headers(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundsRouterData<api::Execute>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_router_data = datatrans::DatatransRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.refund_amount,
+ req,
+ ))?;
+ let connector_req = datatrans::DatatransRefundRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::RefundExecuteType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ let response: datatrans::RefundResponse = res
+ .response
+ .parse_struct("datatrans RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
+ for Datatrans
+{
+ fn get_headers(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ let response: datatrans::RefundResponse = res
+ .response
+ .parse_struct("datatrans RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Datatrans {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
+ Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ }
+}
diff --git a/crates/router/src/connector/datatrans/transformers.rs b/crates/router/src/connector/datatrans/transformers.rs
new file mode 100644
index 00000000000..b079708e233
--- /dev/null
+++ b/crates/router/src/connector/datatrans/transformers.rs
@@ -0,0 +1,235 @@
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ connector::utils::PaymentsAuthorizeRequestData,
+ core::errors,
+ types::{self, api, domain, storage::enums},
+};
+
+//TODO: Fill the struct with respective fields
+pub struct DatatransRouterData<T> {
+ pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub router_data: T,
+}
+
+impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for DatatransRouterData<T> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (_currency_unit, _currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
+ ) -> Result<Self, Self::Error> {
+ //Todo : use utils to convert the amount to the type of amount that a connector accepts
+ Ok(Self {
+ amount,
+ router_data: item,
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct DatatransPaymentsRequest {
+ amount: i64,
+ card: DatatransCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct DatatransCard {
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&DatatransRouterData<&types::PaymentsAuthorizeRouterData>>
+ for DatatransPaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &DatatransRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ domain::PaymentMethodData::Card(req_card) => {
+ let card = DatatransCard {
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.router_data.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.amount.to_owned(),
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct DatatransAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for DatatransAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: api_key.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum DatatransPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<DatatransPaymentStatus> for enums::AttemptStatus {
+ fn from(item: DatatransPaymentStatus) -> Self {
+ match item {
+ DatatransPaymentStatus::Succeeded => Self::Charged,
+ DatatransPaymentStatus::Failed => Self::Failure,
+ DatatransPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct DatatransPaymentsResponse {
+ status: DatatransPaymentStatus,
+ id: String,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, DatatransPaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ DatatransPaymentsResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: enums::AttemptStatus::from(item.response.status),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct DatatransRefundRequest {
+ pub amount: i64,
+}
+
+impl<F> TryFrom<&DatatransRouterData<&types::RefundsRouterData<F>>> for DatatransRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &DatatransRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.amount.to_owned(),
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct DatatransErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 180852c8a37..71e91373454 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1900,6 +1900,11 @@ pub(crate) fn validate_auth_and_metadata_type_with_connector(
cybersource::transformers::CybersourceAuthType::try_from(val)?;
Ok(())
}
+ // api_enums::Connector::Datatrans => {
+ // datatrans::transformers::DatatransAuthType::try_from(val)?;
+ // Ok(())
+ // }
+ // added for future use
api_enums::Connector::Dlocal => {
dlocal::transformers::DlocalAuthType::try_from(val)?;
Ok(())
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index bc5bc3ff0ef..4c55ebc359d 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -166,6 +166,7 @@ default_imp_for_complete_authorize!(
connector::Checkout,
connector::Coinbase,
connector::Cryptopay,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -247,6 +248,7 @@ default_imp_for_webhook_source_verification!(
connector::Coinbase,
connector::Cryptopay,
connector::Cybersource,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -338,6 +340,7 @@ default_imp_for_create_customer!(
connector::Coinbase,
connector::Cryptopay,
connector::Cybersource,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -423,6 +426,7 @@ default_imp_for_connector_redirect_response!(
connector::Coinbase,
connector::Cryptopay,
connector::Cybersource,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -490,6 +494,7 @@ default_imp_for_connector_request_id!(
connector::Coinbase,
connector::Cryptopay,
connector::Cybersource,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -581,6 +586,7 @@ default_imp_for_accept_dispute!(
connector::Coinbase,
connector::Cryptopay,
connector::Cybersource,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -694,6 +700,7 @@ default_imp_for_file_upload!(
connector::Coinbase,
connector::Cryptopay,
connector::Cybersource,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -784,6 +791,7 @@ default_imp_for_submit_evidence!(
connector::Cybersource,
connector::Coinbase,
connector::Cryptopay,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -874,6 +882,7 @@ default_imp_for_defend_dispute!(
connector::Cybersource,
connector::Coinbase,
connector::Cryptopay,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -962,6 +971,7 @@ default_imp_for_pre_processing_steps!(
connector::Checkout,
connector::Coinbase,
connector::Cryptopay,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Iatapay,
@@ -1027,6 +1037,7 @@ default_imp_for_payouts!(
connector::Checkout,
connector::Cryptopay,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Fiserv,
connector::Forte,
@@ -1114,6 +1125,7 @@ default_imp_for_payouts_create!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Fiserv,
connector::Forte,
@@ -1205,6 +1217,7 @@ default_imp_for_payouts_eligibility!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Fiserv,
connector::Forte,
@@ -1293,6 +1306,7 @@ default_imp_for_payouts_fulfill!(
connector::Checkout,
connector::Cryptopay,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Fiserv,
connector::Forte,
@@ -1380,6 +1394,7 @@ default_imp_for_payouts_cancel!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Fiserv,
connector::Forte,
@@ -1470,6 +1485,7 @@ default_imp_for_payouts_quote!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Fiserv,
connector::Forte,
@@ -1561,6 +1577,7 @@ default_imp_for_payouts_recipient!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Fiserv,
connector::Forte,
@@ -1654,6 +1671,7 @@ default_imp_for_payouts_recipient_account!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -1745,6 +1763,7 @@ default_imp_for_approve!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -1837,6 +1856,7 @@ default_imp_for_reject!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -1913,6 +1933,7 @@ default_imp_for_fraud_check!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -2005,6 +2026,7 @@ default_imp_for_frm_sale!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -2097,6 +2119,7 @@ default_imp_for_frm_checkout!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -2189,6 +2212,7 @@ default_imp_for_frm_transaction!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -2281,6 +2305,7 @@ default_imp_for_frm_fulfillment!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -2373,6 +2398,7 @@ default_imp_for_frm_record_return!(
connector::Cryptopay,
connector::Cybersource,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -2462,6 +2488,7 @@ default_imp_for_incremental_authorization!(
connector::Checkout,
connector::Cryptopay,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -2551,6 +2578,7 @@ default_imp_for_revoking_mandates!(
connector::Checkout,
connector::Cryptopay,
connector::Coinbase,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -2701,6 +2729,7 @@ default_imp_for_connector_authentication!(
connector::Cryptopay,
connector::Coinbase,
connector::Cybersource,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
@@ -2787,6 +2816,7 @@ default_imp_for_authorize_session_token!(
connector::Cryptopay,
connector::Coinbase,
connector::Cybersource,
+ connector::Datatrans,
connector::Dlocal,
connector::Ebanx,
connector::Fiserv,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index a40fb22e0b9..062d0b4da81 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -331,6 +331,7 @@ impl ConnectorData {
enums::Connector::Coinbase => Ok(Box::new(&connector::Coinbase)),
enums::Connector::Cryptopay => Ok(Box::new(connector::Cryptopay::new())),
enums::Connector::Cybersource => Ok(Box::new(&connector::Cybersource)),
+ // enums::Connector::Datatrans => Ok(Box::new(&connector::Datatrans)), added as template code for future use
enums::Connector::Dlocal => Ok(Box::new(&connector::Dlocal)),
#[cfg(feature = "dummy_connector")]
enums::Connector::DummyConnector1 => Ok(Box::new(&connector::DummyConnector::<1>)),
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 94d84d8ccae..404297e4aad 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -224,6 +224,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Coinbase => Self::Coinbase,
api_enums::Connector::Cryptopay => Self::Cryptopay,
api_enums::Connector::Cybersource => Self::Cybersource,
+ // api_enums::Connector::Datatrans => Self::Datatrans, added as template code for future use
api_enums::Connector::Dlocal => Self::Dlocal,
api_enums::Connector::Ebanx => Self::Ebanx,
api_enums::Connector::Fiserv => Self::Fiserv,
diff --git a/crates/router/tests/connectors/datatrans.rs b/crates/router/tests/connectors/datatrans.rs
new file mode 100644
index 00000000000..cc87b29d5bd
--- /dev/null
+++ b/crates/router/tests/connectors/datatrans.rs
@@ -0,0 +1,420 @@
+use masking::Secret;
+use router::types::{self, api, domain, storage::enums};
+use test_utils::connector_auth;
+
+use crate::utils::{self, ConnectorActions};
+
+#[derive(Clone, Copy)]
+struct DatatransTest;
+impl ConnectorActions for DatatransTest {}
+impl utils::Connector for DatatransTest {
+ fn get_data(&self) -> api::ConnectorData {
+ use router::connector::Adyen;
+ api::ConnectorData {
+ connector: Box::new(&Adyen),
+ connector_name: types::Connector::Adyen,
+ get_token: api::GetToken::Connector,
+ merchant_connector_id: None,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .datatrans
+ .expect("Missing connector authentication configuration")
+ .into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "datatrans".to_string()
+ }
+}
+
+static CONNECTOR: DatatransTest = DatatransTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenarios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: domain::PaymentMethodData::Card(domain::Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 892e1370ccc..ad19a54bbda 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -24,6 +24,7 @@ mod checkout;
mod coinbase;
mod cryptopay;
mod cybersource;
+mod datatrans;
mod dlocal;
#[cfg(feature = "dummy_connector")]
mod dummyconnector;
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 2d7b1974996..655e7c665ae 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -233,3 +233,6 @@ api_key="API Key"
[adyenplatform]
api_key="API Key"
+
+[datatrans]
+api_key="API Key"
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index 4b41506fe2d..aafccbff438 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -29,6 +29,7 @@ pub struct ConnectorAuthentication {
pub coinbase: Option<HeaderKey>,
pub cryptopay: Option<BodyKey>,
pub cybersource: Option<SignatureKey>,
+ pub datatrans: Option<HeaderKey>,
pub dlocal: Option<SignatureKey>,
#[cfg(feature = "dummy_connector")]
pub dummyconnector: Option<HeaderKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index d008ff3231c..d2dd483e9ad 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -91,6 +91,7 @@ checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
cryptopay.base_url = "https://business-sandbox.cryptopay.me"
cybersource.base_url = "https://apitest.cybersource.com/"
+datatrans.base_url = "https://api.sandbox.datatrans.com/"
dlocal.base_url = "https://sandbox.dlocal.com/"
dummyconnector.base_url = "http://localhost:8080/dummy-connector"
ebanx.base_url = "https://sandbox.ebanxpay.com/"
@@ -168,6 +169,7 @@ cards = [
"coinbase",
"cryptopay",
"cybersource",
+ "datatrans",
"dlocal",
"dummyconnector",
"ebanx",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index f35d080bfe6..f4b4fc87578 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -6,7 +6,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# Add new connector to existing list and sort it
- connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless gpayments helcim iatapay klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode payeezy payme payone paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay zsl "$1")
+ connectors=(aci adyen adyenplatform airwallex applepay authorizedotnet bambora bankofamerica billwerk bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource datatrans dlocal dummyconnector ebanx fiserv forte globalpay globepay gocardless gpayments helcim iatapay klarna mifinity mollie multisafepay netcetera nexinets noon nuvei opayo opennode payeezy payme payone paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay zsl "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
2024-06-05T13:30:31Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added Template code for Datatrans. Ran add_connector.sh script
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
No testing needed , Just added Template code for connector
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
0e059e7d847b0c15ed120c72bb4902ac60e6f955
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4881
|
Bug: FRM Analytics
Add FRM analytics and corresponding endpoints
|
diff --git a/Cargo.lock b/Cargo.lock
index 557504d98b9..cfd0da1eed2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -340,6 +340,7 @@ dependencies = [
"aws-sdk-lambda",
"aws-smithy-types 1.1.8",
"bigdecimal",
+ "common_enums",
"common_utils",
"diesel_models",
"error-stack",
@@ -1943,6 +1944,8 @@ name = "common_enums"
version = "0.1.0"
dependencies = [
"diesel",
+ "frunk",
+ "frunk_core",
"router_derive",
"serde",
"serde_json",
diff --git a/config/config.example.toml b/config/config.example.toml
index 4e3747eb8f7..d3f7771934b 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -623,6 +623,7 @@ source = "logs" # The event sink to push events supports kafka or logs (stdout)
[events.kafka]
brokers = [] # Kafka broker urls for bootstrapping the client
+fraud_check_analytics_topic = "topic" # Kafka topic to be used for FraudCheck events
intent_analytics_topic = "topic" # Kafka topic to be used for PaymentIntent events
attempt_analytics_topic = "topic" # Kafka topic to be used for PaymentAttempt events
refund_analytics_topic = "topic" # Kafka topic to be used for Refund events
diff --git a/config/development.toml b/config/development.toml
index 2aaf0e69922..c66ce39224d 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -615,6 +615,7 @@ source = "logs"
[events.kafka]
brokers = ["localhost:9092"]
+fraud_check_analytics_topic= "hyperswitch-fraud-check-events"
intent_analytics_topic = "hyperswitch-payment-intent-events"
attempt_analytics_topic = "hyperswitch-payment-attempt-events"
refund_analytics_topic = "hyperswitch-refund-events"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 2b934ceb20f..6d7414d6abd 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -435,6 +435,7 @@ delay_between_retries_in_milliseconds = 500
[events.kafka]
brokers = ["localhost:9092"]
+fraud_check_analytics_topic= "hyperswitch-fraud-check-events"
intent_analytics_topic = "hyperswitch-payment-intent-events"
attempt_analytics_topic = "hyperswitch-payment-attempt-events"
refund_analytics_topic = "hyperswitch-refund-events"
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml
index 52680df5c49..8cf4b9b911c 100644
--- a/crates/analytics/Cargo.toml
+++ b/crates/analytics/Cargo.toml
@@ -15,6 +15,7 @@ api_models = { version = "0.1.0", path = "../api_models", features = [
"errors",
] }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
+common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
external_services = { version = "0.1.0", path = "../external_services", default-features = false }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" }
diff --git a/crates/analytics/docs/clickhouse/scripts/fraud_check.sql b/crates/analytics/docs/clickhouse/scripts/fraud_check.sql
new file mode 100644
index 00000000000..19e535981b6
--- /dev/null
+++ b/crates/analytics/docs/clickhouse/scripts/fraud_check.sql
@@ -0,0 +1,132 @@
+CREATE TABLE fraud_check_queue (
+ `frm_id` String,
+ `payment_id` String,
+ `merchant_id` String,
+ `attempt_id` String,
+ `created_at` DateTime CODEC(T64, LZ4),
+ `frm_name` LowCardinality(String),
+ `frm_transaction_id` String,
+ `frm_transaction_type` LowCardinality(String),
+ `frm_status` LowCardinality(String),
+ `frm_score` Int32,
+ `frm_reason` LowCardinality(String),
+ `frm_error` Nullable(String),
+ `amount` UInt32,
+ `currency` LowCardinality(String),
+ `payment_method` LowCardinality(String),
+ `payment_method_type` LowCardinality(String),
+ `refund_transaction_id` Nullable(String),
+ `metadata` Nullable(String),
+ `modified_at` DateTime CODEC(T64, LZ4),
+ `last_step` LowCardinality(String),
+ `payment_capture_method` LowCardinality(String),
+ `sign_flag` Int8
+) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
+kafka_topic_list = 'hyperswitch-fraud-check-events',
+kafka_group_name = 'hyper',
+kafka_format = 'JSONEachRow',
+kafka_handle_error_mode = 'stream';
+
+CREATE TABLE fraud_check (
+ `frm_id` String,
+ `payment_id` String,
+ `merchant_id` LowCardinality(String),
+ `attempt_id` String,
+ `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `frm_name` LowCardinality(String),
+ `frm_transaction_id` String,
+ `frm_transaction_type` LowCardinality(String),
+ `frm_status` LowCardinality(String),
+ `frm_score` Int32,
+ `frm_reason` LowCardinality(String),
+ `frm_error` Nullable(String),
+ `amount` UInt32,
+ `currency` LowCardinality(String),
+ `payment_method` LowCardinality(String),
+ `payment_method_type` LowCardinality(String),
+ `refund_transaction_id` Nullable(String),
+ `metadata` Nullable(String),
+ `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `last_step` LowCardinality(String),
+ `payment_capture_method` LowCardinality(String),
+ `sign_flag` Int8
+ INDEX frmNameIndex frm_name TYPE bloom_filter GRANULARITY 1,
+ INDEX frmStatusIndex frm_status TYPE bloom_filter GRANULARITY 1,
+ INDEX paymentMethodIndex payment_method TYPE bloom_filter GRANULARITY 1,
+ INDEX paymentMethodTypeIndex payment_method_type TYPE bloom_filter GRANULARITY 1,
+ INDEX currencyIndex currency TYPE bloom_filter GRANULARITY 1
+) ENGINE = CollapsingMergeTree(sign_flag) PARTITION BY toStartOfDay(created_at)
+ORDER BY
+ (created_at, merchant_id, attempt_id, frm_id) TTL created_at + toIntervalMonth(18) SETTINGS index_granularity = 8192;
+
+CREATE MATERIALIZED VIEW fraud_check_mv TO fraud_check (
+ `frm_id` String,
+ `payment_id` String,
+ `merchant_id` String,
+ `attempt_id` String,
+ `created_at` DateTime64(3),
+ `frm_name` LowCardinality(String),
+ `frm_transaction_id` String,
+ `frm_transaction_type` LowCardinality(String),
+ `frm_status` LowCardinality(String),
+ `frm_score` Int32,
+ `frm_reason` LowCardinality(String),
+ `frm_error` Nullable(String),
+ `amount` UInt32,
+ `currency` LowCardinality(String),
+ `payment_method` LowCardinality(String),
+ `payment_method_type` LowCardinality(String),
+ `refund_transaction_id` Nullable(String),
+ `metadata` Nullable(String),
+ `modified_at` DateTime64(3),
+ `last_step` LowCardinality(String),
+ `payment_capture_method` LowCardinality(String),
+ `sign_flag` Int8
+) AS
+SELECT
+ frm_id,
+ payment_id,
+ merchant_id,
+ attempt_id,
+ created_at,
+ frm_name,
+ frm_transaction_id,
+ frm_transaction_type,
+ frm_status,
+ frm_score,
+ frm_reason,
+ frm_error,
+ amount,
+ currency,
+ payment_method,
+ payment_method_type,
+ refund_transaction_id,
+ metadata,
+ modified_at,
+ last_step,
+ payment_capture_method,
+ sign_flag
+FROM
+ fraud_check_queue
+WHERE
+ length(_error) = 0;
+
+CREATE MATERIALIZED VIEW fraud_check_parse_errors (
+ `topic` String,
+ `partition` Int64,
+ `offset` Int64,
+ `raw` String,
+ `error` String
+) ENGINE = MergeTree
+ORDER BY
+ (topic, partition, offset) SETTINGS index_granularity = 8192 AS
+SELECT
+ _topic AS topic,
+ _partition AS partition,
+ _offset AS offset,
+ _raw_message AS raw,
+ _error AS error
+FROM
+ fraud_check_queue
+WHERE
+ length(_error) > 0;
\ No newline at end of file
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index b455e79b253..ffca5487137 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -9,6 +9,7 @@ use time::PrimitiveDateTime;
use super::{
active_payments::metrics::ActivePaymentsMetricRow,
auth_events::metrics::AuthEventMetricRow,
+ frm::{filters::FrmFilterRow, metrics::FrmMetricRow},
health_check::HealthCheck,
payment_intents::{filters::PaymentIntentFilterRow, metrics::PaymentIntentMetricRow},
payments::{
@@ -130,6 +131,7 @@ impl AnalyticsDataSource for ClickhouseClient {
match table {
AnalyticsCollection::Payment
| AnalyticsCollection::Refund
+ | AnalyticsCollection::FraudCheck
| AnalyticsCollection::PaymentIntent
| AnalyticsCollection::Dispute => {
TableEngine::CollapsingMergeTree { sign: "sign_flag" }
@@ -162,6 +164,8 @@ impl super::payment_intents::filters::PaymentIntentFilterAnalytics for Clickhous
impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for ClickhouseClient {}
impl super::refunds::metrics::RefundMetricAnalytics for ClickhouseClient {}
impl super::refunds::filters::RefundFilterAnalytics for ClickhouseClient {}
+impl super::frm::metrics::FrmMetricAnalytics for ClickhouseClient {}
+impl super::frm::filters::FrmFilterAnalytics for ClickhouseClient {}
impl super::sdk_events::filters::SdkEventFilterAnalytics for ClickhouseClient {}
impl super::sdk_events::metrics::SdkEventMetricAnalytics for ClickhouseClient {}
impl super::sdk_events::events::SdkEventsFilterAnalytics for ClickhouseClient {}
@@ -290,6 +294,25 @@ impl TryInto<RefundFilterRow> for serde_json::Value {
}
}
+impl TryInto<FrmMetricRow> for serde_json::Value {
+ type Error = Report<ParsingError>;
+
+ fn try_into(self) -> Result<FrmMetricRow, Self::Error> {
+ serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
+ "Failed to parse FrmMetricRow in clickhouse results",
+ ))
+ }
+}
+
+impl TryInto<FrmFilterRow> for serde_json::Value {
+ type Error = Report<ParsingError>;
+
+ fn try_into(self) -> Result<FrmFilterRow, Self::Error> {
+ serde_json::from_value(self).change_context(ParsingError::StructParseFailure(
+ "Failed to parse FrmFilterRow in clickhouse results",
+ ))
+ }
+}
impl TryInto<DisputeMetricRow> for serde_json::Value {
type Error = Report<ParsingError>;
@@ -409,6 +432,7 @@ impl ToSql<ClickhouseClient> for AnalyticsCollection {
match self {
Self::Payment => Ok("payment_attempts".to_string()),
Self::Refund => Ok("refunds".to_string()),
+ Self::FraudCheck => Ok("fraud_check".to_string()),
Self::SdkEvents => Ok("sdk_events_audit".to_string()),
Self::SdkEventsAnalytics => Ok("sdk_events".to_string()),
Self::ApiEvents => Ok("api_events_audit".to_string()),
diff --git a/crates/analytics/src/core.rs b/crates/analytics/src/core.rs
index 2c5945f75b5..0e3ced7993d 100644
--- a/crates/analytics/src/core.rs
+++ b/crates/analytics/src/core.rs
@@ -21,6 +21,11 @@ pub async fn get_domain_info(
download_dimensions: None,
dimensions: utils::get_refund_dimensions(),
},
+ AnalyticsDomain::Frm => GetInfoResponse {
+ metrics: utils::get_frm_metrics_info(),
+ download_dimensions: None,
+ dimensions: utils::get_frm_dimensions(),
+ },
AnalyticsDomain::SdkEvents => GetInfoResponse {
metrics: utils::get_sdk_event_metrics_info(),
download_dimensions: None,
diff --git a/crates/analytics/src/frm.rs b/crates/analytics/src/frm.rs
new file mode 100644
index 00000000000..7598bddaaef
--- /dev/null
+++ b/crates/analytics/src/frm.rs
@@ -0,0 +1,9 @@
+pub mod accumulator;
+mod core;
+
+pub mod filters;
+pub mod metrics;
+pub mod types;
+pub use accumulator::{FrmMetricAccumulator, FrmMetricsAccumulator};
+
+pub use self::core::{get_filters, get_metrics};
diff --git a/crates/analytics/src/frm/accumulator.rs b/crates/analytics/src/frm/accumulator.rs
new file mode 100644
index 00000000000..04b60beb98e
--- /dev/null
+++ b/crates/analytics/src/frm/accumulator.rs
@@ -0,0 +1,78 @@
+use api_models::analytics::frm::FrmMetricsBucketValue;
+use common_enums::enums as storage_enums;
+
+use super::metrics::FrmMetricRow;
+#[derive(Debug, Default)]
+pub struct FrmMetricsAccumulator {
+ pub frm_triggered_attempts: TriggeredAttemptsAccumulator,
+ pub frm_blocked_rate: BlockedRateAccumulator,
+}
+
+#[derive(Debug, Default)]
+#[repr(transparent)]
+pub struct TriggeredAttemptsAccumulator {
+ pub count: Option<i64>,
+}
+
+#[derive(Debug, Default)]
+pub struct BlockedRateAccumulator {
+ pub fraud: i64,
+ pub total: i64,
+}
+
+pub trait FrmMetricAccumulator {
+ type MetricOutput;
+
+ fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow);
+
+ fn collect(self) -> Self::MetricOutput;
+}
+
+impl FrmMetricAccumulator for TriggeredAttemptsAccumulator {
+ type MetricOutput = Option<u64>;
+ #[inline]
+ fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow) {
+ self.count = match (self.count, metrics.count) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ }
+ }
+ #[inline]
+ fn collect(self) -> Self::MetricOutput {
+ self.count.and_then(|i| u64::try_from(i).ok())
+ }
+}
+
+impl FrmMetricAccumulator for BlockedRateAccumulator {
+ type MetricOutput = Option<f64>;
+
+ fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow) {
+ if let Some(ref frm_status) = metrics.frm_status {
+ if frm_status.as_ref() == &storage_enums::FraudCheckStatus::Fraud {
+ self.fraud += metrics.count.unwrap_or_default();
+ }
+ };
+ self.total += metrics.count.unwrap_or_default();
+ }
+
+ fn collect(self) -> Self::MetricOutput {
+ if self.total <= 0 {
+ None
+ } else {
+ Some(
+ f64::from(u32::try_from(self.fraud).ok()?) * 100.0
+ / f64::from(u32::try_from(self.total).ok()?),
+ )
+ }
+ }
+}
+
+impl FrmMetricsAccumulator {
+ pub fn collect(self) -> FrmMetricsBucketValue {
+ FrmMetricsBucketValue {
+ frm_blocked_rate: self.frm_blocked_rate.collect(),
+ frm_triggered_attempts: self.frm_triggered_attempts.collect(),
+ }
+ }
+}
diff --git a/crates/analytics/src/frm/core.rs b/crates/analytics/src/frm/core.rs
new file mode 100644
index 00000000000..9c9e73b49a8
--- /dev/null
+++ b/crates/analytics/src/frm/core.rs
@@ -0,0 +1,193 @@
+#![allow(dead_code)]
+use std::collections::HashMap;
+
+use api_models::analytics::{
+ frm::{FrmDimensions, FrmMetrics, FrmMetricsBucketIdentifier, FrmMetricsBucketResponse},
+ AnalyticsMetadata, FrmFilterValue, FrmFiltersResponse, GetFrmFilterRequest,
+ GetFrmMetricRequest, MetricsResponse,
+};
+use error_stack::ResultExt;
+use router_env::{
+ logger,
+ metrics::add_attributes,
+ tracing::{self, Instrument},
+};
+
+use super::{
+ filters::{get_frm_filter_for_dimension, FrmFilterRow},
+ FrmMetricsAccumulator,
+};
+use crate::{
+ errors::{AnalyticsError, AnalyticsResult},
+ frm::FrmMetricAccumulator,
+ metrics, AnalyticsProvider,
+};
+
+pub async fn get_metrics(
+ pool: &AnalyticsProvider,
+ merchant_id: &String,
+ req: GetFrmMetricRequest,
+) -> AnalyticsResult<MetricsResponse<FrmMetricsBucketResponse>> {
+ let mut metrics_accumulator: HashMap<FrmMetricsBucketIdentifier, FrmMetricsAccumulator> =
+ HashMap::new();
+ let mut set = tokio::task::JoinSet::new();
+ for metric_type in req.metrics.iter().cloned() {
+ let req = req.clone();
+ let pool = pool.clone();
+ let task_span =
+ tracing::debug_span!("analytics_frm_query", frm_metric = metric_type.as_ref());
+ // Currently JoinSet works with only static lifetime references even if the task pool does not outlive the given reference
+ // We can optimize away this clone once that is fixed
+ let merchant_id_scoped = merchant_id.to_owned();
+ set.spawn(
+ async move {
+ let data = pool
+ .get_frm_metrics(
+ &metric_type,
+ &req.group_by_names.clone(),
+ &merchant_id_scoped,
+ &req.filters,
+ &req.time_series.map(|t| t.granularity),
+ &req.time_range,
+ )
+ .await
+ .change_context(AnalyticsError::UnknownError);
+ (metric_type, data)
+ }
+ .instrument(task_span),
+ );
+ }
+
+ while let Some((metric, data)) = set
+ .join_next()
+ .await
+ .transpose()
+ .change_context(AnalyticsError::UnknownError)?
+ {
+ let data = data?;
+
+ let attributes = &add_attributes([
+ ("metric_type", metric.to_string()),
+ ("source", pool.to_string()),
+ ]);
+ let value = u64::try_from(data.len());
+ if let Ok(val) = value {
+ metrics::BUCKETS_FETCHED.record(&metrics::CONTEXT, val, attributes);
+ logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
+ }
+
+ for (id, value) in data {
+ logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
+ let metrics_builder = metrics_accumulator.entry(id).or_default();
+ match metric {
+ FrmMetrics::FrmBlockedRate => {
+ metrics_builder.frm_blocked_rate.add_metrics_bucket(&value)
+ }
+ FrmMetrics::FrmTriggeredAttempts => metrics_builder
+ .frm_triggered_attempts
+ .add_metrics_bucket(&value),
+ }
+ }
+
+ logger::debug!(
+ "Analytics Accumulated Results: metric: {}, results: {:#?}",
+ metric,
+ metrics_accumulator
+ );
+ }
+ let query_data: Vec<FrmMetricsBucketResponse> = metrics_accumulator
+ .into_iter()
+ .map(|(id, val)| FrmMetricsBucketResponse {
+ values: val.collect(),
+ dimensions: id,
+ })
+ .collect();
+
+ Ok(MetricsResponse {
+ query_data,
+ meta_data: [AnalyticsMetadata {
+ current_time_range: req.time_range,
+ }],
+ })
+}
+
+pub async fn get_filters(
+ pool: &AnalyticsProvider,
+ req: GetFrmFilterRequest,
+ merchant_id: &String,
+) -> AnalyticsResult<FrmFiltersResponse> {
+ let mut res = FrmFiltersResponse::default();
+ for dim in req.group_by_names {
+ let values = match pool {
+ AnalyticsProvider::Sqlx(pool) => {
+ get_frm_filter_for_dimension(dim, merchant_id, &req.time_range, pool)
+ .await
+}
+ AnalyticsProvider::Clickhouse(pool) => {
+ get_frm_filter_for_dimension(dim, merchant_id, &req.time_range, pool)
+ .await
+}
+ AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => {
+ let ckh_result = get_frm_filter_for_dimension(
+ dim,
+ merchant_id,
+ &req.time_range,
+ ckh_pool,
+ )
+ .await;
+ let sqlx_result = get_frm_filter_for_dimension(
+ dim,
+ merchant_id,
+ &req.time_range,
+ sqlx_pool,
+ )
+ .await;
+ match (&sqlx_result, &ckh_result) {
+ (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
+ logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics filters")
+ },
+ _ => {}
+ };
+ ckh_result
+}
+ AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => {
+ let ckh_result = get_frm_filter_for_dimension(
+ dim,
+ merchant_id,
+ &req.time_range,
+ ckh_pool,
+ )
+ .await;
+ let sqlx_result = get_frm_filter_for_dimension(
+ dim,
+ merchant_id,
+ &req.time_range,
+ sqlx_pool,
+ )
+ .await;
+ match (&sqlx_result, &ckh_result) {
+ (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
+ logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics filters")
+ },
+ _ => {}
+ };
+ sqlx_result
+}
+}
+ .change_context(AnalyticsError::UnknownError)?
+ .into_iter()
+ .filter_map(|fil: FrmFilterRow| match dim {
+ FrmDimensions::FrmStatus => fil.frm_status.map(|i| i.as_ref().to_string()),
+ FrmDimensions::FrmName => fil.frm_name,
+ FrmDimensions::FrmTransactionType => {
+ fil.frm_transaction_type.map(|i| i.as_ref().to_string())
+ }
+ })
+ .collect::<Vec<String>>();
+ res.query_data.push(FrmFilterValue {
+ dimension: dim,
+ values,
+ })
+ }
+ Ok(res)
+}
diff --git a/crates/analytics/src/frm/filters.rs b/crates/analytics/src/frm/filters.rs
new file mode 100644
index 00000000000..c019f61d427
--- /dev/null
+++ b/crates/analytics/src/frm/filters.rs
@@ -0,0 +1,59 @@
+use api_models::analytics::{
+ frm::{FrmDimensions, FrmTransactionType},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use diesel_models::enums::FraudCheckStatus;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use crate::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window},
+ types::{
+ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult,
+ LoadRow,
+ },
+};
+pub trait FrmFilterAnalytics: LoadRow<FrmFilterRow> {}
+
+pub async fn get_frm_filter_for_dimension<T>(
+ dimension: FrmDimensions,
+ merchant: &String,
+ time_range: &TimeRange,
+ pool: &T,
+) -> FiltersResult<Vec<FrmFilterRow>>
+where
+ T: AnalyticsDataSource + FrmFilterAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::FraudCheck);
+
+ query_builder.add_select_column(dimension).switch()?;
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ query_builder
+ .add_filter_clause("merchant_id", merchant)
+ .switch()?;
+
+ query_builder.set_distinct();
+
+ query_builder
+ .execute_query::<FrmFilterRow, _>(pool)
+ .await
+ .change_context(FiltersError::QueryBuildingError)?
+ .change_context(FiltersError::QueryExecutionFailure)
+}
+
+#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
+pub struct FrmFilterRow {
+ pub frm_status: Option<DBEnumWrapper<FraudCheckStatus>>,
+ pub frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>>,
+ pub frm_name: Option<String>,
+}
diff --git a/crates/analytics/src/frm/metrics.rs b/crates/analytics/src/frm/metrics.rs
new file mode 100644
index 00000000000..8f904090983
--- /dev/null
+++ b/crates/analytics/src/frm/metrics.rs
@@ -0,0 +1,99 @@
+use api_models::analytics::{
+ frm::{FrmDimensions, FrmFilters, FrmMetrics, FrmMetricsBucketIdentifier, FrmTransactionType},
+ Granularity, TimeRange,
+};
+use diesel_models::enums as storage_enums;
+use time::PrimitiveDateTime;
+mod frm_blocked_rate;
+mod frm_triggered_attempts;
+
+use frm_blocked_rate::FrmBlockedRate;
+use frm_triggered_attempts::FrmTriggeredAttempts;
+
+use crate::{
+ query::{Aggregate, GroupByClause, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult},
+};
+#[derive(Debug, Eq, PartialEq, serde::Deserialize)]
+pub struct FrmMetricRow {
+ pub frm_name: Option<String>,
+ pub frm_status: Option<DBEnumWrapper<storage_enums::FraudCheckStatus>>,
+ pub frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>>,
+ pub total: Option<bigdecimal::BigDecimal>,
+ pub count: Option<i64>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub start_bucket: Option<PrimitiveDateTime>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub end_bucket: Option<PrimitiveDateTime>,
+}
+
+pub trait FrmMetricAnalytics: LoadRow<FrmMetricRow> {}
+
+#[async_trait::async_trait]
+pub trait FrmMetric<T>
+where
+ T: AnalyticsDataSource + FrmMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[FrmDimensions],
+ merchant_id: &str,
+ filters: &FrmFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>>;
+}
+
+#[async_trait::async_trait]
+impl<T> FrmMetric<T> for FrmMetrics
+where
+ T: AnalyticsDataSource + FrmMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[FrmDimensions],
+ merchant_id: &str,
+ filters: &FrmFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> {
+ match self {
+ Self::FrmTriggeredAttempts => {
+ FrmTriggeredAttempts::default()
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::FrmBlockedRate => {
+ FrmBlockedRate::default()
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ }
+ }
+}
diff --git a/crates/analytics/src/frm/metrics/frm_blocked_rate.rs b/crates/analytics/src/frm/metrics/frm_blocked_rate.rs
new file mode 100644
index 00000000000..5f331feab6c
--- /dev/null
+++ b/crates/analytics/src/frm/metrics/frm_blocked_rate.rs
@@ -0,0 +1,117 @@
+use api_models::analytics::{
+ frm::{FrmDimensions, FrmFilters, FrmMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::FrmMetricRow;
+use crate::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(super) struct FrmBlockedRate {}
+
+#[async_trait::async_trait]
+impl<T> super::FrmMetric<T> for FrmBlockedRate
+where
+ T: AnalyticsDataSource + super::FrmMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[FrmDimensions],
+ merchant_id: &str,
+ filters: &FrmFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::FrmMetricAnalytics,
+ {
+ let mut query_builder = QueryBuilder::new(AnalyticsCollection::FraudCheck);
+ let mut dimensions = dimensions.to_vec();
+
+ dimensions.push(FrmDimensions::FrmStatus);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ query_builder
+ .add_filter_clause("merchant_id", merchant_id)
+ .switch()?;
+
+ time_range.set_filter_clause(&mut query_builder).switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder.add_group_by_clause(dim).switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<FrmMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ FrmMetricsBucketIdentifier::new(
+ i.frm_name.as_ref().map(|i| i.to_string()),
+ None,
+ i.frm_transaction_type.as_ref().map(|i| i.0.to_string()),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<
+ Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs b/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs
new file mode 100644
index 00000000000..b72345c4e3a
--- /dev/null
+++ b/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs
@@ -0,0 +1,116 @@
+use api_models::analytics::{
+ frm::{FrmDimensions, FrmFilters, FrmMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::FrmMetricRow;
+use crate::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+
+#[derive(Default)]
+pub(super) struct FrmTriggeredAttempts {}
+
+#[async_trait::async_trait]
+impl<T> super::FrmMetric<T> for FrmTriggeredAttempts
+where
+ T: AnalyticsDataSource + super::FrmMetricAnalytics,
+ PrimitiveDateTime: ToSql<T>,
+ AnalyticsCollection: ToSql<T>,
+ Granularity: GroupByClause<T>,
+ Aggregate<&'static str>: ToSql<T>,
+ Window<&'static str>: ToSql<T>,
+{
+ async fn load_metrics(
+ &self,
+ dimensions: &[FrmDimensions],
+ merchant_id: &str,
+ filters: &FrmFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> {
+ let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::FraudCheck);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Count {
+ field: None,
+ alias: Some("count"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Min {
+ field: "created_at",
+ alias: Some("start_bucket"),
+ })
+ .switch()?;
+ query_builder
+ .add_select_column(Aggregate::Max {
+ field: "created_at",
+ alias: Some("end_bucket"),
+ })
+ .switch()?;
+
+ filters.set_filter_clause(&mut query_builder).switch()?;
+
+ query_builder
+ .add_filter_clause("merchant_id", merchant_id)
+ .switch()?;
+
+ time_range
+ .set_filter_clause(&mut query_builder)
+ .attach_printable("Error filtering time range")
+ .switch()?;
+
+ for dim in dimensions.iter() {
+ query_builder
+ .add_group_by_clause(dim)
+ .attach_printable("Error grouping by dimensions")
+ .switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .attach_printable("Error adding granularity")
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<FrmMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ FrmMetricsBucketIdentifier::new(
+ i.frm_name.as_ref().map(|i| i.to_string()),
+ i.frm_status.as_ref().map(|i| i.0.to_string()),
+ i.frm_transaction_type.as_ref().map(|i| i.0.to_string()),
+ TimeRange {
+ start_time: match (granularity, i.start_bucket) {
+ (Some(g), Some(st)) => g.clip_to_start(st)?,
+ _ => time_range.start_time,
+ },
+ end_time: granularity.as_ref().map_or_else(
+ || Ok(time_range.end_time),
+ |g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
+ )?,
+ },
+ ),
+ i,
+ ))
+ })
+ .collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/frm/types.rs b/crates/analytics/src/frm/types.rs
new file mode 100644
index 00000000000..72fc65098bd
--- /dev/null
+++ b/crates/analytics/src/frm/types.rs
@@ -0,0 +1,38 @@
+use api_models::analytics::frm::{FrmDimensions, FrmFilters};
+use error_stack::ResultExt;
+
+use crate::{
+ query::{QueryBuilder, QueryFilter, QueryResult, ToSql},
+ types::{AnalyticsCollection, AnalyticsDataSource},
+};
+
+impl<T> QueryFilter<T> for FrmFilters
+where
+ T: AnalyticsDataSource,
+ AnalyticsCollection: ToSql<T>,
+{
+ fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> {
+ if !self.frm_status.is_empty() {
+ builder
+ .add_filter_in_range_clause(FrmDimensions::FrmStatus, &self.frm_status)
+ .attach_printable("Error adding frm status filter")?;
+ }
+
+ if !self.frm_name.is_empty() {
+ builder
+ .add_filter_in_range_clause(FrmDimensions::FrmName, &self.frm_name)
+ .attach_printable("Error adding frm name filter")?;
+ }
+
+ if !self.frm_transaction_type.is_empty() {
+ builder
+ .add_filter_in_range_clause(
+ FrmDimensions::FrmTransactionType,
+ &self.frm_transaction_type,
+ )
+ .attach_printable("Error adding frm transaction type filter")?;
+ }
+
+ Ok(())
+ }
+}
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 10e628475e8..69afcec5524 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -2,6 +2,7 @@ mod clickhouse;
pub mod core;
pub mod disputes;
pub mod errors;
+pub mod frm;
pub mod metrics;
pub mod payment_intents;
pub mod payments;
@@ -40,6 +41,7 @@ use api_models::analytics::{
},
auth_events::{AuthEventMetrics, AuthEventMetricsBucketIdentifier},
disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier},
+ frm::{FrmDimensions, FrmFilters, FrmMetrics, FrmMetricsBucketIdentifier},
payment_intents::{
PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetrics,
PaymentIntentMetricsBucketIdentifier,
@@ -65,6 +67,7 @@ use strum::Display;
use self::{
active_payments::metrics::{ActivePaymentsMetric, ActivePaymentsMetricRow},
auth_events::metrics::{AuthEventMetric, AuthEventMetricRow},
+ frm::metrics::{FrmMetric, FrmMetricRow},
payment_intents::metrics::{PaymentIntentMetric, PaymentIntentMetricRow},
payments::{
distribution::{PaymentDistribution, PaymentDistributionRow},
@@ -524,6 +527,106 @@ impl AnalyticsProvider {
.await
}
+ pub async fn get_frm_metrics(
+ &self,
+ metric: &FrmMetrics,
+ dimensions: &[FrmDimensions],
+ merchant_id: &str,
+ filters: &FrmFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ ) -> types::MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> {
+ // Metrics to get the fetch time for each refund metric
+ metrics::request::record_operation_time(
+ async {
+ match self {
+ Self::Sqlx(pool) => {
+ metric
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::Clickhouse(pool) => {
+ metric
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::CombinedCkh(sqlx_pool, ckh_pool) => {
+ let (ckh_result, sqlx_result) = tokio::join!(
+ metric.load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ ckh_pool,
+ ),
+ metric.load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ sqlx_pool,
+ )
+ );
+ match (&sqlx_result, &ckh_result) {
+ (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
+ logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics metrics")
+ }
+ _ => {}
+ };
+ ckh_result
+ }
+ Self::CombinedSqlx(sqlx_pool, ckh_pool) => {
+ let (ckh_result, sqlx_result) = tokio::join!(
+ metric.load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ ckh_pool,
+ ),
+ metric.load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ sqlx_pool,
+ )
+ );
+ match (&sqlx_result, &ckh_result) {
+ (Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
+ logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics metrics")
+ }
+ _ => {}
+ };
+ sqlx_result
+ }
+ }
+ },
+ &metrics::METRIC_FETCH_TIME,
+ metric,
+ self,
+ )
+ .await
+ }
+
pub async fn get_dispute_metrics(
&self,
metric: &DisputeMetrics,
@@ -869,12 +972,14 @@ pub enum AnalyticsFlow {
GetPaymentMetrics,
GetPaymentIntentMetrics,
GetRefundsMetrics,
+ GetFrmMetrics,
GetSdkMetrics,
GetAuthMetrics,
GetActivePaymentsMetrics,
GetPaymentFilters,
GetPaymentIntentFilters,
GetRefundFilters,
+ GetFrmFilters,
GetSdkEventFilters,
GetApiEvents,
GetSdkEvents,
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index a257fedc09d..381deb60b80 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -6,6 +6,7 @@ use api_models::{
api_event::ApiEventDimensions,
auth_events::AuthEventFlows,
disputes::DisputeDimensions,
+ frm::{FrmDimensions, FrmTransactionType},
payment_intents::PaymentIntentDimensions,
payments::{PaymentDimensions, PaymentDistributions},
refunds::{RefundDimensions, RefundType},
@@ -19,7 +20,7 @@ use api_models::{
refunds::RefundStatus,
};
use common_utils::errors::{CustomResult, ParsingError};
-use diesel_models::enums as storage_enums;
+use diesel_models::{enums as storage_enums, enums::FraudCheckStatus};
use error_stack::ResultExt;
use router_env::{logger, Flow};
@@ -372,10 +373,12 @@ impl_to_sql_for_to_string!(
&PaymentDimensions,
&PaymentIntentDimensions,
&RefundDimensions,
+ &FrmDimensions,
PaymentDimensions,
PaymentIntentDimensions,
&PaymentDistributions,
RefundDimensions,
+ FrmDimensions,
PaymentMethod,
PaymentMethodType,
AuthenticationType,
@@ -383,9 +386,11 @@ impl_to_sql_for_to_string!(
AttemptStatus,
IntentStatus,
RefundStatus,
+ FraudCheckStatus,
storage_enums::RefundStatus,
Currency,
RefundType,
+ FrmTransactionType,
Flow,
&String,
&bool,
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 6a4faf50eb8..656a2448a44 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -1,7 +1,7 @@
use std::{fmt::Display, str::FromStr};
use api_models::{
- analytics::refunds::RefundType,
+ analytics::{frm::FrmTransactionType, refunds::RefundType},
enums::{DisputeStage, DisputeStatus},
};
use common_utils::{
@@ -9,7 +9,8 @@ use common_utils::{
DbConnectionParams,
};
use diesel_models::enums::{
- AttemptStatus, AuthenticationType, Currency, IntentStatus, PaymentMethod, RefundStatus,
+ AttemptStatus, AuthenticationType, Currency, FraudCheckStatus, IntentStatus, PaymentMethod,
+ RefundStatus,
};
use error_stack::ResultExt;
use sqlx::{
@@ -91,6 +92,8 @@ db_type!(IntentStatus);
db_type!(PaymentMethod, TEXT);
db_type!(RefundStatus);
db_type!(RefundType);
+db_type!(FraudCheckStatus);
+db_type!(FrmTransactionType);
db_type!(DisputeStage);
db_type!(DisputeStatus);
@@ -150,6 +153,8 @@ impl super::refunds::metrics::RefundMetricAnalytics for SqlxClient {}
impl super::refunds::filters::RefundFilterAnalytics for SqlxClient {}
impl super::disputes::filters::DisputeFilterAnalytics for SqlxClient {}
impl super::disputes::metrics::DisputeMetricAnalytics for SqlxClient {}
+impl super::frm::metrics::FrmMetricAnalytics for SqlxClient {}
+impl super::frm::filters::FrmFilterAnalytics for SqlxClient {}
#[async_trait::async_trait]
impl AnalyticsDataSource for SqlxClient {
@@ -230,6 +235,49 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::metrics::RefundMetricRow {
}
}
+impl<'a> FromRow<'a, PgRow> for super::frm::metrics::FrmMetricRow {
+ fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
+ let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> =
+ row.try_get("frm_status").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> =
+ row.try_get("frm_transaction_type").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let total: Option<bigdecimal::BigDecimal> = row.try_get("total").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let count: Option<i64> = row.try_get("count").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ // Removing millisecond precision to get accurate diffs against clickhouse
+ let start_bucket: Option<PrimitiveDateTime> = row
+ .try_get::<Option<PrimitiveDateTime>, _>("start_bucket")?
+ .and_then(|dt| dt.replace_millisecond(0).ok());
+ let end_bucket: Option<PrimitiveDateTime> = row
+ .try_get::<Option<PrimitiveDateTime>, _>("end_bucket")?
+ .and_then(|dt| dt.replace_millisecond(0).ok());
+ Ok(Self {
+ frm_name,
+ frm_status,
+ frm_transaction_type,
+ total,
+ count,
+ start_bucket,
+ end_bucket,
+ })
+ }
+}
+
impl<'a> FromRow<'a, PgRow> for super::payments::metrics::PaymentMetricRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let currency: Option<DBEnumWrapper<Currency>> =
@@ -516,6 +564,30 @@ impl<'a> FromRow<'a, PgRow> for super::refunds::filters::RefundFilterRow {
}
}
+impl<'a> FromRow<'a, PgRow> for super::frm::filters::FrmFilterRow {
+ fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
+ let frm_name: Option<String> = row.try_get("frm_name").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let frm_status: Option<DBEnumWrapper<FraudCheckStatus>> =
+ row.try_get("frm_status").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>> =
+ row.try_get("frm_transaction_type").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ Ok(Self {
+ frm_name,
+ frm_status,
+ frm_transaction_type,
+ })
+ }
+}
+
impl<'a> FromRow<'a, PgRow> for super::disputes::filters::DisputeFilterRow {
fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
let dispute_stage: Option<String> = row.try_get("dispute_stage").or_else(|e| match e {
@@ -604,6 +676,7 @@ impl ToSql<SqlxClient> for AnalyticsCollection {
.attach_printable("SdkEvents table is not implemented for Sqlx"))?,
Self::ApiEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ApiEvents table is not implemented for Sqlx"))?,
+ Self::FraudCheck => Ok("fraud_check".to_string()),
Self::PaymentIntent => Ok("payment_intent".to_string()),
Self::ConnectorEvents => Err(error_stack::report!(ParsingError::UnknownError)
.attach_printable("ConnectorEvents table is not implemented for Sqlx"))?,
diff --git a/crates/analytics/src/types.rs b/crates/analytics/src/types.rs
index 816c77fd304..12a82801d54 100644
--- a/crates/analytics/src/types.rs
+++ b/crates/analytics/src/types.rs
@@ -15,6 +15,7 @@ use crate::errors::AnalyticsError;
pub enum AnalyticsDomain {
Payments,
Refunds,
+ Frm,
PaymentIntents,
AuthEvents,
SdkEvents,
@@ -26,6 +27,7 @@ pub enum AnalyticsDomain {
pub enum AnalyticsCollection {
Payment,
Refund,
+ FraudCheck,
SdkEvents,
SdkEventsAnalytics,
ApiEvents,
diff --git a/crates/analytics/src/utils.rs b/crates/analytics/src/utils.rs
index 3955a8c1dfe..7b73f5a1c1d 100644
--- a/crates/analytics/src/utils.rs
+++ b/crates/analytics/src/utils.rs
@@ -2,6 +2,7 @@ use api_models::analytics::{
api_event::{ApiEventDimensions, ApiEventMetrics},
auth_events::AuthEventMetrics,
disputes::{DisputeDimensions, DisputeMetrics},
+ frm::{FrmDimensions, FrmMetrics},
payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics},
payments::{PaymentDimensions, PaymentMetrics},
refunds::{RefundDimensions, RefundMetrics},
@@ -22,6 +23,10 @@ pub fn get_refund_dimensions() -> Vec<NameDescription> {
RefundDimensions::iter().map(Into::into).collect()
}
+pub fn get_frm_dimensions() -> Vec<NameDescription> {
+ FrmDimensions::iter().map(Into::into).collect()
+}
+
pub fn get_sdk_event_dimensions() -> Vec<NameDescription> {
SdkEventDimensions::iter().map(Into::into).collect()
}
@@ -42,6 +47,10 @@ pub fn get_refund_metrics_info() -> Vec<NameDescription> {
RefundMetrics::iter().map(Into::into).collect()
}
+pub fn get_frm_metrics_info() -> Vec<NameDescription> {
+ FrmMetrics::iter().map(Into::into).collect()
+}
+
pub fn get_sdk_event_metrics_info() -> Vec<NameDescription> {
SdkEventMetrics::iter().map(Into::into).collect()
}
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 0bd0b01a278..80737cfbc41 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -35,7 +35,6 @@ url = { version = "2.5.0", features = ["serde"] }
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] }
frunk = "0.4.2"
frunk_core = "0.4.2"
-
# First party crates
cards = { version = "0.1.0", path = "../cards" }
common_enums = { version = "0.1.0", path = "../common_enums" }
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index 85a9c3ded09..ca10d7ce599 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -1,6 +1,6 @@
use std::collections::HashSet;
-use common_utils::pii::EmailStrategy;
+use common_utils::{events::ApiEventMetric, pii::EmailStrategy};
use masking::Secret;
use self::{
@@ -8,6 +8,7 @@ use self::{
api_event::{ApiEventDimensions, ApiEventMetrics},
auth_events::AuthEventMetrics,
disputes::{DisputeDimensions, DisputeMetrics},
+ frm::{FrmDimensions, FrmMetrics},
payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics},
payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics},
refunds::{RefundDimensions, RefundMetrics},
@@ -20,6 +21,7 @@ pub mod api_event;
pub mod auth_events;
pub mod connector_events;
pub mod disputes;
+pub mod frm;
pub mod outgoing_webhook_event;
pub mod payment_intents;
pub mod payments;
@@ -144,6 +146,22 @@ pub struct GetRefundMetricRequest {
pub delta: bool,
}
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetFrmMetricRequest {
+ pub time_series: Option<TimeSeries>,
+ pub time_range: TimeRange,
+ #[serde(default)]
+ pub group_by_names: Vec<FrmDimensions>,
+ #[serde(default)]
+ pub filters: frm::FrmFilters,
+ pub metrics: HashSet<FrmMetrics>,
+ #[serde(default)]
+ pub delta: bool,
+}
+
+impl ApiEventMetric for GetFrmMetricRequest {}
+
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSdkEventMetricRequest {
@@ -247,6 +265,33 @@ pub struct RefundFilterValue {
pub values: Vec<String>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetFrmFilterRequest {
+ pub time_range: TimeRange,
+ #[serde(default)]
+ pub group_by_names: Vec<FrmDimensions>,
+}
+
+impl ApiEventMetric for GetFrmFilterRequest {}
+
+#[derive(Debug, Default, serde::Serialize, Eq, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct FrmFiltersResponse {
+ pub query_data: Vec<FrmFilterValue>,
+}
+
+impl ApiEventMetric for FrmFiltersResponse {}
+
+#[derive(Debug, serde::Serialize, Eq, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct FrmFilterValue {
+ pub dimension: FrmDimensions,
+ pub values: Vec<String>,
+}
+
+impl ApiEventMetric for FrmFilterValue {}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSdkEventFiltersRequest {
diff --git a/crates/api_models/src/analytics/frm.rs b/crates/api_models/src/analytics/frm.rs
new file mode 100644
index 00000000000..3ac45e75894
--- /dev/null
+++ b/crates/api_models/src/analytics/frm.rs
@@ -0,0 +1,163 @@
+use std::{
+ collections::hash_map::DefaultHasher,
+ hash::{Hash, Hasher},
+};
+
+use common_enums::enums::FraudCheckStatus;
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ PartialEq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum FrmTransactionType {
+ #[default]
+ PreFrm,
+ PostFrm,
+}
+
+use super::{NameDescription, TimeRange};
+#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
+pub struct FrmFilters {
+ #[serde(default)]
+ pub frm_status: Vec<FraudCheckStatus>,
+ #[serde(default)]
+ pub frm_name: Vec<String>,
+ #[serde(default)]
+ pub frm_transaction_type: Vec<FrmTransactionType>,
+}
+
+#[derive(
+ Debug,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::AsRefStr,
+ PartialEq,
+ PartialOrd,
+ Eq,
+ Ord,
+ strum::Display,
+ strum::EnumIter,
+ Clone,
+ Copy,
+)]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum FrmDimensions {
+ FrmStatus,
+ FrmName,
+ FrmTransactionType,
+}
+
+#[derive(
+ Clone,
+ Debug,
+ Hash,
+ PartialEq,
+ Eq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumIter,
+ strum::AsRefStr,
+)]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+pub enum FrmMetrics {
+ FrmTriggeredAttempts,
+ FrmBlockedRate,
+}
+
+pub mod metric_behaviour {
+ pub struct FrmTriggeredAttempts;
+ pub struct FrmBlockRate;
+}
+
+impl From<FrmMetrics> for NameDescription {
+ fn from(value: FrmMetrics) -> Self {
+ Self {
+ name: value.to_string(),
+ desc: String::new(),
+ }
+ }
+}
+
+impl From<FrmDimensions> for NameDescription {
+ fn from(value: FrmDimensions) -> Self {
+ Self {
+ name: value.to_string(),
+ desc: String::new(),
+ }
+ }
+}
+
+#[derive(Debug, serde::Serialize, Eq)]
+pub struct FrmMetricsBucketIdentifier {
+ pub frm_status: Option<String>,
+ pub frm_name: Option<String>,
+ pub frm_transaction_type: Option<String>,
+ #[serde(rename = "time_range")]
+ pub time_bucket: TimeRange,
+ #[serde(rename = "time_bucket")]
+ #[serde(with = "common_utils::custom_serde::iso8601custom")]
+ pub start_time: time::PrimitiveDateTime,
+}
+
+impl Hash for FrmMetricsBucketIdentifier {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.frm_status.hash(state);
+ self.frm_name.hash(state);
+ self.frm_transaction_type.hash(state);
+ self.time_bucket.hash(state);
+ }
+}
+
+impl PartialEq for FrmMetricsBucketIdentifier {
+ fn eq(&self, other: &Self) -> bool {
+ let mut left = DefaultHasher::new();
+ self.hash(&mut left);
+ let mut right = DefaultHasher::new();
+ other.hash(&mut right);
+ left.finish() == right.finish()
+ }
+}
+
+impl FrmMetricsBucketIdentifier {
+ pub fn new(
+ frm_status: Option<String>,
+ frm_name: Option<String>,
+ frm_transaction_type: Option<String>,
+ normalized_time_range: TimeRange,
+ ) -> Self {
+ Self {
+ frm_status,
+ frm_name,
+ frm_transaction_type,
+ time_bucket: normalized_time_range,
+ start_time: normalized_time_range.start_time,
+ }
+ }
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct FrmMetricsBucketValue {
+ pub frm_triggered_attempts: Option<u64>,
+ pub frm_blocked_rate: Option<f64>,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct FrmMetricsBucketResponse {
+ #[serde(flatten)]
+ pub values: FrmMetricsBucketValue,
+ #[serde(flatten)]
+ pub dimensions: FrmMetricsBucketIdentifier,
+}
diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml
index 5c88236b8ae..e364af0407d 100644
--- a/crates/common_enums/Cargo.toml
+++ b/crates/common_enums/Cargo.toml
@@ -18,6 +18,8 @@ serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
strum = { version = "0.26", features = ["derive"] }
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] }
+frunk = "0.4.2"
+frunk_core = "0.4.2"
# First party crates
router_derive = { version = "0.1.0", path = "../router_derive" }
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 2ad0ad35cb3..492aed35797 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -10,7 +10,8 @@ pub mod diesel_exports {
DbBlocklistDataKind as BlocklistDataKind, DbCaptureMethod as CaptureMethod,
DbCaptureStatus as CaptureStatus, DbConnectorType as ConnectorType,
DbCountryAlpha2 as CountryAlpha2, DbCurrency as Currency, DbDisputeStage as DisputeStage,
- DbDisputeStatus as DisputeStatus, DbEventType as EventType, DbFutureUsage as FutureUsage,
+ DbDisputeStatus as DisputeStatus, DbEventType as EventType,
+ DbFraudCheckStatus as FraudCheckStatus, DbFutureUsage as FutureUsage,
DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus,
DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentType as PaymentType,
DbRefundStatus as RefundStatus,
@@ -236,6 +237,30 @@ pub enum AuthenticationType {
}
/// The status of the capture
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ PartialEq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+ frunk::LabelledGeneric,
+)]
+#[router_derive::diesel_enum(storage_type = "db_enum")]
+#[strum(serialize_all = "snake_case")]
+pub enum FraudCheckStatus {
+ Fraud,
+ ManualReview,
+ #[default]
+ Pending,
+ Legit,
+ TransactionFailure,
+}
+
#[derive(
Clone,
Copy,
@@ -1556,6 +1581,28 @@ pub enum RefundStatus {
TransactionFailure,
}
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ Hash,
+ PartialEq,
+ strum::Display,
+ strum::EnumString,
+ strum::EnumIter,
+ serde::Serialize,
+ serde::Deserialize,
+)]
+#[router_derive::diesel_enum(storage_type = "db_enum")]
+#[strum(serialize_all = "snake_case")]
+pub enum FrmTransactionType {
+ #[default]
+ PreFrm,
+ PostFrm,
+}
+
/// The status of the mandate, which indicates whether it can be used to initiate a payment.
#[derive(
Clone,
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index e95116f99a4..5eeed2990af 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -194,30 +194,6 @@ pub enum FraudCheckType {
PostFrm,
}
-#[derive(
- Clone,
- Copy,
- Debug,
- Default,
- Eq,
- PartialEq,
- serde::Serialize,
- serde::Deserialize,
- strum::Display,
- strum::EnumString,
- frunk::LabelledGeneric,
-)]
-#[diesel_enum(storage_type = "db_enum")]
-#[strum(serialize_all = "snake_case")]
-pub enum FraudCheckStatus {
- Fraud,
- ManualReview,
- #[default]
- Pending,
- Legit,
- TransactionFailure,
-}
-
#[derive(
Clone,
Copy,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 64f62f48762..cf98748048d 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -14,9 +14,10 @@ pub mod routes {
},
GenerateReportRequest, GetActivePaymentsMetricRequest, GetApiEventFiltersRequest,
GetApiEventMetricRequest, GetAuthEventMetricRequest, GetDisputeMetricRequest,
- GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest,
- GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest,
- GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest,
+ GetFrmFilterRequest, GetFrmMetricRequest, GetPaymentFiltersRequest,
+ GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, GetPaymentMetricRequest,
+ GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest,
+ GetSdkEventMetricRequest, ReportRequest,
};
use error_stack::ResultExt;
@@ -54,6 +55,9 @@ pub mod routes {
web::resource("filters/payments")
.route(web::post().to(get_payment_filters)),
)
+ .service(
+ web::resource("filters/frm").route(web::post().to(get_frm_filters)),
+ )
.service(
web::resource("filters/refunds")
.route(web::post().to(get_refund_filters)),
@@ -87,6 +91,9 @@ pub mod routes {
web::resource("metrics/auth_events")
.route(web::post().to(get_auth_event_metrics)),
)
+ .service(
+ web::resource("metrics/frm").route(web::post().to(get_frm_metrics)),
+ )
.service(
web::resource("api_event_logs").route(web::get().to(get_api_events)),
)
@@ -270,6 +277,38 @@ pub mod routes {
.await
}
+ /// # Panics
+ ///
+ /// Panics if `json_payload` array does not contain one `GetFrmMetricRequest` element.
+ pub async fn get_frm_metrics(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<[GetFrmMetricRequest; 1]>,
+ ) -> impl Responder {
+ #[allow(clippy::expect_used)]
+ // safety: This shouldn't panic owing to the data type
+ let payload = json_payload
+ .into_inner()
+ .to_vec()
+ .pop()
+ .expect("Couldn't get GetFrmMetricRequest");
+ let flow = AnalyticsFlow::GetFrmMetrics;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: AuthenticationData, req, _| async move {
+ analytics::frm::get_metrics(&state.pool, &auth.merchant_account.merchant_id, req)
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth(Permission::Analytics),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetSdkEventMetricRequest` element.
@@ -458,6 +497,28 @@ pub mod routes {
.await
}
+ pub async fn get_frm_filters(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<GetFrmFilterRequest>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GetFrmFilters;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, auth: AuthenticationData, req: GetFrmFilterRequest, _| async move {
+ analytics::frm::get_filters(&state.pool, req, &auth.merchant_account.merchant_id)
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth(Permission::Analytics),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
pub async fn get_sdk_event_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 2a00e7adbb6..34210cf6de6 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -36,9 +36,8 @@ pub mod user;
pub mod user_authentication_method;
pub mod user_key_store;
pub mod user_role;
-
use diesel_models::{
- fraud_check::{FraudCheck, FraudCheckNew, FraudCheckUpdate},
+ fraud_check::{FraudCheck, FraudCheckUpdate},
organization::{Organization, OrganizationNew, OrganizationUpdate},
};
use error_stack::ResultExt;
@@ -53,16 +52,23 @@ use hyperswitch_domain_models::payouts::{
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use masking::PeekInterface;
use redis_interface::errors::RedisError;
+use router_env::logger;
use storage_impl::{errors::StorageError, redis::kv_store::RedisConnInterface, MockDb};
pub use self::kafka_store::KafkaStore;
use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface};
pub use crate::{
+ core::errors::{self, ProcessTrackerError},
errors::CustomResult,
services::{
kafka::{KafkaError, KafkaProducer, MQResult},
Store,
},
+ types::{
+ domain,
+ storage::{self},
+ AccessToken,
+ },
};
#[derive(PartialEq, Eq)]
@@ -259,36 +265,74 @@ impl RequestIdStore for KafkaStore {
impl FraudCheckInterface for KafkaStore {
async fn insert_fraud_check_response(
&self,
- new: FraudCheckNew,
+ new: storage::FraudCheckNew,
) -> CustomResult<FraudCheck, StorageError> {
- self.diesel_store.insert_fraud_check_response(new).await
+ let frm = self.diesel_store.insert_fraud_check_response(new).await?;
+ if let Err(er) = self
+ .kafka_producer
+ .log_fraud_check(&frm, None, self.tenant_id.clone())
+ .await
+ {
+ logger::error!(message = "Failed to log analytics event for fraud check", error_message = ?er);
+ }
+ Ok(frm)
}
async fn update_fraud_check_response_with_attempt_id(
&self,
- fraud_check: FraudCheck,
- fraud_check_update: FraudCheckUpdate,
+ this: FraudCheck,
+ fraud_check: FraudCheckUpdate,
) -> CustomResult<FraudCheck, StorageError> {
- self.diesel_store
- .update_fraud_check_response_with_attempt_id(fraud_check, fraud_check_update)
+ let frm = self
+ .diesel_store
+ .update_fraud_check_response_with_attempt_id(this, fraud_check)
+ .await?;
+ if let Err(er) = self
+ .kafka_producer
+ .log_fraud_check(&frm, None, self.tenant_id.clone())
.await
+ {
+ logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er)
+ }
+ Ok(frm)
}
async fn find_fraud_check_by_payment_id(
&self,
payment_id: String,
merchant_id: String,
) -> CustomResult<FraudCheck, StorageError> {
- self.diesel_store
+ let frm = self
+ .diesel_store
.find_fraud_check_by_payment_id(payment_id, merchant_id)
+ .await?;
+ if let Err(er) = self
+ .kafka_producer
+ .log_fraud_check(&frm, None, self.tenant_id.clone())
.await
+ {
+ logger::error!(message="Failed to log analytics event for fraud check {frm:?}", error_message=?er)
+ }
+ Ok(frm)
}
async fn find_fraud_check_by_payment_id_if_present(
&self,
payment_id: String,
merchant_id: String,
) -> CustomResult<Option<FraudCheck>, StorageError> {
- self.diesel_store
+ let frm = self
+ .diesel_store
.find_fraud_check_by_payment_id_if_present(payment_id, merchant_id)
- .await
+ .await?;
+
+ if let Some(fraud_check) = frm.clone() {
+ if let Err(er) = self
+ .kafka_producer
+ .log_fraud_check(&fraud_check, None, self.tenant_id.clone())
+ .await
+ {
+ logger::error!(message="Failed to log analytics event for frm {frm:?}", error_message=?er);
+ }
+ }
+ Ok(frm)
}
}
diff --git a/crates/router/src/db/fraud_check.rs b/crates/router/src/db/fraud_check.rs
index 34818260364..9e27f451019 100644
--- a/crates/router/src/db/fraud_check.rs
+++ b/crates/router/src/db/fraud_check.rs
@@ -116,33 +116,3 @@ impl FraudCheckInterface for MockDb {
Err(errors::StorageError::MockDbError)?
}
}
-
-#[cfg(feature = "kafka_events")]
-#[async_trait::async_trait]
-impl FraudCheckInterface for super::KafkaStore {
- #[instrument(skip_all)]
- async fn insert_fraud_check_response(
- &self,
- _new: storage::FraudCheckNew,
- ) -> CustomResult<FraudCheck, errors::StorageError> {
- Err(errors::StorageError::MockDbError)?
- }
-
- #[instrument(skip_all)]
- async fn update_fraud_check_response_with_attempt_id(
- &self,
- _this: FraudCheck,
- _fraud_check: FraudCheckUpdate,
- ) -> CustomResult<FraudCheck, errors::StorageError> {
- Err(errors::StorageError::MockDbError)?
- }
-
- #[instrument(skip_all)]
- async fn find_fraud_check_by_payment_id(
- &self,
- _payment_id: String,
- _merchant_id: String,
- ) -> CustomResult<FraudCheck, errors::StorageError> {
- Err(errors::StorageError::MockDbError)?
- }
-}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index e5686d616d4..edf8a53346c 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -83,7 +83,7 @@ pub struct TenantID(pub String);
#[derive(Clone)]
pub struct KafkaStore {
- kafka_producer: KafkaProducer,
+ pub kafka_producer: KafkaProducer,
pub diesel_store: Store,
pub tenant_id: TenantID,
}
diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs
index 1bdd9016c49..b7ab4ebaa1e 100644
--- a/crates/router/src/events.rs
+++ b/crates/router/src/events.rs
@@ -23,6 +23,7 @@ pub mod outgoing_webhook_logs;
#[serde(rename_all = "snake_case")]
pub enum EventType {
PaymentIntent,
+ FraudCheck,
PaymentAttempt,
Refund,
ApiLogs,
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index b245eb3fe74..d1abda2105d 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -11,11 +11,15 @@ use rdkafka::{
};
#[cfg(feature = "payouts")]
pub mod payout;
-use crate::events::EventType;
+use diesel_models::fraud_check::FraudCheck;
+
+use crate::{events::EventType, services::kafka::fraud_check_event::KafkaFraudCheckEvent};
mod authentication;
mod authentication_event;
mod dispute;
mod dispute_event;
+mod fraud_check;
+mod fraud_check_event;
mod payment_attempt;
mod payment_attempt_event;
mod payment_intent;
@@ -36,7 +40,7 @@ use self::{
payment_intent_event::KafkaPaymentIntentEvent, refund::KafkaRefund,
refund_event::KafkaRefundEvent,
};
-use crate::types::storage::Dispute;
+use crate::{services::kafka::fraud_check::KafkaFraudCheck, types::storage::Dispute};
// Using message queue result here to avoid confusion with Kafka result provided by library
pub type MQResult<T> = CustomResult<T, KafkaError>;
@@ -139,6 +143,7 @@ impl<'a, T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'a, T> {
#[serde(default)]
pub struct KafkaSettings {
brokers: Vec<String>,
+ fraud_check_analytics_topic: String,
intent_analytics_topic: String,
attempt_analytics_topic: String,
refund_analytics_topic: String,
@@ -246,6 +251,7 @@ impl KafkaSettings {
pub struct KafkaProducer {
producer: Arc<RdKafkaProducer>,
intent_analytics_topic: String,
+ fraud_check_analytics_topic: String,
attempt_analytics_topic: String,
refund_analytics_topic: String,
api_logs_topic: String,
@@ -288,6 +294,7 @@ impl KafkaProducer {
.change_context(KafkaError::InitializationError)?,
)),
+ fraud_check_analytics_topic: conf.fraud_check_analytics_topic.clone(),
intent_analytics_topic: conf.intent_analytics_topic.clone(),
attempt_analytics_topic: conf.attempt_analytics_topic.clone(),
refund_analytics_topic: conf.refund_analytics_topic.clone(),
@@ -321,6 +328,38 @@ impl KafkaProducer {
.map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}")))
.change_context(KafkaError::GenericError)
}
+ pub async fn log_fraud_check(
+ &self,
+ attempt: &FraudCheck,
+ old_attempt: Option<FraudCheck>,
+ tenant_id: TenantID,
+ ) -> MQResult<()> {
+ if let Some(negative_event) = old_attempt {
+ self.log_event(&KafkaEvent::old(
+ &KafkaFraudCheck::from_storage(&negative_event),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| {
+ format!("Failed to add negative fraud check event {negative_event:?}")
+ })?;
+ };
+
+ self.log_event(&KafkaEvent::new(
+ &KafkaFraudCheck::from_storage(attempt),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| {
+ format!("Failed to add positive fraud check event {attempt:?}")
+ })?;
+
+ self.log_event(&KafkaConsolidatedEvent::new(
+ &KafkaFraudCheckEvent::from_storage(attempt),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| {
+ format!("Failed to add consolidated fraud check event {attempt:?}")
+ })
+ }
pub async fn log_payment_attempt(
&self,
@@ -544,6 +583,7 @@ impl KafkaProducer {
pub fn get_topic(&self, event: EventType) -> &str {
match event {
+ EventType::FraudCheck => &self.fraud_check_analytics_topic,
EventType::ApiLogs => &self.api_logs_topic,
EventType::PaymentAttempt => &self.attempt_analytics_topic,
EventType::PaymentIntent => &self.intent_analytics_topic,
diff --git a/crates/router/src/services/kafka/fraud_check.rs b/crates/router/src/services/kafka/fraud_check.rs
new file mode 100644
index 00000000000..e52fbbbc9ac
--- /dev/null
+++ b/crates/router/src/services/kafka/fraud_check.rs
@@ -0,0 +1,67 @@
+// use diesel_models::enums as storage_enums;
+use diesel_models::{
+ enums as storage_enums,
+ enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType},
+ fraud_check::FraudCheck,
+};
+use time::OffsetDateTime;
+
+#[derive(serde::Serialize, Debug)]
+pub struct KafkaFraudCheck<'a> {
+ pub frm_id: &'a String,
+ pub payment_id: &'a String,
+ pub merchant_id: &'a String,
+ pub attempt_id: &'a String,
+ #[serde(with = "time::serde::timestamp")]
+ pub created_at: OffsetDateTime,
+ pub frm_name: &'a String,
+ pub frm_transaction_id: Option<&'a String>,
+ pub frm_transaction_type: FraudCheckType,
+ pub frm_status: FraudCheckStatus,
+ pub frm_score: Option<i32>,
+ pub frm_reason: Option<serde_json::Value>,
+ pub frm_error: Option<&'a String>,
+ pub payment_details: Option<serde_json::Value>,
+ pub metadata: Option<serde_json::Value>,
+ #[serde(with = "time::serde::timestamp")]
+ pub modified_at: OffsetDateTime,
+ pub last_step: FraudCheckLastStep,
+ pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision.
+}
+
+impl<'a> KafkaFraudCheck<'a> {
+ pub fn from_storage(check: &'a FraudCheck) -> Self {
+ Self {
+ frm_id: &check.frm_id,
+ payment_id: &check.payment_id,
+ merchant_id: &check.merchant_id,
+ attempt_id: &check.attempt_id,
+ created_at: check.created_at.assume_utc(),
+ frm_name: &check.frm_name,
+ frm_transaction_id: check.frm_transaction_id.as_ref(),
+ frm_transaction_type: check.frm_transaction_type,
+ frm_status: check.frm_status,
+ frm_score: check.frm_score,
+ frm_reason: check.frm_reason.clone(),
+ frm_error: check.frm_error.as_ref(),
+ payment_details: check.payment_details.clone(),
+ metadata: check.metadata.clone(),
+ modified_at: check.modified_at.assume_utc(),
+ last_step: check.last_step,
+ payment_capture_method: check.payment_capture_method,
+ }
+ }
+}
+
+impl<'a> super::KafkaMessage for KafkaFraudCheck<'a> {
+ fn key(&self) -> String {
+ format!(
+ "{}_{}_{}_{}",
+ self.merchant_id, self.payment_id, self.attempt_id, self.frm_id
+ )
+ }
+
+ fn event_type(&self) -> crate::events::EventType {
+ crate::events::EventType::FraudCheck
+ }
+}
diff --git a/crates/router/src/services/kafka/fraud_check_event.rs b/crates/router/src/services/kafka/fraud_check_event.rs
new file mode 100644
index 00000000000..57dc4d20876
--- /dev/null
+++ b/crates/router/src/services/kafka/fraud_check_event.rs
@@ -0,0 +1,66 @@
+use diesel_models::{
+ enums as storage_enums,
+ enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType},
+ fraud_check::FraudCheck,
+};
+use time::OffsetDateTime;
+
+#[derive(serde::Serialize, Debug)]
+pub struct KafkaFraudCheckEvent<'a> {
+ pub frm_id: &'a String,
+ pub payment_id: &'a String,
+ pub merchant_id: &'a String,
+ pub attempt_id: &'a String,
+ #[serde(default, with = "time::serde::timestamp::milliseconds")]
+ pub created_at: OffsetDateTime,
+ pub frm_name: &'a String,
+ pub frm_transaction_id: Option<&'a String>,
+ pub frm_transaction_type: FraudCheckType,
+ pub frm_status: FraudCheckStatus,
+ pub frm_score: Option<i32>,
+ pub frm_reason: Option<serde_json::Value>,
+ pub frm_error: Option<&'a String>,
+ pub payment_details: Option<serde_json::Value>,
+ pub metadata: Option<serde_json::Value>,
+ #[serde(default, with = "time::serde::timestamp::milliseconds")]
+ pub modified_at: OffsetDateTime,
+ pub last_step: FraudCheckLastStep,
+ pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision.
+}
+
+impl<'a> KafkaFraudCheckEvent<'a> {
+ pub fn from_storage(check: &'a FraudCheck) -> Self {
+ Self {
+ frm_id: &check.frm_id,
+ payment_id: &check.payment_id,
+ merchant_id: &check.merchant_id,
+ attempt_id: &check.attempt_id,
+ created_at: check.created_at.assume_utc(),
+ frm_name: &check.frm_name,
+ frm_transaction_id: check.frm_transaction_id.as_ref(),
+ frm_transaction_type: check.frm_transaction_type,
+ frm_status: check.frm_status,
+ frm_score: check.frm_score,
+ frm_reason: check.frm_reason.clone(),
+ frm_error: check.frm_error.as_ref(),
+ payment_details: check.payment_details.clone(),
+ metadata: check.metadata.clone(),
+ modified_at: check.modified_at.assume_utc(),
+ last_step: check.last_step,
+ payment_capture_method: check.payment_capture_method,
+ }
+ }
+}
+
+impl<'a> super::KafkaMessage for KafkaFraudCheckEvent<'a> {
+ fn key(&self) -> String {
+ format!(
+ "{}_{}_{}_{}",
+ self.merchant_id, self.payment_id, self.attempt_id, self.frm_id
+ )
+ }
+
+ fn event_type(&self) -> crate::events::EventType {
+ crate::events::EventType::FraudCheck
+ }
+}
|
2024-06-05T06:39:40Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added frm dashboard metrics and filters.
Filters based on:
- frm_status
- frm_name
- frm_transaction_type
Metrics calculated:
- frm_triggered_attempts
- frm_blocked_rate
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Can get analytics insights based on frm
## How did you test it?
Below is the collection for testing :
[frms.postman_collection.json](https://github.com/user-attachments/files/15897457/frms.postman_collection.json)
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Tested using local data by sending cURL requests through Postman.
<img width="1287" alt="Screenshot 2024-06-05 at 11 57 32 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/3ef62a2a-62f0-4235-8ae9-c7de11b08675">
<img width="1278" alt="Screenshot 2024-06-05 at 11 57 49 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b1c5131a-0a9d-4999-82f6-09cd70dd25d0">
<img width="1285" alt="Screenshot 2024-06-05 at 11 58 01 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b4bdb5bf-deb0-4723-8b01-bf236ae5aa0f">
<img width="952" alt="Screenshot 2024-06-05 at 11 58 35 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b271cd09-eac4-42c5-96b7-05fcab9067aa">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7004a802de2d30b97ecd37f57ba0e9c3aa962993
|
Below is the collection for testing :
[frms.postman_collection.json](https://github.com/user-attachments/files/15897457/frms.postman_collection.json)
Tested using local data by sending cURL requests through Postman.
<img width="1287" alt="Screenshot 2024-06-05 at 11 57 32 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/3ef62a2a-62f0-4235-8ae9-c7de11b08675">
<img width="1278" alt="Screenshot 2024-06-05 at 11 57 49 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b1c5131a-0a9d-4999-82f6-09cd70dd25d0">
<img width="1285" alt="Screenshot 2024-06-05 at 11 58 01 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b4bdb5bf-deb0-4723-8b01-bf236ae5aa0f">
<img width="952" alt="Screenshot 2024-06-05 at 11 58 35 AM" src="https://github.com/juspay/hyperswitch/assets/83278309/b271cd09-eac4-42c5-96b7-05fcab9067aa">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4848
|
Bug: refactor: Home and Sign out API changes for 2FA Phase - II
As we are having the reset TOTP and regenerate recovery codes flows in the Phase - II, we need to let FE know whether the user has completed the 2FA or not and also number of recovery codes left for the user, so that FE can show a warning if there are less.
And also redis needs to be cleaned up if user signs out.
|
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index ee9498cfeee..a61b9fd7dff 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -165,7 +165,10 @@ pub struct GetUserDetailsResponse {
#[serde(skip_serializing)]
pub user_id: String,
pub org_id: String,
+ pub is_two_factor_auth_setup: bool,
+ pub recovery_codes_left: Option<usize>,
}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetUserRoleDetailsRequest {
pub email: pii::Email,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index c259e87c93d..f7ef79bb7d6 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -94,6 +94,8 @@ pub async fn get_user_details(
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()),
},
))
}
@@ -328,6 +330,10 @@ pub async fn signout(
state: SessionState,
user_from_token: auth::UserFromToken,
) -> 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()
}
diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs
index a0915f3ed86..aa0077e00ae 100644
--- a/crates/router/src/utils/user/two_factor_auth.rs
+++ b/crates/router/src/utils/user/two_factor_auth.rs
@@ -115,3 +115,26 @@ pub async fn insert_recovery_code_in_redis(state: &SessionState, user_id: &str)
.await
.change_context(UserErrors::InternalServerError)
}
+
+pub async fn delete_totp_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection(state)?;
+ let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id);
+ redis_conn
+ .delete_key(&key)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|_| ())
+}
+
+pub async fn delete_recovery_code_from_redis(
+ state: &SessionState,
+ user_id: &str,
+) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection(state)?;
+ let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id);
+ redis_conn
+ .delete_key(&key)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|_| ())
+}
|
2024-06-03T10:06:39Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
After this PR, Home API will send the details about the user's 2FA, specifically weather user has completed 2FA setup and number of recovery codes left for him.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #4848
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Home API
```
curl --location 'http://localhost:8080/user' \
--header 'Authorization: Bearer Login Token'
```
```json
{
"merchant_id": "company_name",
"name": "name",
"email": "email",
"verification_days_left": null,
"role_id": "org_admin",
"org_id": "org_lbZlm2cx4j2LgVo7bUwq",
"is_two_factor_auth_setup": true,
"recovery_codes_left": 8
}
```
2. Signout
1. Hit Signout API
```
curl --location --request POST 'http://localhost:8080/user/signout' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer Login Token'
```
200 OK
2. Signin with the same user again
```
curl --location 'http://localhost:8080/user/v2/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "password"
}'
```
```
{
"flow_type": "dashboard_entry",
"token": "Login Token",
"merchant_id": "company_name",
"name": "name",
"email": "email",
"verification_days_left": null,
"user_role": "org_admin"
}
```
3. Take the token from the above response and hit 2FA status API
```
curl --location 'http://localhost:8080/user/2fa' \
--header 'Authorization: Bearer Login Token'
```
```
{
"totp": false,
"recovery_code": false
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
15d6c3e846a77dec6b6a5165d86044a9b9fd52f1
|
1. Home API
```
curl --location 'http://localhost:8080/user' \
--header 'Authorization: Bearer Login Token'
```
```json
{
"merchant_id": "company_name",
"name": "name",
"email": "email",
"verification_days_left": null,
"role_id": "org_admin",
"org_id": "org_lbZlm2cx4j2LgVo7bUwq",
"is_two_factor_auth_setup": true,
"recovery_codes_left": 8
}
```
2. Signout
1. Hit Signout API
```
curl --location --request POST 'http://localhost:8080/user/signout' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer Login Token'
```
200 OK
2. Signin with the same user again
```
curl --location 'http://localhost:8080/user/v2/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "password"
}'
```
```
{
"flow_type": "dashboard_entry",
"token": "Login Token",
"merchant_id": "company_name",
"name": "name",
"email": "email",
"verification_days_left": null,
"user_role": "org_admin"
}
```
3. Take the token from the above response and hit 2FA status API
```
curl --location 'http://localhost:8080/user/2fa' \
--header 'Authorization: Bearer Login Token'
```
```
{
"totp": false,
"recovery_code": false
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4850
|
Bug: [REFACTOR] use `const` instead of `String` for `business_status`
As of now, we've around `9` distinct values for `process_tracker` and all these values are hard coded as Strings in various places.
This makes it harder for us to keep track of the values that exist in the code base.
As a measure to tackle this issue, we would have to create a set of `const`s in scheduler crate and use them in places where we've used hardcoded strings now. This will help us keep track of all the values that are used and helps increase readability.
|
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs
index cd0dbed2c64..135c8e2b055 100644
--- a/crates/diesel_models/src/process_tracker.rs
+++ b/crates/diesel_models/src/process_tracker.rs
@@ -76,8 +76,6 @@ impl ProcessTrackerNew {
where
T: Serialize + std::fmt::Debug,
{
- const BUSINESS_STATUS_PENDING: &str = "Pending";
-
let current_time = common_utils::date_time::now();
Ok(Self {
id: process_tracker_id.into(),
@@ -91,7 +89,7 @@ impl ProcessTrackerNew {
.encode_to_value()
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to serialize process tracker tracking data")?,
- business_status: String::from(BUSINESS_STATUS_PENDING),
+ business_status: String::from(business_status::PENDING),
status: storage_enums::ProcessTrackerStatus::New,
event: vec![],
created_at: current_time,
@@ -227,3 +225,42 @@ mod tests {
assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow);
}
}
+
+pub mod business_status {
+ /// Indicates that an irrecoverable error occurred during the workflow execution.
+ pub const GLOBAL_FAILURE: &str = "GLOBAL_FAILURE";
+
+ /// Task successfully completed by consumer.
+ /// A task that reaches this status should not be retried (rescheduled for execution) later.
+ pub const COMPLETED_BY_PT: &str = "COMPLETED_BY_PT";
+
+ /// An error occurred during the workflow execution which prevents further execution and
+ /// retries.
+ /// A task that reaches this status should not be retried (rescheduled for execution) later.
+ pub const FAILURE: &str = "FAILURE";
+
+ /// The resource associated with the task was removed, due to which further retries can/should
+ /// not be done.
+ pub const REVOKED: &str = "Revoked";
+
+ /// The task was executed for the maximum possible number of times without a successful outcome.
+ /// A task that reaches this status should not be retried (rescheduled for execution) later.
+ pub const RETRIES_EXCEEDED: &str = "RETRIES_EXCEEDED";
+
+ /// The outgoing webhook was successfully delivered in the initial attempt.
+ /// Further retries of the task are not required.
+ pub const INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL: &str = "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL";
+
+ /// Indicates that an error occurred during the workflow execution.
+ /// This status is typically set by the workflow error handler.
+ /// A task that reaches this status should not be retried (rescheduled for execution) later.
+ pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR";
+
+ /// The resource associated with the task has been significantly modified since the task was
+ /// created, due to which further retries of the current task are not required.
+ /// A task that reaches this status should not be retried (rescheduled for execution) later.
+ pub const RESOURCE_STATUS_MISMATCH: &str = "RESOURCE_STATUS_MISMATCH";
+
+ /// Business status set for newly created tasks.
+ pub const PENDING: &str = "Pending";
+}
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 7e78a355e5c..167e7a6b6ed 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -4,7 +4,7 @@ use std::{collections::HashMap, str::FromStr, sync::Arc};
use actix_web::{dev::Server, web, Scope};
use api_models::health_check::SchedulerHealthCheckResponse;
use common_utils::ext_traits::{OptionExt, StringExt};
-use diesel_models::process_tracker as storage;
+use diesel_models::process_tracker::{self as storage, business_status};
use error_stack::ResultExt;
use router::{
configs::settings::{CmdLineConf, Settings},
@@ -329,10 +329,13 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
let status = state
.get_db()
.as_scheduler()
- .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string())
+ .finish_process_with_business_status(
+ process,
+ business_status::GLOBAL_FAILURE,
+ )
.await;
if let Err(err) = status {
- logger::error!(%err, "Failed while performing database operation: GLOBAL_FAILURE");
+ logger::error!(%err, "Failed while performing database operation: {}", business_status::GLOBAL_FAILURE);
}
}
},
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index 8fe536731d3..ef81e3c190d 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -381,7 +381,9 @@ pub async fn update_api_key_expiry_task(
retry_count: Some(0),
schedule_time,
tracking_data: Some(updated_api_key_expiry_workflow_model),
- business_status: Some("Pending".to_string()),
+ business_status: Some(String::from(
+ diesel_models::process_tracker::business_status::PENDING,
+ )),
status: Some(storage_enums::ProcessTrackerStatus::New),
updated_at: Some(current_time),
};
@@ -450,7 +452,7 @@ pub async fn revoke_api_key_expiry_task(
let task_ids = vec![task_id];
let updated_process_tracker_data = storage::ProcessTrackerUpdate::StatusUpdate {
status: storage_enums::ProcessTrackerStatus::Finish,
- business_status: Some("Revoked".to_string()),
+ business_status: Some(String::from(diesel_models::business_status::REVOKED)),
};
store
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 9e20017d57f..f37385b80c6 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -1178,7 +1178,7 @@ pub async fn start_tokenize_data_workflow(
db.as_scheduler()
.finish_process_with_business_status(
tokenize_tracker.clone(),
- "COMPLETED_BY_PT".to_string(),
+ diesel_models::process_tracker::business_status::COMPLETED_BY_PT,
)
.await?;
}
@@ -1241,7 +1241,10 @@ pub async fn retry_delete_tokenize(
}
None => db
.as_scheduler()
- .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string())
+ .finish_process_with_business_status(
+ pt,
+ diesel_models::process_tracker::business_status::RETRIES_EXCEEDED,
+ )
.await
.map_err(Into::into),
}
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 0d441e95382..164fd1ec784 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -9,6 +9,7 @@ use common_utils::{
ext_traits::{AsyncExt, ValueExt},
types::MinorUnit,
};
+use diesel_models::process_tracker::business_status;
use error_stack::{report, ResultExt};
use masking::PeekInterface;
use router_env::{instrument, tracing};
@@ -1028,7 +1029,7 @@ pub async fn sync_refund_with_gateway_workflow(
.as_scheduler()
.finish_process_with_business_status(
refund_tracker.clone(),
- "COMPLETED_BY_PT".to_string(),
+ business_status::COMPLETED_BY_PT,
)
.await?
}
@@ -1193,7 +1194,7 @@ pub async fn trigger_refund_execute_workflow(
db.as_scheduler()
.finish_process_with_business_status(
refund_tracker.clone(),
- "COMPLETED_BY_PT".to_string(),
+ business_status::COMPLETED_BY_PT,
)
.await?;
}
diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs
index 0be4e9272f0..07fe78f51ce 100644
--- a/crates/router/src/core/webhooks/outgoing.rs
+++ b/crates/router/src/core/webhooks/outgoing.rs
@@ -3,6 +3,7 @@ use api_models::{
webhooks,
};
use common_utils::{ext_traits::Encode, request::RequestContent};
+use diesel_models::process_tracker::business_status;
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use router_env::{
@@ -231,7 +232,7 @@ async fn trigger_webhook_to_merchant(
state
.store
.as_scheduler()
- .finish_process_with_business_status(process_tracker, "FAILURE".into())
+ .finish_process_with_business_status(process_tracker, business_status::FAILURE)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
@@ -304,7 +305,7 @@ async fn trigger_webhook_to_merchant(
state.clone(),
&business_profile.merchant_id,
process_tracker,
- "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL",
+ business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
.await?;
} else {
@@ -769,7 +770,7 @@ async fn success_response_handler(
Some(process_tracker) => state
.store
.as_scheduler()
- .finish_process_with_business_status(process_tracker, business_status.into())
+ .finish_process_with_business_status(process_tracker, business_status)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0545191318d..75b830cbb41 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1821,7 +1821,7 @@ impl ProcessTrackerInterface for KafkaStore {
async fn finish_process_with_business_status(
&self,
this: storage::ProcessTracker,
- business_status: String,
+ business_status: &'static str,
) -> CustomResult<(), errors::StorageError> {
self.diesel_store
.finish_process_with_business_status(this, business_status)
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index 79c8b2ed2f0..f5626c267d2 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -40,7 +40,8 @@ pub mod user_role;
use std::collections::HashMap;
pub use diesel_models::{
- ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner, ProcessTrackerUpdate,
+ process_tracker::business_status, ProcessTracker, ProcessTrackerNew, ProcessTrackerRunner,
+ ProcessTrackerUpdate,
};
pub use hyperswitch_domain_models::payments::{
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs
index dff7905a262..c24671be34d 100644
--- a/crates/router/src/workflows/api_key_expiry.rs
+++ b/crates/router/src/workflows/api_key_expiry.rs
@@ -1,5 +1,7 @@
use common_utils::{errors::ValidationError, ext_traits::ValueExt};
-use diesel_models::{enums as storage_enums, ApiKeyExpiryTrackingData};
+use diesel_models::{
+ enums as storage_enums, process_tracker::business_status, ApiKeyExpiryTrackingData,
+};
use router_env::logger;
use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerSessionState};
@@ -96,7 +98,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow {
state
.get_db()
.as_scheduler()
- .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string())
+ .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)
.await?
}
// If tasks are remaining that has to be scheduled
diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs
index 9184a78b6b2..7560da210d1 100644
--- a/crates/router/src/workflows/outgoing_webhook_retry.rs
+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs
@@ -6,6 +6,7 @@ use api_models::{
webhooks::{OutgoingWebhook, OutgoingWebhookContent},
};
use common_utils::ext_traits::{StringExt, ValueExt};
+use diesel_models::process_tracker::business_status;
use error_stack::ResultExt;
use masking::PeekInterface;
use router_env::tracing::{self, instrument};
@@ -197,7 +198,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
db.as_scheduler()
.finish_process_with_business_status(
process.clone(),
- "RESOURCE_STATUS_MISMATCH".to_string(),
+ business_status::RESOURCE_STATUS_MISMATCH,
)
.await?;
}
@@ -309,7 +310,7 @@ pub(crate) async fn retry_webhook_delivery_task(
}
None => {
db.as_scheduler()
- .finish_process_with_business_status(process, "RETRIES_EXCEEDED".to_string())
+ .finish_process_with_business_status(process, business_status::RETRIES_EXCEEDED)
.await
}
}
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index c34b8ebe73b..666de8c3376 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -1,4 +1,5 @@
use common_utils::ext_traits::{OptionExt, StringExt, ValueExt};
+use diesel_models::process_tracker::business_status;
use error_stack::ResultExt;
use router_env::logger;
use scheduler::{
@@ -89,7 +90,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {
state
.store
.as_scheduler()
- .finish_process_with_business_status(process, "COMPLETED_BY_PT".to_string())
+ .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)
.await?
}
_ => {
@@ -269,7 +270,7 @@ pub async fn retry_sync_task(
}
None => {
db.as_scheduler()
- .finish_process_with_business_status(pt, "RETRIES_EXCEEDED".to_string())
+ .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
.await?;
Ok(true)
}
diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs
index 3e15a7cde0f..b58e8ce60d7 100644
--- a/crates/scheduler/src/consumer.rs
+++ b/crates/scheduler/src/consumer.rs
@@ -30,7 +30,7 @@ use crate::{
// Valid consumer business statuses
pub fn valid_business_statuses() -> Vec<&'static str> {
- vec!["Pending"]
+ vec![storage::business_status::PENDING]
}
#[instrument(skip_all)]
@@ -262,7 +262,7 @@ pub async fn consumer_error_handler(
vec![process.id],
storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Finish,
- business_status: Some("GLOBAL_ERROR".to_string()),
+ business_status: Some(String::from(storage::business_status::GLOBAL_ERROR)),
},
)
.await
diff --git a/crates/scheduler/src/consumer/workflows.rs b/crates/scheduler/src/consumer/workflows.rs
index bbece87f309..974f1ec4153 100644
--- a/crates/scheduler/src/consumer/workflows.rs
+++ b/crates/scheduler/src/consumer/workflows.rs
@@ -1,6 +1,7 @@
use async_trait::async_trait;
use common_utils::errors::CustomResult;
pub use diesel_models::process_tracker as storage;
+use diesel_models::process_tracker::business_status;
use router_env::logger;
use crate::{errors, SchedulerSessionState};
@@ -45,7 +46,10 @@ pub trait ProcessTrackerWorkflows<T>: Send + Sync {
let status = app_state
.get_db()
.as_scheduler()
- .finish_process_with_business_status(process, "GLOBAL_FAILURE".to_string())
+ .finish_process_with_business_status(
+ process,
+ business_status::GLOBAL_FAILURE,
+ )
.await;
if let Err(error) = status {
logger::error!(?error, "Failed to update process business status");
diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rs
index feb201f8b75..c73b53b608c 100644
--- a/crates/scheduler/src/db/process_tracker.rs
+++ b/crates/scheduler/src/db/process_tracker.rs
@@ -52,7 +52,7 @@ pub trait ProcessTrackerInterface: Send + Sync + 'static {
async fn finish_process_with_business_status(
&self,
this: storage::ProcessTracker,
- business_status: String,
+ business_status: &'static str,
) -> CustomResult<(), errors::StorageError>;
async fn find_processes_by_time_status(
@@ -166,13 +166,13 @@ impl ProcessTrackerInterface for Store {
async fn finish_process_with_business_status(
&self,
this: storage::ProcessTracker,
- business_status: String,
+ business_status: &'static str,
) -> CustomResult<(), errors::StorageError> {
self.update_process(
this,
storage::ProcessTrackerUpdate::StatusUpdate {
status: storage_enums::ProcessTrackerStatus::Finish,
- business_status: Some(business_status),
+ business_status: Some(String::from(business_status)),
},
)
.await
@@ -284,7 +284,7 @@ impl ProcessTrackerInterface for MockDb {
async fn finish_process_with_business_status(
&self,
_this: storage::ProcessTracker,
- _business_status: String,
+ _business_status: &'static str,
) -> CustomResult<(), errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
|
2024-06-03T09:31:02Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
When below command is executed in sandbox DB, we get a set of "distinct" `business_status`es that is specified for process tracker:
```sql
SELECT DISTINCT(business_status) FROM process_tracker;
```
For debugging and fun, execute to learn more about process tracker and its behavior:
```sql
SELECT DISTINCT(name, retry_count, business_status, status), created_at FROM process_tracker order by created_at desc LIMIT 10000;
```
The main goal for us here is to keep all the `business_status`es in a single place, confined for ease of access and increased readability. This also helps us keep track of the statuses we use.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
We need to keep a track of the statuses that we use in `process_tracker`
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
This should not require any testing as the change done is here just a mere replacement of hardcoded string with `const`s. If needed, the changes can be verified by following #3712's instructions. Reproduced below:
Perform PSync call from connector like `Checkout`. Payment Status should go to `processing` state. Wait for `process_tracker` to kick in and do a `force_sync` on its own. Wait for the status to get updated. I had webhooks set up (invalid configuration), even that is verified to be working.
Command used in DB:
```sql
SELECT * FROM process_tracker ORDER BY created_at desc LIMIT 2;
```




## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2852a3ba156e3e2bd89d0a116990134268e7bee8
|
This should not require any testing as the change done is here just a mere replacement of hardcoded string with `const`s. If needed, the changes can be verified by following #3712's instructions. Reproduced below:
Perform PSync call from connector like `Checkout`. Payment Status should go to `processing` state. Wait for `process_tracker` to kick in and do a `force_sync` on its own. Wait for the status to get updated. I had webhooks set up (invalid configuration), even that is verified to be working.
Command used in DB:
```sql
SELECT * FROM process_tracker ORDER BY created_at desc LIMIT 2;
```




|
|
juspay/hyperswitch
|
juspay__hyperswitch-4834
|
Bug: [BUG] 5xx during External Authentication through Netcetera Fails
### Bug Description
In some very rare scenarios, when external authentication fails from netcetera, hyperswitch throws 5xx because of error message deserialization error.
The error object returned by netcetera is inconsistent with their official documentation. Few fields that were marked as required were missing in the actual response. This caused deserialization failure.
### Expected Behavior
Hyperswitch should be retuning appropriate error message instead of throwing 5xx.
### Actual Behavior
Hyperswitch throws 5xx.
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Create a payment by enabling external authentication.
2. Confirm the payment
3. Do auth call.
4. Check if 5xx is thrown.
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/netcetera.rs b/crates/router/src/connector/netcetera.rs
index 43df87db40f..714873cfb53 100644
--- a/crates/router/src/connector/netcetera.rs
+++ b/crates/router/src/connector/netcetera.rs
@@ -107,7 +107,7 @@ impl ConnectorCommon for Netcetera {
status_code: res.status_code,
code: response.error_details.error_code,
message: response.error_details.error_description,
- reason: Some(response.error_details.error_detail),
+ reason: response.error_details.error_detail,
attempt_status: None,
connector_transaction_id: None,
})
diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs
index 25ed7c5271e..9218c2eaf1e 100644
--- a/crates/router/src/connector/netcetera/transformers.rs
+++ b/crates/router/src/connector/netcetera/transformers.rs
@@ -105,8 +105,8 @@ impl
NetceteraPreAuthenticationResponse::Failure(error_response) => {
Err(types::ErrorResponse {
code: error_response.error_details.error_code,
- message: error_response.error_details.error_detail,
- reason: Some(error_response.error_details.error_description),
+ message: error_response.error_details.error_description,
+ reason: error_response.error_details.error_detail,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
@@ -173,8 +173,8 @@ impl
}
NetceteraAuthenticationResponse::Error(error_response) => Err(types::ErrorResponse {
code: error_response.error_details.error_code,
- message: error_response.error_details.error_detail,
- reason: Some(error_response.error_details.error_description),
+ message: error_response.error_details.error_description,
+ reason: error_response.error_details.error_detail,
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: None,
@@ -234,20 +234,20 @@ pub struct NetceteraErrorDetails {
pub error_code: String,
/// Code indicating the 3-D Secure component that identified the error.
- pub error_component: String,
+ pub error_component: Option<String>,
/// Text describing the problem identified.
pub error_description: String,
/// Additional detail regarding the problem identified.
- pub error_detail: String,
+ pub error_detail: Option<String>,
/// Universally unique identifier for the transaction assigned by the 3DS SDK.
#[serde(rename = "sdkTransID")]
pub sdk_trans_id: Option<String>,
/// The Message Type that was identified as erroneous.
- pub error_message_type: String,
+ pub error_message_type: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
|
2024-05-30T13:18:32Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Few fields in netcetera error object that were marked required in the official api documentation were missing in api response body. This caused deserialization failure at hyperswitch.
So made those fields optional.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Manual.
Tested sanity of Netcetera Authentication Connector.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
21a3a2ea8ada838c67b0e5871f01d09bd5a8b9ed
|
Manual.
Tested sanity of Netcetera Authentication Connector.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4840
|
Bug: [FEATURE] [AUTHORIZEDOTNET] Support payment_method_id in recurring mandate payment
### Feature Description
Support `payment_method_id` in recurring mandate payment for connector Authorizedotnet.
### Possible Implementation
Support `payment_method_id` in recurring mandate payment for connector Authorizedotnet.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index b281d0a0a77..15aedad7599 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -1,16 +1,15 @@
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, ValueExt},
- id_type, pii,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret};
+use rand::distributions::{Alphanumeric, DistString};
use serde::{Deserialize, Serialize};
use crate::{
connector::utils::{
- self, missing_field_err, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData,
- WalletData,
+ self, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, WalletData,
},
core::errors,
services,
@@ -179,7 +178,7 @@ struct PaymentProfileDetails {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomerDetails {
- id: id_type::CustomerId,
+ id: String,
}
#[derive(Debug, Serialize)]
@@ -273,10 +272,7 @@ pub struct AuthorizedotnetZeroMandateRequest {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct Profile {
- merchant_customer_id: id_type::CustomerId,
- #[serde(skip_serializing_if = "Option::is_none")]
- description: Option<String>,
- email: Option<pii::Email>,
+ description: String,
payment_profiles: PaymentProfiles,
}
@@ -318,12 +314,8 @@ impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest {
create_customer_profile_request: AuthorizedotnetZeroMandateRequest {
merchant_authentication,
profile: Profile {
- merchant_customer_id: item
- .customer_id
- .clone()
- .ok_or_else(missing_field_err("customer_id"))?,
- description: item.description.clone(),
- email: item.request.email.clone(),
+ //The payment ID is included in the description because the connector requires unique description when creating a mandate.
+ description: item.payment_id.clone(),
payment_profiles: PaymentProfiles {
customer_type: CustomerType::Individual,
payment: PaymentDetails::CreditCard(CreditCardDetails {
@@ -393,16 +385,18 @@ impl<F, T>
response: Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::NoResponseId,
redirection_data: None,
- mandate_reference: item.response.customer_profile_id.map(|mandate_id| {
- types::MandateReference {
- connector_mandate_id: Some(mandate_id),
- payment_method_id: item
+ mandate_reference: item.response.customer_profile_id.map(
+ |customer_profile_id| types::MandateReference {
+ connector_mandate_id: item
.response
.customer_payment_profile_id_list
.first()
- .cloned(),
- }
- }),
+ .map(|payment_profile_id| {
+ format!("{customer_profile_id}-{payment_profile_id}")
+ }),
+ payment_method_id: None,
+ },
+ ),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
@@ -635,27 +629,24 @@ impl
api_models::payments::ConnectorMandateReferenceId,
),
) -> Result<Self, Self::Error> {
+ let mandate_id = connector_mandate_id
+ .connector_mandate_id
+ .ok_or(errors::ConnectorError::MissingConnectorMandateID)?;
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: None,
- profile: Some(ProfileDetails::CustomerProfileDetails(
- CustomerProfileDetails {
- customer_profile_id: Secret::from(
- connector_mandate_id
- .connector_mandate_id
- .ok_or(errors::ConnectorError::MissingConnectorMandateID)?,
- ),
- payment_profile: PaymentProfileDetails {
- payment_profile_id: Secret::from(
- connector_mandate_id
- .payment_method_id
- .ok_or(errors::ConnectorError::MissingConnectorMandateID)?,
- ),
- },
- },
- )),
+ profile: mandate_id
+ .split_once('-')
+ .map(|(customer_profile_id, payment_profile_id)| {
+ ProfileDetails::CustomerProfileDetails(CustomerProfileDetails {
+ customer_profile_id: Secret::from(customer_profile_id.to_string()),
+ payment_profile: PaymentProfileDetails {
+ payment_profile_id: Secret::from(payment_profile_id.to_string()),
+ },
+ })
+ }),
order: Order {
description: item.router_data.connector_request_reference_id.clone(),
},
@@ -709,11 +700,13 @@ impl
create_profile: true,
})),
Some(CustomerDetails {
- id: item
- .router_data
- .customer_id
- .clone()
- .ok_or_else(missing_field_err("customer_id"))?,
+ //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate.
+ //If the length exceeds 20 characters, a random alphanumeric string is used instead.
+ id: if item.router_data.payment_id.len() <= 20 {
+ item.router_data.payment_id.clone()
+ } else {
+ Alphanumeric.sample_string(&mut rand::thread_rng(), 20)
+ },
}),
)
} else {
@@ -1087,6 +1080,24 @@ impl<F, T>
.and_then(|x| x.secure_acceptance_url.to_owned());
let redirection_data =
url.map(|url| services::RedirectForm::from((url, services::Method::Get)));
+ let mandate_reference = item.response.profile_response.map(|profile_response| {
+ let payment_profile_id = profile_response
+ .customer_payment_profile_id_list
+ .and_then(|customer_payment_profile_id_list| {
+ customer_payment_profile_id_list.first().cloned()
+ });
+ types::MandateReference {
+ connector_mandate_id: profile_response.customer_profile_id.and_then(
+ |customer_profile_id| {
+ payment_profile_id.map(|payment_profile_id| {
+ format!("{customer_profile_id}-{payment_profile_id}")
+ })
+ },
+ ),
+ payment_method_id: None,
+ }
+ });
+
Ok(Self {
status,
response: match error {
@@ -1096,16 +1107,7 @@ impl<F, T>
transaction_response.transaction_id.clone(),
),
redirection_data,
- mandate_reference: item.response.profile_response.map(
- |profile_response| types::MandateReference {
- connector_mandate_id: profile_response.customer_profile_id,
- payment_method_id: profile_response
- .customer_payment_profile_id_list
- .and_then(|customer_payment_profile_id_list| {
- customer_payment_profile_id_list.first().cloned()
- }),
- },
- ),
+ mandate_reference,
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
|
2024-05-31T12:00:38Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Support `payment_method_id` in recurring mandate payment for connector Authorizedotnet.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4840
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Payment Intent Create (Zero):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_8aib7npeItergz3tpMqm1iqsMXrAdiw8VjVdjiVUWLMUSRWR34DrRDGJPmy2mcMm' \
--data '{
"amount": 0,
"currency": "USD",
"confirm": false,
"customer_id": "tester799"
}'
```
Response:
```
{
"payment_id": "pay_hduDivSEknVCYLL3ekxX",
"merchant_id": "merchant_1717157151",
"status": "requires_payment_method",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "API_KEY_HERE",
"created": "2024-06-03T09:25:42.690Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": null,
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester799",
"created_at": 1717406742,
"expires": 1717410342,
"secret": "epk_6d3c1f24d50e48ebb08373224ef23d5a"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:40:42.690Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-06-03T09:25:42.781Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Confirm (Zero):
Request:
```
curl --location 'http://localhost:8080/payments/pay_jKXxp9HeQV41lRZW4TsV/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"setup_future_usage": "off_session",
"payment_method": "card",
"payment_method_type": "credit",
"payment_type": "setup_mandate",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "offline"
}
}'
```
Response:
```
{
"payment_id": "pay_hduDivSEknVCYLL3ekxX",
"merchant_id": "merchant_1717157151",
"status": "succeeded",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "pay_hduDivSEknVCYLL3ekxX_secret_iJjHlRGKZhNU4XJto9AD",
"created": "2024-06-03T09:25:42.690Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:40:42.690Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_D0ahV0rd04bLhjjYrV2I",
"payment_method_status": null,
"updated": "2024-06-03T09:28:35.781Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Intent Create (Non-Zero):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 370,
"currency": "USD",
"confirm": false,
"customer_id": "tester799"
}'
```
Response:
```
{
"payment_id": "pay_ZBSRCNSVIqDtDcw6IsUz",
"merchant_id": "merchant_1717157151",
"status": "requires_payment_method",
"amount": 370,
"net_amount": 370,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_ZBSRCNSVIqDtDcw6IsUz_secret_uZouNfEDWSG1goR8XmeG",
"created": "2024-06-03T09:27:07.982Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": null,
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester799",
"created_at": 1717406827,
"expires": 1717410427,
"secret": "epk_9301e21e18a54abe870465212fee94d2"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:42:07.982Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-06-03T09:27:08.012Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Confirm (Non-Zero):
Request:
```
curl --location 'http://localhost:8080/payments/pay_ZBSRCNSVIqDtDcw6IsUz/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"setup_future_usage": "off_session",
"payment_method": "card",
"payment_method_type": "credit",
"payment_type": "setup_mandate",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "offline"
}
}'
```
Response:
```
{
"payment_id": "pay_ZBSRCNSVIqDtDcw6IsUz",
"merchant_id": "merchant_1717157151",
"status": "succeeded",
"amount": 370,
"net_amount": 370,
"amount_capturable": 370,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "pay_ZBSRCNSVIqDtDcw6IsUz_secret_uZouNfEDWSG1goR8XmeG",
"created": "2024-06-03T09:27:07.982Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:42:07.982Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_KOptxkOcyGWIly77GCiQ",
"payment_method_status": null,
"updated": "2024-06-03T09:29:35.382Z",
"charges": null,
"frm_metadata": null
}
```
- Payments Create - Using payment_method_id:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 400,
"currency": "USD",
"confirm": true,
"customer_id": "tester799",
"recurring_details": {
"type": "payment_method_id",
"data": "pm_D0ahV0rd04bLhjjYrV2I"
},
"off_session": true
}'
```
Response:
```
{
"payment_id": "pay_3Z93A6rW7b2qOUHxED2H",
"merchant_id": "merchant_1717157151",
"status": "succeeded",
"amount": 400,
"net_amount": 400,
"amount_capturable": 0,
"amount_received": 400,
"connector": "authorizedotnet",
"client_secret": "pay_3Z93A6rW7b2qOUHxED2H_secret_BonNTHUTARbIb2QiWN2o",
"created": "2024-06-03T09:32:47.521Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester799",
"created_at": 1717407167,
"expires": 1717410767,
"secret": "epk_bf0885fc144047dcb5dad7a35be92057"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80019529820",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80019529820",
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:47:47.521Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_D0ahV0rd04bLhjjYrV2I",
"payment_method_status": "active",
"updated": "2024-06-03T09:32:48.396Z",
"charges": null,
"frm_metadata": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
865007717c5c7e617ca1b447ea5f9bb3d274cac3
|
- Payment Intent Create (Zero):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_8aib7npeItergz3tpMqm1iqsMXrAdiw8VjVdjiVUWLMUSRWR34DrRDGJPmy2mcMm' \
--data '{
"amount": 0,
"currency": "USD",
"confirm": false,
"customer_id": "tester799"
}'
```
Response:
```
{
"payment_id": "pay_hduDivSEknVCYLL3ekxX",
"merchant_id": "merchant_1717157151",
"status": "requires_payment_method",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "API_KEY_HERE",
"created": "2024-06-03T09:25:42.690Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": null,
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester799",
"created_at": 1717406742,
"expires": 1717410342,
"secret": "epk_6d3c1f24d50e48ebb08373224ef23d5a"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:40:42.690Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-06-03T09:25:42.781Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Confirm (Zero):
Request:
```
curl --location 'http://localhost:8080/payments/pay_jKXxp9HeQV41lRZW4TsV/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"setup_future_usage": "off_session",
"payment_method": "card",
"payment_method_type": "credit",
"payment_type": "setup_mandate",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "offline"
}
}'
```
Response:
```
{
"payment_id": "pay_hduDivSEknVCYLL3ekxX",
"merchant_id": "merchant_1717157151",
"status": "succeeded",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "pay_hduDivSEknVCYLL3ekxX_secret_iJjHlRGKZhNU4XJto9AD",
"created": "2024-06-03T09:25:42.690Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:40:42.690Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_D0ahV0rd04bLhjjYrV2I",
"payment_method_status": null,
"updated": "2024-06-03T09:28:35.781Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Intent Create (Non-Zero):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 370,
"currency": "USD",
"confirm": false,
"customer_id": "tester799"
}'
```
Response:
```
{
"payment_id": "pay_ZBSRCNSVIqDtDcw6IsUz",
"merchant_id": "merchant_1717157151",
"status": "requires_payment_method",
"amount": 370,
"net_amount": 370,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_ZBSRCNSVIqDtDcw6IsUz_secret_uZouNfEDWSG1goR8XmeG",
"created": "2024-06-03T09:27:07.982Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": null,
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester799",
"created_at": 1717406827,
"expires": 1717410427,
"secret": "epk_9301e21e18a54abe870465212fee94d2"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:42:07.982Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-06-03T09:27:08.012Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Confirm (Non-Zero):
Request:
```
curl --location 'http://localhost:8080/payments/pay_ZBSRCNSVIqDtDcw6IsUz/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"setup_future_usage": "off_session",
"payment_method": "card",
"payment_method_type": "credit",
"payment_type": "setup_mandate",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "offline"
}
}'
```
Response:
```
{
"payment_id": "pay_ZBSRCNSVIqDtDcw6IsUz",
"merchant_id": "merchant_1717157151",
"status": "succeeded",
"amount": 370,
"net_amount": 370,
"amount_capturable": 370,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "pay_ZBSRCNSVIqDtDcw6IsUz_secret_uZouNfEDWSG1goR8XmeG",
"created": "2024-06-03T09:27:07.982Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:42:07.982Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_KOptxkOcyGWIly77GCiQ",
"payment_method_status": null,
"updated": "2024-06-03T09:29:35.382Z",
"charges": null,
"frm_metadata": null
}
```
- Payments Create - Using payment_method_id:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 400,
"currency": "USD",
"confirm": true,
"customer_id": "tester799",
"recurring_details": {
"type": "payment_method_id",
"data": "pm_D0ahV0rd04bLhjjYrV2I"
},
"off_session": true
}'
```
Response:
```
{
"payment_id": "pay_3Z93A6rW7b2qOUHxED2H",
"merchant_id": "merchant_1717157151",
"status": "succeeded",
"amount": 400,
"net_amount": 400,
"amount_capturable": 0,
"amount_received": 400,
"connector": "authorizedotnet",
"client_secret": "pay_3Z93A6rW7b2qOUHxED2H_secret_BonNTHUTARbIb2QiWN2o",
"created": "2024-06-03T09:32:47.521Z",
"currency": "USD",
"customer_id": "tester799",
"customer": {
"id": "tester799",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester799",
"created_at": 1717407167,
"expires": 1717410767,
"secret": "epk_bf0885fc144047dcb5dad7a35be92057"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80019529820",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80019529820",
"payment_link": null,
"profile_id": "pro_lxWuQ5I3AgeVdF3GLB03",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_F6pucFwthqPFPERwAhf8",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-06-03T09:47:47.521Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_D0ahV0rd04bLhjjYrV2I",
"payment_method_status": "active",
"updated": "2024-06-03T09:32:48.396Z",
"charges": null,
"frm_metadata": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4824
|
Bug: [BUG] FIx routing field validation in payments request
### Feature Description
As of now, routing field in the payments request wasn't being validated, have to add validations for the same
### Possible Implementation
Jus have to add validations in payments create, update and confirm
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index a3ed16def0c..b8b3ea3a971 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1336,6 +1336,16 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir
.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 {
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 68f8b7056c0..1a0e27a7d68 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -735,6 +735,16 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate
)?;
}
+ 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 {
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index d7351b3b5ba..a671a6b5596 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -782,6 +782,16 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate
&request.mandate_id,
)?;
+ 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 {
|
2024-05-24T11:54:21Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added validation for straight through routing in payments request
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. By using invalid req body for `routing` field (4xx should be thrown instead of 5xx)
```
curl --location --request POST 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_wnIRnsZGiq0NHNq3WskWv4Kw7Eg7InEHASiXrAXA4zM2MoJMvL2fCMDWNt8Ieg5I' \
--data-raw '{
"amount": 200,
"currency": "EUR",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer1",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"routing":{
"type": "single",
"data": {"connector": "strip", "merchant_connector_id": "mca_123"}
},
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "2025",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response -
```
{
"error": {
"type": "invalid_request",
"message": "Invalid straight through routing rules format",
"code": "IR_06"
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] - [ ]
|
e41d5e25dfd4d3113edac11b249e847f8718b263
|
1. By using invalid req body for `routing` field (4xx should be thrown instead of 5xx)
```
curl --location --request POST 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_wnIRnsZGiq0NHNq3WskWv4Kw7Eg7InEHASiXrAXA4zM2MoJMvL2fCMDWNt8Ieg5I' \
--data-raw '{
"amount": 200,
"currency": "EUR",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "StripeCustomer1",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"routing":{
"type": "single",
"data": {"connector": "strip", "merchant_connector_id": "mca_123"}
},
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "2025",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response -
```
{
"error": {
"type": "invalid_request",
"message": "Invalid straight through routing rules format",
"code": "IR_06"
}
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4820
|
Bug: feat(users): add endpoint to reset totp
Add support to reset TOTP from dashboard!
|
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 7b6e8ebd365..9931d450ab9 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1634,7 +1634,39 @@ pub async fn begin_totp(
let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?;
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: AppState,
+ user_token: auth::UserFromToken,
+) -> UserResponse<user_api::BeginTotpResponse> {
+ let user_from_db: domain::UserFromStorage = state
+ .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)?;
+ 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 {
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index b38479cd2b6..6d790d81873 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1217,6 +1217,7 @@ impl User {
.service(
web::scope("/totp")
.service(web::resource("/begin").route(web::get().to(totp_begin)))
+ .service(web::resource("/reset").route(web::get().to(totp_reset)))
.service(
web::resource("/verify")
.route(web::post().to(totp_verify))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9e53eb35473..ee466a7e09a 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -214,6 +214,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::VerifyEmailRequest
| Flow::UpdateUserAccountDetails
| Flow::TotpBegin
+ | Flow::TotpReset
| Flow::TotpVerify
| Flow::TotpUpdate
| Flow::RecoveryCodeVerify
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 5ba7ec8da25..6b73ea03b62 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -648,6 +648,20 @@ pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpRes
.await
}
+pub async fn totp_reset(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::TotpReset;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| user_core::reset_totp(state, user),
+ &auth::DashboardNoPermissionAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn totp_verify(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 1bfc20ff1ca..ddbc64e81f8 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -404,6 +404,8 @@ pub enum Flow {
UserFromEmail,
/// Begin TOTP
TotpBegin,
+ // Reset TOTP
+ TotpReset,
/// Verify TOTP
TotpVerify,
/// Update TOTP secret
|
2024-05-30T08:43:41Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Add support to reset TOTP
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#4820](https://github.com/juspay/hyperswitch/issues/4820)
## How did you test it?
Use the curl to reset TOTP when it is already setup (from inside dashboard):
```
curl --location 'http://localhost:8080/user/2fa/totp/reset' \
--header 'Authorization: Bearer JWT' \
--header 'Cookie: Cookie_1=value'
```
Response:
```
{
"secret": {
"secret": "VERUDBNHLYZDGFTKNXY2VVP4EQ5GOBUB",
"totp_url": "otpauth://totp/Hyperswitch:ver%40gmail.com?secret=VERUDBNHLYZDGFTKNXY2VVP4EQ5GOBUB&issuer=Hyperswitch"
}
}
```
The Response can be used to generate new QR and reset TOTP.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
bed42ce4be901f2b8f46033dd395dee8dbe807c9
|
Use the curl to reset TOTP when it is already setup (from inside dashboard):
```
curl --location 'http://localhost:8080/user/2fa/totp/reset' \
--header 'Authorization: Bearer JWT' \
--header 'Cookie: Cookie_1=value'
```
Response:
```
{
"secret": {
"secret": "VERUDBNHLYZDGFTKNXY2VVP4EQ5GOBUB",
"totp_url": "otpauth://totp/Hyperswitch:ver%40gmail.com?secret=VERUDBNHLYZDGFTKNXY2VVP4EQ5GOBUB&issuer=Hyperswitch"
}
}
```
The Response can be used to generate new QR and reset TOTP.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4829
|
Bug: feat: Add new auth type to allow both SPTs and Login Tokens for 2FA APIs
The following APIs are needed in both with Sign In and in the dashboard.
- `/2fa/totp/verify`
- `/2fa/recovery_code/verify`
- `/2fa/recovery_code/generate`
Currently these APIs use SPT as auth, which makes them unable to access using Login Tokens.
We need a new Auth type which allows us to do this.
|
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index c7615aa4be4..331c256e8a4 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -18,4 +18,4 @@ pub const MIN_PASSWORD_LENGTH: usize = 8;
pub const REDIS_TOTP_PREFIX: &str = "TOTP_";
pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_";
pub const REDIS_TOTP_SECRET_PREFIX: &str = "TOTP_SEC_";
-pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 5 * 60; // 5 minutes
+pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 15 * 60; // 15 minutes
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 69a4cfc8a61..cfc01afb91b 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1237,11 +1237,11 @@ pub async fn create_merchant_account(
pub async fn list_merchants_for_user(
state: SessionState,
- user_from_token: Box<dyn auth::GetUserIdFromAuth>,
+ user_from_token: auth::UserIdFromAuth,
) -> UserResponse<Vec<user_api::UserMerchantAccount>> {
let user_roles = state
.store
- .list_user_roles_by_user_id(user_from_token.get_user_id().as_str())
+ .list_user_roles_by_user_id(user_from_token.user_id.as_str())
.await
.change_context(UserErrors::InternalServerError)?;
@@ -1697,7 +1697,7 @@ pub async fn reset_totp(
pub async fn verify_totp(
state: SessionState,
- user_token: auth::UserFromSinglePurposeToken,
+ user_token: auth::UserIdFromAuth,
req: user_api::VerifyTotpRequest,
) -> UserResponse<user_api::TokenResponse> {
let user_from_db: domain::UserFromStorage = state
@@ -1737,7 +1737,7 @@ pub async fn verify_totp(
pub async fn update_totp(
state: SessionState,
- user_token: auth::UserFromSinglePurposeToken,
+ user_token: auth::UserIdFromAuth,
req: user_api::VerifyTotpRequest,
) -> UserResponse<()> {
let user_from_db: domain::UserFromStorage = state
@@ -1806,7 +1806,7 @@ pub async fn update_totp(
pub async fn generate_recovery_codes(
state: SessionState,
- user_token: auth::UserFromSinglePurposeToken,
+ 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());
@@ -1838,7 +1838,7 @@ pub async fn generate_recovery_codes(
pub async fn verify_recovery_code(
state: SessionState,
- user_token: auth::UserFromSinglePurposeToken,
+ user_token: auth::UserIdFromAuth,
req: user_api::VerifyRecoveryCodeRequest,
) -> UserResponse<user_api::TokenResponse> {
let user_from_db: domain::UserFromStorage = state
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 5af3a2bef25..457e232ebd1 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1316,7 +1316,7 @@ impl User {
// The route is utilized to select an invitation from a list of merchants in an intermediate state
.service(
web::resource("/merchants_select/list")
- .route(web::get().to(list_merchants_for_user_with_spt)),
+ .route(web::get().to(list_merchants_for_user)),
)
.service(web::resource("/permission_info").route(web::get().to(get_authorization_info)))
.service(web::resource("/update").route(web::post().to(update_user_account_details)))
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index e5cc7e4e294..5325cbe437b 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -318,24 +318,7 @@ pub async fn list_merchants_for_user(state: web::Data<AppState>, req: HttpReques
&req,
(),
|state, user, _, _| user_core::list_merchants_for_user(state, user),
- &auth::DashboardNoPermissionAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
-pub async fn list_merchants_for_user_with_spt(
- state: web::Data<AppState>,
- req: HttpRequest,
-) -> HttpResponse {
- let flow = Flow::UserMerchantAccountList;
- Box::pin(api::server_wrap(
- flow,
- state,
- &req,
- (),
- |state, user, _, _| user_core::list_merchants_for_user(state, user),
- &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
+ &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::AcceptInvite),
api_locking::LockAction::NotApplicable,
))
.await
@@ -674,7 +657,7 @@ pub async fn totp_verify(
&req,
json_payload.into_inner(),
|state, user, req_body, _| user_core::verify_totp(state, user, req_body),
- &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
+ &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
@@ -692,7 +675,7 @@ pub async fn verify_recovery_code(
&req,
json_payload.into_inner(),
|state, user, req_body, _| user_core::verify_recovery_code(state, user, req_body),
- &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
+ &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
@@ -710,7 +693,7 @@ pub async fn totp_update(
&req,
json_payload.into_inner(),
|state, user, req_body, _| user_core::update_totp(state, user, req_body),
- &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
+ &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
@@ -724,7 +707,7 @@ pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpReques
&req,
(),
|state, user, _, _| user_core::generate_recovery_codes(state, user),
- &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
+ &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 28f9ccd1a77..72d0860eed9 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -64,10 +64,15 @@ pub enum AuthenticationType {
UserJwt {
user_id: String,
},
- SinglePurposeJWT {
+ SinglePurposeJwt {
user_id: String,
purpose: TokenPurpose,
},
+ SinglePurposeOrLoginJwt {
+ user_id: String,
+ purpose: Option<TokenPurpose>,
+ role_id: Option<String>,
+ },
MerchantId {
merchant_id: String,
},
@@ -107,7 +112,8 @@ impl AuthenticationType {
| Self::WebhookAuth { merchant_id } => Some(merchant_id.as_ref()),
Self::AdminApiKey
| Self::UserJwt { .. }
- | Self::SinglePurposeJWT { .. }
+ | Self::SinglePurposeJwt { .. }
+ | Self::SinglePurposeOrLoginJwt { .. }
| Self::NoAuth => None,
}
}
@@ -189,6 +195,19 @@ pub struct UserFromToken {
pub org_id: String,
}
+pub struct UserIdFromAuth {
+ pub user_id: String,
+}
+
+#[cfg(feature = "olap")]
+#[derive(serde::Serialize, serde::Deserialize)]
+pub struct SinglePurposeOrLoginToken {
+ pub user_id: String,
+ pub role_id: Option<String>,
+ pub purpose: Option<TokenPurpose>,
+ pub exp: u64,
+}
+
pub trait AuthInfo {
fn get_merchant_id(&self) -> Option<&str>;
}
@@ -205,23 +224,6 @@ impl AuthInfo for AuthenticationData {
}
}
-pub trait GetUserIdFromAuth {
- fn get_user_id(&self) -> String;
-}
-
-impl GetUserIdFromAuth for UserFromToken {
- fn get_user_id(&self) -> String {
- self.user_id.clone()
- }
-}
-
-#[cfg(feature = "olap")]
-impl GetUserIdFromAuth for UserFromSinglePurposeToken {
- fn get_user_id(&self) -> String {
- self.user_id.clone()
- }
-}
-
#[async_trait]
pub trait AuthenticateAndFetch<T, A>
where
@@ -355,7 +357,7 @@ where
user_id: payload.user_id.clone(),
origin: payload.origin.clone(),
},
- AuthenticationType::SinglePurposeJWT {
+ AuthenticationType::SinglePurposeJwt {
user_id: payload.user_id,
purpose: payload.purpose,
},
@@ -363,9 +365,13 @@ where
}
}
+#[cfg(feature = "olap")]
+#[derive(Debug)]
+pub struct SinglePurposeOrLoginTokenAuth(pub TokenPurpose);
+
#[cfg(feature = "olap")]
#[async_trait]
-impl<A> AuthenticateAndFetch<Box<dyn GetUserIdFromAuth>, A> for SinglePurposeJWTAuth
+impl<A> AuthenticateAndFetch<UserIdFromAuth, A> for SinglePurposeOrLoginTokenAuth
where
A: SessionStateInfo + Sync,
{
@@ -373,26 +379,35 @@ where
&self,
request_headers: &HeaderMap,
state: &A,
- ) -> RouterResult<(Box<dyn GetUserIdFromAuth>, AuthenticationType)> {
- let payload = parse_jwt_payload::<A, SinglePurposeToken>(request_headers, state).await?;
+ ) -> RouterResult<(UserIdFromAuth, AuthenticationType)> {
+ let payload =
+ parse_jwt_payload::<A, SinglePurposeOrLoginToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
- if self.0 != payload.purpose {
- return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
- }
+ let is_purpose_equal = payload
+ .purpose
+ .as_ref()
+ .is_some_and(|purpose| purpose == &self.0);
- Ok((
- Box::new(UserFromSinglePurposeToken {
- user_id: payload.user_id.clone(),
- origin: payload.origin.clone(),
- }),
- AuthenticationType::SinglePurposeJWT {
- user_id: payload.user_id,
- purpose: payload.purpose,
- },
- ))
+ let purpose_exists = payload.purpose.is_some();
+ let role_id_exists = payload.role_id.is_some();
+
+ if is_purpose_equal && !role_id_exists || role_id_exists && !purpose_exists {
+ Ok((
+ UserIdFromAuth {
+ user_id: payload.user_id.clone(),
+ },
+ AuthenticationType::SinglePurposeOrLoginJwt {
+ user_id: payload.user_id,
+ purpose: payload.purpose,
+ role_id: payload.role_id,
+ },
+ ))
+ } else {
+ Err(errors::ApiErrorResponse::InvalidJwtToken.into())
+ }
}
}
@@ -864,37 +879,6 @@ where
}
}
-#[cfg(feature = "olap")]
-#[async_trait]
-impl<A> AuthenticateAndFetch<Box<dyn GetUserIdFromAuth>, A> for DashboardNoPermissionAuth
-where
- A: SessionStateInfo + Sync,
-{
- async fn authenticate_and_fetch(
- &self,
- request_headers: &HeaderMap,
- state: &A,
- ) -> RouterResult<(Box<dyn GetUserIdFromAuth>, AuthenticationType)> {
- let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if payload.check_in_blacklist(state).await? {
- return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
- }
-
- Ok((
- Box::new(UserFromToken {
- user_id: payload.user_id.clone(),
- merchant_id: payload.merchant_id.clone(),
- org_id: payload.org_id,
- role_id: payload.role_id,
- }),
- AuthenticationType::MerchantJwt {
- merchant_id: payload.merchant_id,
- user_id: Some(payload.user_id),
- },
- ))
- }
-}
-
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for DashboardNoPermissionAuth
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index 8a3aefd8fc0..0ac8c419ef6 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -7,7 +7,7 @@ use redis_interface::RedisConnectionPool;
use super::AuthToken;
#[cfg(feature = "olap")]
-use super::SinglePurposeToken;
+use super::{SinglePurposeOrLoginToken, SinglePurposeToken};
#[cfg(feature = "email")]
use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS};
use crate::{
@@ -166,3 +166,14 @@ impl BlackList for SinglePurposeToken {
check_user_in_blacklist(state, &self.user_id, self.exp).await
}
}
+
+#[cfg(feature = "olap")]
+#[async_trait::async_trait]
+impl BlackList for SinglePurposeOrLoginToken {
+ async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
+ where
+ A: SessionStateInfo + Sync,
+ {
+ check_user_in_blacklist(state, &self.user_id, self.exp).await
+ }
+}
|
2024-05-30T14:55:01Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR adds new auth type `SinglePurposeOrLoginTokenAuth`, which will allow both SPTs and Login Tokens to be used as auth token for APIs.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #4829.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Verify TOTP
```
curl --location 'http://localhost:8080/user/2fa/totp/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with purpose as TOTP' \
--data '{
"totp": "597760"
}'
```
```
curl --location 'http://localhost:8080/user/2fa/totp/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer Login Token' \
--data '{
"totp": "597760"
}'
```
In both the cases this API should give 200 OK.
2. Verify Recovery Code
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with purpose as TOTP' \
--data '{
"recovery_code": "recovery_code"
}'
```
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer Login Token' \
--data '{
"recovery_code": "recovery_code"
}'
```
In both the cases this API should give 200 OK.
3. Generate Recovery Codes
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \
--header 'Authorization: Bearer SPT with purpose as TOTP' \
```
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \
--header 'Authorization: Bearer Login Token' \
```
In both the cases, API should respond like this
```
{
"recovery_codes": [
"w5fM-NLm0",
"TumH-oyXE",
"wDIr-zEmu",
"HZjm-e16M",
"Q4qB-MupL",
"5BtN-vRuY",
"4vG6-URGf",
"Dbq8-n5V1"
]
}
```
4. Merchant select List
```
curl --location 'http://localhost:8080/user/merchants_select/list' \
--header 'Authorization: Bearer SPT with Purpose as AcceptInvite'
```
```
curl --location 'http://localhost:8080/user/merchants_select/list' \
--header 'Authorization: Bearer Login Token'
```
In both the cases, API should respond like this
```
[
{
"merchant_id": "merchant_1681110944832",
"merchant_name": "sdjkfl",
"is_active": true,
"role_id": "merchant_admin",
"role_name": "admin",
"org_id": "org_LoNX0cc4lNZVgJrPV65QY"
},
{
"merchant_id": "merchant_1704717001",
"merchant_name": null,
"is_active": true,
"role_id": "merchant_customer_support",
"role_name": "customer_support",
"org_id": "org_7yULICVqnwmSX5PgW5zK"
}
]
```
5. Switch List
```
curl --location 'http://localhost:8080/user/switch/list' \
--header 'Authorization: Bearer SPT with Purpose as AcceptInvite'
```
```
curl --location 'http://localhost:8080/user/switch/list' \
--header 'Authorization: Bearer Login Token'
```
In both the cases, API should respond like this
```
[
{
"merchant_id": "merchant_1681110944832",
"merchant_name": "sdjkfl",
"is_active": true,
"role_id": "merchant_admin",
"role_name": "admin",
"org_id": "org_LoNX0cc4lNZVgJrPV65QY"
},
{
"merchant_id": "merchant_1704717001",
"merchant_name": null,
"is_active": true,
"role_id": "merchant_customer_support",
"role_name": "customer_support",
"org_id": "org_7yULICVqnwmSX5PgW5zK"
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ba0a1e95b72c0acf5bde81d424aa8fe220c40a22
|
1. Verify TOTP
```
curl --location 'http://localhost:8080/user/2fa/totp/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with purpose as TOTP' \
--data '{
"totp": "597760"
}'
```
```
curl --location 'http://localhost:8080/user/2fa/totp/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer Login Token' \
--data '{
"totp": "597760"
}'
```
In both the cases this API should give 200 OK.
2. Verify Recovery Code
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with purpose as TOTP' \
--data '{
"recovery_code": "recovery_code"
}'
```
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer Login Token' \
--data '{
"recovery_code": "recovery_code"
}'
```
In both the cases this API should give 200 OK.
3. Generate Recovery Codes
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \
--header 'Authorization: Bearer SPT with purpose as TOTP' \
```
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \
--header 'Authorization: Bearer Login Token' \
```
In both the cases, API should respond like this
```
{
"recovery_codes": [
"w5fM-NLm0",
"TumH-oyXE",
"wDIr-zEmu",
"HZjm-e16M",
"Q4qB-MupL",
"5BtN-vRuY",
"4vG6-URGf",
"Dbq8-n5V1"
]
}
```
4. Merchant select List
```
curl --location 'http://localhost:8080/user/merchants_select/list' \
--header 'Authorization: Bearer SPT with Purpose as AcceptInvite'
```
```
curl --location 'http://localhost:8080/user/merchants_select/list' \
--header 'Authorization: Bearer Login Token'
```
In both the cases, API should respond like this
```
[
{
"merchant_id": "merchant_1681110944832",
"merchant_name": "sdjkfl",
"is_active": true,
"role_id": "merchant_admin",
"role_name": "admin",
"org_id": "org_LoNX0cc4lNZVgJrPV65QY"
},
{
"merchant_id": "merchant_1704717001",
"merchant_name": null,
"is_active": true,
"role_id": "merchant_customer_support",
"role_name": "customer_support",
"org_id": "org_7yULICVqnwmSX5PgW5zK"
}
]
```
5. Switch List
```
curl --location 'http://localhost:8080/user/switch/list' \
--header 'Authorization: Bearer SPT with Purpose as AcceptInvite'
```
```
curl --location 'http://localhost:8080/user/switch/list' \
--header 'Authorization: Bearer Login Token'
```
In both the cases, API should respond like this
```
[
{
"merchant_id": "merchant_1681110944832",
"merchant_name": "sdjkfl",
"is_active": true,
"role_id": "merchant_admin",
"role_name": "admin",
"org_id": "org_LoNX0cc4lNZVgJrPV65QY"
},
{
"merchant_id": "merchant_1704717001",
"merchant_name": null,
"is_active": true,
"role_id": "merchant_customer_support",
"role_name": "customer_support",
"org_id": "org_7yULICVqnwmSX5PgW5zK"
}
]
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4812
|
Bug: [CHORE] : [Paypal] Add session_token flow for Paypal sdk and update the wasm
### Feature Description
- Change payment_experience for paypal via paypal to sdk
- update the wasm
### Possible Implementation
- update wasm config for paypal
https://github.com/juspay/hyperswitch/pull/4697
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index 94cc06786aa..87d1e3e810b 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -63,6 +63,36 @@ impl DashboardRequestPayload {
},
}
}
+
+ pub fn transform_paypal_payment_method(
+ providers: Vec<Provider>,
+ ) -> Vec<payment_methods::RequestPaymentMethodTypes> {
+ let payment_experiences = [
+ api_models::enums::PaymentExperience::RedirectToUrl,
+ api_models::enums::PaymentExperience::InvokeSdkClient,
+ ];
+
+ let mut payment_method_types = Vec::new();
+
+ for experience in payment_experiences {
+ for provider in &providers {
+ let data = payment_methods::RequestPaymentMethodTypes {
+ payment_method_type: provider.payment_method_type,
+ card_networks: None,
+ minimum_amount: Some(0),
+ maximum_amount: Some(68607706),
+ recurring_enabled: true,
+ installment_payment_enabled: false,
+ accepted_currencies: provider.accepted_currencies.clone(),
+ accepted_countries: provider.accepted_countries.clone(),
+ payment_experience: Some(experience),
+ };
+ payment_method_types.push(data);
+ }
+ }
+
+ payment_method_types
+ }
pub fn transform_payment_method(
connector: Connector,
provider: Vec<Provider>,
@@ -125,8 +155,37 @@ impl DashboardRequestPayload {
}
}
- PaymentMethod::Wallet
- | PaymentMethod::BankRedirect
+ PaymentMethod::Wallet => match request.connector {
+ Connector::Paypal => {
+ if let Some(provider) = payload.provider {
+ let val = Self::transform_paypal_payment_method(provider);
+ if !val.is_empty() {
+ let methods = PaymentMethodsEnabled {
+ payment_method: payload.payment_method,
+ payment_method_types: Some(val),
+ };
+ payment_method_enabled.push(methods);
+ }
+ }
+ }
+ _ => {
+ if let Some(provider) = payload.provider {
+ let val = Self::transform_payment_method(
+ request.connector,
+ provider,
+ payload.payment_method,
+ );
+ if !val.is_empty() {
+ let methods = PaymentMethodsEnabled {
+ payment_method: payload.payment_method,
+ payment_method_types: Some(val),
+ };
+ payment_method_enabled.push(methods);
+ }
+ }
+ }
+ },
+ PaymentMethod::BankRedirect
| PaymentMethod::PayLater
| PaymentMethod::BankTransfer
| PaymentMethod::Crypto
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index c3ee6dfb0ad..138fef0cdf3 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1650,9 +1650,9 @@ merchant_secret="Source verification key"
client_id="Client ID"
[paypal_payout]
-[[paypal.wallet]]
+[[paypal_payout.wallet]]
payment_method_type = "paypal"
-[[paypal.wallet]]
+[[paypal_payout.wallet]]
payment_method_type = "venmo"
[paypal_payout.connector_auth.BodyKey]
api_key="Client Secret"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 86183ae7f6f..7236863745d 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -1650,9 +1650,9 @@ merchant_secret="Source verification key"
client_id="Client ID"
[paypal_payout]
-[[paypal.wallet]]
+[[paypal_payout.wallet]]
payment_method_type = "paypal"
-[[paypal.wallet]]
+[[paypal_payout.wallet]]
payment_method_type = "venmo"
[paypal_payout.connector_auth.BodyKey]
api_key="Client Secret"
|
2024-05-29T11:14:21Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Allow Paypal Wallet to have both payment_experiences RedirectToUrl and InvokeSdkClient
<img width="952" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/f7eb2488-bbe2-4e50-bfbd-1d7e3b1dc6ca">
Dashboard Request Payload
<img width="1374" alt="image" src="https://github.com/juspay/hyperswitch/assets/120017870/73c30b9f-f8ce-45a2-9252-0781829951d5">
Reference PR https://github.com/juspay/hyperswitch/pull/4697
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7888dd48b2f3da7d3f867369331accee624f2b39
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4809
|
Bug: feat(users): add support to check 2FA status
Add support to check whether the 2FA has been done recently or not. ( For now it will check for last five minutes)
Use case: The api will help to check for when was last TOTP done, if user has recently done sign in and trying to do some operation that asks for TOTP again from inside dashboard, we can ignore TOTP based on the result this api gives.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index a472b3a76e6..c41f52a93ea 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -16,8 +16,9 @@ use crate::user::{
GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest,
RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest,
SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
- TokenOrPayloadResponse, TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest,
- UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
+ TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse,
+ UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest,
+ VerifyRecoveryCodeRequest, VerifyTotpRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -73,6 +74,7 @@ common_utils::impl_misc_api_event_type!(
GetUserRoleDetailsRequest,
GetUserRoleDetailsResponse,
TokenResponse,
+ TwoFactorAuthStatusResponse,
UserFromEmailRequest,
BeginTotpResponse,
VerifyRecoveryCodeRequest,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 0c8678d2ef8..ee9498cfeee 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -235,6 +235,12 @@ pub struct TokenResponse {
pub token_type: TokenPurpose,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TwoFactorAuthStatusResponse {
+ pub totp: bool,
+ pub recovery_code: bool,
+}
+
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum TokenOrPayloadResponse<T> {
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 7b6e8ebd365..0da381bd493 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1874,3 +1874,16 @@ pub async fn terminate_two_factor_auth(
token,
)
}
+
+pub async fn check_two_factor_auth_status(
+ state: AppState,
+ 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?,
+ },
+ ))
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index b38479cd2b6..141e9f53af4 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1214,6 +1214,7 @@ impl User {
// Two factor auth routes
route = route.service(
web::scope("/2fa")
+ .service(web::resource("").route(web::get().to(check_two_factor_auth_status)))
.service(
web::scope("/totp")
.service(web::resource("/begin").route(web::get().to(totp_begin)))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9e53eb35473..417a4360c51 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -218,7 +218,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::TotpUpdate
| Flow::RecoveryCodeVerify
| Flow::RecoveryCodesGenerate
- | Flow::TerminateTwoFactorAuth => Self::User,
+ | Flow::TerminateTwoFactorAuth
+ | Flow::TwoFactorAuthStatus => Self::User,
Flow::ListRoles
| Flow::GetRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 5ba7ec8da25..f22e4aac521 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -735,3 +735,20 @@ pub async fn terminate_two_factor_auth(
))
.await
}
+
+pub async fn check_two_factor_auth_status(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::TwoFactorAuthStatus;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| user_core::check_two_factor_auth_status(state, user),
+ &auth::DashboardNoPermissionAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 1bfc20ff1ca..728f2ed206e 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -414,6 +414,8 @@ pub enum Flow {
RecoveryCodesGenerate,
// Terminate two factor authentication
TerminateTwoFactorAuth,
+ // Check 2FA status
+ TwoFactorAuthStatus,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
2024-05-29T11:10:35Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
The api checks whether the 2FA has been done recently or not.
It just checks the status in Redis and gives the response.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#4809](https://github.com/juspay/hyperswitch/issues/4809)
## How did you test it?
Use the curl to get the status
```
curl --location 'http://localhost:8080/user/2fa' \
--header 'Authorization: Bearer JWT' \
--header 'Cookie: Cookie_1=value'
```
Response will be something like
```
{
"totp": true,
"recovery_code": false
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
cd9c9b609c8d5d7c77658d973f7922ae71af9a4d
|
Use the curl to get the status
```
curl --location 'http://localhost:8080/user/2fa' \
--header 'Authorization: Bearer JWT' \
--header 'Cookie: Cookie_1=value'
```
Response will be something like
```
{
"totp": true,
"recovery_code": false
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4808
|
Bug: [BUG] Fixing 3DS payment failure in headless mode
### Bug Description
3DS payments were failing in the refund test in Cypress headless mode. I added the timeout and properly configured the hooks to fetch the redirection URL correctly.
### Expected Behavior
It should pass in headless mode
### Actual Behavior
Its failing in headless mode
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Run the cypress test in headless using the below command
CYPRESS_CONNECTOR='connector_name' npm run cypress:ci
### Context For The Bug
_No response_
### Environment
In sandbox
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
2024-05-29T10:09:01Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
3DS payments were failing in the refund test in Cypress headless mode. I added the timeout and properly configured the hooks to fetch the redirection URL correctly.
## Motivation and Context
To ensure the test runs successfully without any failures in the CI/CD pipeline.
## How did you test it?
Tested locally in the headless mode
Stripe
<img width="843" alt="Screenshot 2024-05-29 at 1 41 57 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/b5737099-bf5c-4408-b598-77185c257411">
Cybersource
<img width="898" alt="Screenshot 2024-05-29 at 2 45 53 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/63c7be7b-9b12-4312-8b55-26aa53fde86d">
NMI
<img width="807" alt="Screenshot 2024-05-29 at 3 09 28 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/496d2212-0ceb-4fd8-8584-b507907f2521">
Adyen
<img width="852" alt="Screenshot 2024-05-29 at 3 17 36 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/07722a6d-b771-4585-b618-944423c8c15b">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b812e596a1bef4cc154f5b925753ad158c9022de
|
Tested locally in the headless mode
Stripe
<img width="843" alt="Screenshot 2024-05-29 at 1 41 57 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/b5737099-bf5c-4408-b598-77185c257411">
Cybersource
<img width="898" alt="Screenshot 2024-05-29 at 2 45 53 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/63c7be7b-9b12-4312-8b55-26aa53fde86d">
NMI
<img width="807" alt="Screenshot 2024-05-29 at 3 09 28 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/496d2212-0ceb-4fd8-8584-b507907f2521">
Adyen
<img width="852" alt="Screenshot 2024-05-29 at 3 17 36 PM" src="https://github.com/juspay/hyperswitch/assets/118818938/07722a6d-b771-4585-b618-944423c8c15b">
|
||
juspay/hyperswitch
|
juspay__hyperswitch-4818
|
Bug: [FEATURE]:Remove Braintree SDK Flow support
Remove the SDK Support for the Braintree
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 941a315aaee..a78e5b2c995 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -194,8 +194,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -542,8 +541,6 @@ adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamal
[bank_config.online_banking_thailand]
adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank"
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[applepay_decrypt_keys]
apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE" # Payment Processing Certificate provided by Apple Pay (https://developer.apple.com/) Certificates, Identifiers & Profiles > Apple Pay Payment Processing Certificate
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 7c946f8209b..4d433e1a9db 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -34,8 +34,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -157,8 +156,6 @@ card.debit = { connector_list = "cybersource" } # Update Mandate sup
[network_transaction_id_supported_connectors]
connector_list = "stripe,adyen,cybersource"
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[payouts]
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 4630b969224..5c843faf519 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -38,8 +38,7 @@ bitpay.base_url = "https://bitpay.com"
bluesnap.base_url = "https://ws.bluesnap.com/"
bluesnap.secondary_base_url = "https://pay.bluesnap.com/"
boku.base_url = "https://country-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.braintree-api.com/graphql"
+braintree.base_url = "https://payments.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster14.api.cashtocode.com"
checkout.base_url = "https://api.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -154,8 +153,6 @@ bank_redirect.giropay.connector_list = "adyen,globalpay,multisafepay" # M
card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[payouts]
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 5fb7bfe0d68..fe0d99f8eeb 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -38,8 +38,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -157,8 +156,6 @@ card.debit = { connector_list = "cybersource" } # Update Mandate sup
[network_transaction_id_supported_connectors]
connector_list = "stripe,adyen,cybersource"
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[payouts]
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
diff --git a/config/development.toml b/config/development.toml
index 48aa82b07a2..b3a64adf0ba 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -190,8 +190,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -573,8 +572,6 @@ merchant_ids_send_payment_id_as_connector_request_id = []
[payouts]
payout_eligibility = true
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[applepay_decrypt_keys]
apple_pay_ppc = "APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 61fdf86e457..6263e945b96 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -123,8 +123,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://$-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -439,8 +438,6 @@ connector_list = "stripe,adyen,cybersource"
connector_list = "gocardless,stax,stripe"
payout_connector_list = "stripe,wise"
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
[payment_method_auth]
redis_expiry = 900
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index fe15422a128..85b310397b2 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -1,10 +1,14 @@
-pub mod braintree_graphql_transformers;
pub mod transformers;
-use std::{fmt::Debug, str::FromStr};
+use std::str::FromStr;
use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
-use common_utils::{crypto, ext_traits::XmlExt, request::RequestContent};
+use common_utils::{
+ crypto,
+ ext_traits::XmlExt,
+ request::RequestContent,
+ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
+};
use diesel_models::enums;
use error_stack::{report, Report, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
@@ -37,19 +41,22 @@ use crate::{
utils::{self, BytesExt},
};
-#[derive(Debug, Clone)]
-pub struct Braintree;
-
-pub const BRAINTREE_VERSION: &str = "Braintree-Version";
-pub const BRAINTREE_VERSION_VALUE: &str = "2019-01-01";
-pub const BRAINTREE_API_VERSION: &str = "graphql_api";
+#[derive(Clone)]
+pub struct Braintree {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
+}
impl Braintree {
- pub fn is_braintree_graphql_version(&self, connector_api_version: &Option<String>) -> bool {
- *connector_api_version == Some(BRAINTREE_API_VERSION.to_string())
+ pub const fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMajorUnitForConnector,
+ }
}
}
+pub const BRAINTREE_VERSION: &str = "Braintree-Version";
+pub const BRAINTREE_VERSION_VALUE: &str = "2019-01-01";
+
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Braintree
where
Self: ConnectorIntegration<Flow, Request, Response>,
@@ -94,9 +101,11 @@ impl ConnectorCommon for Braintree {
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
let auth = braintree::BraintreeAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let auth_key = format!("{}:{}", auth.public_key.peek(), auth.private_key.peek());
+ let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
- auth.auth_header.into_masked(),
+ auth_header.into_masked(),
)])
}
@@ -105,11 +114,13 @@ impl ConnectorCommon for Braintree {
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- let response: Result<braintree::ErrorResponse, Report<common_utils::errors::ParsingError>> =
- res.response.parse_struct("Braintree Error Response");
+ let response: Result<
+ braintree::ErrorResponses,
+ Report<common_utils::errors::ParsingError>,
+ > = res.response.parse_struct("Braintree Error Response");
match response {
- Ok(braintree::ErrorResponse::BraintreeApiErrorResponse(response)) => {
+ Ok(braintree::ErrorResponses::BraintreeApiErrorResponse(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -139,7 +150,7 @@ impl ConnectorCommon for Braintree {
connector_transaction_id: None,
})
}
- Ok(braintree::ErrorResponse::BraintreeErrorResponse(response)) => {
+ Ok(braintree::ErrorResponses::BraintreeErrorResponse(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -205,109 +216,6 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
for Braintree
{
- fn get_headers(
- &self,
- req: &types::PaymentsSessionRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsSessionType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
-
- fn get_content_type(&self) -> &'static str {
- "application/json"
- }
-
- fn get_url(
- &self,
- req: &types::PaymentsSessionRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(format!(
- "{}/merchants/{}/client_token",
- self.base_url(connectors),
- auth_type.merchant_id.peek(),
- ))
- }
-
- fn build_request(
- &self,
- req: &types::PaymentsSessionRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(None),
- false => {
- let request = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsSessionType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::PaymentsSessionType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsSessionType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- );
- Ok(request)
- }
- }
- }
-
- fn get_error_response(
- &self,
- res: types::Response,
- event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res, event_builder)
- }
-
- fn get_request_body(
- &self,
- req: &types::PaymentsSessionRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = braintree::BraintreeSessionRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
-
- fn handle_response(
- &self,
- data: &types::PaymentsSessionRouterData,
- event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> {
- let response: braintree::BraintreeSessionTokenResponse = res
- .response
- .parse_struct("braintree SessionTokenResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
}
impl api::PaymentToken for Braintree {}
@@ -336,12 +244,7 @@ impl
_req: &types::TokenizationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -349,7 +252,7 @@ impl
req: &types::TokenizationRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = braintree_graphql_transformers::BraintreeTokenRequest::try_from(req)?;
+ let connector_req = transformers::BraintreeTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
@@ -359,23 +262,18 @@ impl
req: &types::TokenizationRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::TokenizationType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::TokenizationType::get_headers(self, req, connectors)?)
- .set_body(types::TokenizationType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- )),
- false => Ok(None),
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::TokenizationType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::TokenizationType::get_headers(self, req, connectors)?)
+ .set_body(types::TokenizationType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
}
-
fn handle_response(
&self,
data: &types::TokenizationRouterData,
@@ -385,7 +283,7 @@ impl
where
types::PaymentsResponseData: Clone,
{
- let response: braintree_graphql_transformers::BraintreeTokenResponse = res
+ let response: transformers::BraintreeTokenResponse = res
.response
.parse_struct("BraintreeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -442,11 +340,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version.clone();
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => Ok(vec![]),
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -455,23 +349,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
+ _req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = req.connector_api_version.clone();
- match self.is_braintree_graphql_version(&connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -479,28 +360,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
req: &types::PaymentsCaptureRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version.clone();
- let connector_router_data =
- braintree_graphql_transformers::BraintreeRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.amount_to_capture,
- req,
- ))?;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreeCaptureRequest::try_from(
- &connector_router_data,
- )?;
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount_to_capture,
+ req.request.currency,
+ )?;
+ let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
+ let connector_req =
+ transformers::BraintreeCaptureRequest::try_from(&connector_router_data)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(errors::ConnectorError::NotImplemented(
- "get_request_body method".to_string(),
- )
- .into()),
- }
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -508,26 +377,19 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
req: &types::PaymentsCaptureRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- )),
- false => Err(errors::ConnectorError::NotImplemented(
- "Capture flow not Implemented".to_string(),
- )
- .into()),
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCaptureType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
}
fn handle_response(
@@ -536,7 +398,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: braintree_graphql_transformers::BraintreeCaptureResponse = res
+ let response: transformers::BraintreeCaptureResponse = res
.response
.parse_struct("Braintree PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -566,28 +428,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsSyncType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -596,34 +437,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
+ _req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- let connector_payment_id = req
- .request
- .connector_transaction_id
- .get_connector_transaction_id()
- .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
- Ok(format!(
- "{}/merchants/{}/transactions/{connector_payment_id}",
- self.base_url(connectors),
- auth_type.merchant_id.peek()
- ))
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -631,16 +448,9 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
req: &types::PaymentsSyncRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreePSyncRequest::try_from(req)?;
+ let connector_req = transformers::BraintreePSyncRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(report!(errors::ConnectorError::RequestEncodingFailed)),
- }
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -648,31 +458,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
- .set_body(types::PaymentsSyncType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- )),
- false => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
- .set_body(types::PaymentsSyncType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- )),
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::PaymentsSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
}
fn handle_response(
@@ -681,35 +477,17 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let response: braintree_graphql_transformers::BraintreePSyncResponse = res
- .response
- .parse_struct("Braintree PaymentSyncResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree::BraintreePaymentsResponse = res
- .response
- .parse_struct("Braintree PaymentsResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- }
+ let response: transformers::BraintreePSyncResponse = res
+ .response
+ .parse_struct("Braintree PaymentSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
}
fn get_error_response(
@@ -729,56 +507,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
- }
+ self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ _req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
-
- Ok(format!(
- "{}merchants/{}/transactions",
- self.base_url(connectors),
- auth_type.merchant_id.peek()
- ))
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn build_request(
@@ -808,27 +545,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- let connector_router_data =
- braintree_graphql_transformers::BraintreeRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.amount,
- req,
- ))?;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreePaymentsRequest::try_from(
- &connector_router_data,
- )?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => {
- let connector_req = braintree::BraintreePaymentsRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- }
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
+ let connector_req: transformers::BraintreePaymentsRequest =
+ transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
@@ -837,38 +562,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => match data.request.is_auto_capture()? {
- true => {
- let response: braintree_graphql_transformers::BraintreePaymentsResponse = res
- .response
- .parse_struct("Braintree PaymentsResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree_graphql_transformers::BraintreeAuthResponse = res
- .response
- .parse_struct("Braintree AuthResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- },
- false => {
- let response: braintree::BraintreePaymentsResponse = res
+ match data.request.is_auto_capture()? {
+ true => {
+ let response: transformers::BraintreePaymentsResponse = res
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -880,6 +576,19 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
http_code: res.status_code,
})
}
+ false => {
+ let response: transformers::BraintreeAuthResponse = res
+ .response
+ .parse_struct("Braintree AuthResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
}
}
@@ -900,28 +609,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsVoidType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -930,30 +618,10 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
+ _req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(format!(
- "{}merchants/{}/transactions/{}/void",
- self.base_url(connectors),
- auth_type.merchant_id.peek(),
- req.request.connector_transaction_id
- ))
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn build_request(
@@ -979,15 +647,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
req: &types::PaymentsCancelRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreeCancelRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(report!(errors::ConnectorError::RequestEncodingFailed)),
- }
+ let connector_req = transformers::BraintreeCancelRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
@@ -996,37 +657,18 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let response: braintree_graphql_transformers::BraintreeCancelResponse = res
- .response
- .parse_struct("Braintree VoidResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree::BraintreePaymentsResponse = res
- .response
- .parse_struct("Braintree PaymentsVoidResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- }
+ let response: transformers::BraintreeCancelResponse = res
+ .response
+ .parse_struct("Braintree VoidResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
}
-
fn get_error_response(
&self,
res: types::Response,
@@ -1048,28 +690,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => {
- let mut headers = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::RefundExecuteType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (headers::X_API_VERSION.to_string(), "6".to_string().into()),
- (
- headers::ACCEPT.to_string(),
- "application/json".to_string().into(),
- ),
- ];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- headers.append(&mut api_key);
- Ok(headers)
- }
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -1078,31 +699,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
+ _req: &types::RefundsRouterData<api::Execute>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- let connector_payment_id = req.request.connector_transaction_id.clone();
- Ok(format!(
- "{}merchants/{}/transactions/{}",
- self.base_url(connectors),
- auth_type.merchant_id.peek(),
- connector_payment_id
- ))
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -1110,29 +710,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- let connector_router_data =
- braintree_graphql_transformers::BraintreeRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.refund_amount,
- req,
- ))?;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreeRefundRequest::try_from(
- connector_router_data,
- )?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => {
- let connector_req = braintree::BraintreeRefundRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- }
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_refund_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
+ let connector_req = transformers::BraintreeRefundRequest::try_from(connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
-
fn build_request(
&self,
req: &types::RefundsRouterData<api::Execute>,
@@ -1158,35 +744,17 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let response: braintree_graphql_transformers::BraintreeRefundResponse = res
- .response
- .parse_struct("Braintree RefundResponse")
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree::RefundResponse = res
- .response
- .parse_struct("Braintree RefundResponse")
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- }
+ let response: transformers::BraintreeRefundResponse = res
+ .response
+ .parse_struct("Braintree RefundResponse")
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
}
fn get_error_response(
@@ -1206,11 +774,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => Ok(vec![]),
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -1219,23 +783,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
+ _req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
@@ -1243,15 +794,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
req: &types::RefundSyncRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreeRSyncRequest::try_from(req)?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(report!(errors::ConnectorError::RequestEncodingFailed)),
- }
+ let connector_req = transformers::BraintreeRSyncRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -1259,21 +803,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
req: &types::RefundSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
- .set_body(types::RefundSyncType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- )),
- false => Ok(None),
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(types::RefundSyncType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
}
fn handle_response(
@@ -1285,35 +825,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
errors::ConnectorError,
> {
- let connector_api_version = &data.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let response: braintree_graphql_transformers::BraintreeRSyncResponse = res
- .response
- .parse_struct("Braintree RefundResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- false => {
- let response: braintree::RefundResponse = res
- .response
- .parse_struct("Braintree RefundResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
- }
+ let response: transformers::BraintreeRSyncResponse = res
+ .response
+ .parse_struct("Braintree RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
}
fn get_error_response(
&self,
@@ -1485,9 +1007,7 @@ impl api::IncomingWebhook for Braintree {
currency,
)?,
currency: dispute_data.currency_iso_code,
- dispute_stage: braintree_graphql_transformers::get_dispute_stage(
- dispute_data.kind.as_str(),
- )?,
+ dispute_stage: transformers::get_dispute_stage(dispute_data.kind.as_str())?,
connector_dispute_id: dispute_data.id,
connector_reason: dispute_data.reason,
connector_reason_code: dispute_data.reason_code,
@@ -1516,16 +1036,15 @@ fn get_matching_webhook_signature(
fn get_webhook_object_from_body(
body: &[u8],
-) -> CustomResult<braintree_graphql_transformers::BraintreeWebhookResponse, errors::ParsingError> {
- serde_urlencoded::from_bytes::<braintree_graphql_transformers::BraintreeWebhookResponse>(body)
- .change_context(errors::ParsingError::StructParseFailure(
- "BraintreeWebhookResponse",
- ))
+) -> CustomResult<transformers::BraintreeWebhookResponse, errors::ParsingError> {
+ serde_urlencoded::from_bytes::<transformers::BraintreeWebhookResponse>(body).change_context(
+ errors::ParsingError::StructParseFailure("BraintreeWebhookResponse"),
+ )
}
fn decode_webhook_payload(
payload: &[u8],
-) -> CustomResult<braintree_graphql_transformers::Notification, errors::ConnectorError> {
+) -> CustomResult<transformers::Notification, errors::ConnectorError> {
let decoded_response = consts::BASE64_ENGINE
.decode(payload)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
@@ -1534,7 +1053,7 @@ fn decode_webhook_payload(
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
xml_response
- .parse_xml::<braintree_graphql_transformers::Notification>()
+ .parse_xml::<transformers::Notification>()
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
}
@@ -1548,17 +1067,16 @@ impl services::ConnectorRedirectResponse for Braintree {
match action {
services::PaymentAction::PSync => match json_payload {
Some(payload) => {
- let redirection_response:braintree_graphql_transformers::BraintreeRedirectionResponse = serde_json::from_value(payload)
-
- .change_context(
- errors::ConnectorError::MissingConnectorRedirectionPayload {
- field_name: "redirection_response",
- },
- )?;
+ let redirection_response: transformers::BraintreeRedirectionResponse =
+ serde_json::from_value(payload).change_context(
+ errors::ConnectorError::MissingConnectorRedirectionPayload {
+ field_name: "redirection_response",
+ },
+ )?;
let braintree_payload =
- serde_json::from_str::<
- braintree_graphql_transformers::BraintreeThreeDsErrorResponse,
- >(&redirection_response.authentication_response);
+ serde_json::from_str::<transformers::BraintreeThreeDsErrorResponse>(
+ &redirection_response.authentication_response,
+ );
let (error_code, error_message) = match braintree_payload {
Ok(braintree_response_payload) => (
braintree_response_payload.code,
@@ -1597,62 +1115,33 @@ impl
req: &types::PaymentsCompleteAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => self.build_headers(req, connectors),
- false => Err(errors::ConnectorError::NotImplemented(
- "get_headers method".to_string(),
- ))?,
- }
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
+ _req: &types::PaymentsCompleteAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let base_url = connectors
- .braintree
- .secondary_base_url
- .as_ref()
- .ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
- Ok(base_url.to_string())
- }
- false => Err(errors::ConnectorError::NotImplemented(
- "get_url method".to_string(),
- ))?,
- }
+ Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &types::PaymentsCompleteAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_router_data =
- braintree_graphql_transformers::BraintreeRouterData::try_from((
- &self.get_currency_unit(),
- req.request.currency,
- req.request.amount,
- req,
- ))?;
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => {
- let connector_req =
- braintree_graphql_transformers::BraintreePaymentsRequest::try_from(
- &connector_router_data,
- )?;
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
- false => Err(errors::ConnectorError::NotImplemented(
- "get_request_body method".to_string(),
- ))?,
- }
+ let amount = connector_utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount,
+ req.request.currency,
+ )?;
+ let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
+
+ let connector_req =
+ transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -1660,27 +1149,21 @@ impl
req: &types::PaymentsCompleteAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let connector_api_version = &req.connector_api_version;
- match self.is_braintree_graphql_version(connector_api_version) {
- true => Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCompleteAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .attach_default_headers()
- .headers(types::PaymentsCompleteAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- )),
- false => Err(errors::ConnectorError::NotImplemented(
- "payment method".to_string(),
- ))?,
- }
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
}
fn handle_response(
&self,
@@ -1691,7 +1174,7 @@ impl
match connector_utils::PaymentsCompleteAuthorizeRequestData::is_auto_capture(&data.request)?
{
true => {
- let response: braintree_graphql_transformers::BraintreeCompleteChargeResponse = res
+ let response: transformers::BraintreeCompleteChargeResponse = res
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -1704,7 +1187,7 @@ impl
})
}
false => {
- let response: braintree_graphql_transformers::BraintreeCompleteAuthResponse = res
+ let response: transformers::BraintreeCompleteAuthResponse = res
.response
.parse_struct("Braintree AuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
deleted file mode 100644
index af50bd10ce7..00000000000
--- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
+++ /dev/null
@@ -1,1667 +0,0 @@
-use common_utils::pii;
-use error_stack::ResultExt;
-use masking::{ExposeInterface, Secret};
-use serde::{Deserialize, Serialize};
-use time::PrimitiveDateTime;
-
-use crate::{
- connector::utils::{
- self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
- RefundsRequestData, RouterData,
- },
- consts,
- core::errors,
- services,
- types::{self, api, domain, storage::enums, MandateReference},
- unimplemented_payment_method,
-};
-
-pub const CLIENT_TOKEN_MUTATION: &str = "mutation createClientToken($input: CreateClientTokenInput!) { createClientToken(input: $input) { clientToken}}";
-pub const TOKENIZE_CREDIT_CARD: &str = "mutation tokenizeCreditCard($input: TokenizeCreditCardInput!) { tokenizeCreditCard(input: $input) { clientMutationId paymentMethod { id } } }";
-pub const CHARGE_CREDIT_CARD_MUTATION: &str = "mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id legacyId createdAt amount { value currencyCode } status } } }";
-pub const AUTHORIZE_CREDIT_CARD_MUTATION: &str = "mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
-pub const CAPTURE_TRANSACTION_MUTATION: &str = "mutation captureTransaction($input: CaptureTransactionInput!) { captureTransaction(input: $input) { clientMutationId transaction { id legacyId amount { value currencyCode } status } } }";
-pub const VOID_TRANSACTION_MUTATION: &str = "mutation voidTransaction($input: ReverseTransactionInput!) { reverseTransaction(input: $input) { clientMutationId reversal { ... on Transaction { id legacyId amount { value currencyCode } status } } } }";
-pub const REFUND_TRANSACTION_MUTATION: &str = "mutation refundTransaction($input: RefundTransactionInput!) { refundTransaction(input: $input) {clientMutationId refund { id legacyId amount { value currencyCode } status } } }";
-pub const AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION: &str="mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
-pub const CHARGE_AND_VAULT_TRANSACTION_MUTATION: &str ="mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
-
-#[derive(Debug, Serialize)]
-pub struct BraintreeRouterData<T> {
- pub amount: String,
- pub router_data: T,
-}
-
-impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for BraintreeRouterData<T> {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- (currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
- ) -> Result<Self, Self::Error> {
- let amount = utils::get_amount_as_string(currency_unit, amount, currency)?;
- Ok(Self {
- amount,
- router_data: item,
- })
- }
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentInput {
- payment_method_id: Secret<String>,
- transaction: TransactionBody,
-}
-
-#[derive(Debug, Serialize)]
-pub struct VariablePaymentInput {
- input: PaymentInput,
-}
-
-#[derive(Debug, Serialize)]
-pub struct CardPaymentRequest {
- query: String,
- variables: VariablePaymentInput,
-}
-
-#[derive(Debug, Serialize)]
-pub struct MandatePaymentRequest {
- query: String,
- variables: VariablePaymentInput,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(untagged)]
-pub enum BraintreePaymentsRequest {
- Card(CardPaymentRequest),
- CardThreeDs(BraintreeClientTokenRequest),
- Mandate(MandatePaymentRequest),
-}
-
-#[derive(Debug, Deserialize)]
-pub struct BraintreeMeta {
- merchant_account_id: Secret<String>,
- merchant_config_currency: enums::Currency,
-}
-
-impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
- let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConnectorConfig {
- config: "metadata",
- })?;
- Ok(metadata)
- }
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct RegularTransactionBody {
- amount: String,
- merchant_account_id: Secret<String>,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct VaultTransactionBody {
- amount: String,
- merchant_account_id: Secret<String>,
- vault_payment_method_after_transacting: TransactionTiming,
-}
-
-#[derive(Debug, Serialize)]
-#[serde(untagged)]
-pub enum TransactionBody {
- Regular(RegularTransactionBody),
- Vault(VaultTransactionBody),
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TransactionTiming {
- when: String,
-}
-
-impl
- TryFrom<(
- &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- String,
- BraintreeMeta,
- )> for MandatePaymentRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- (item, connector_mandate_id, metadata): (
- &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- String,
- BraintreeMeta,
- ),
- ) -> Result<Self, Self::Error> {
- let (query, transaction_body) = (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
- false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Regular(RegularTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- }),
- );
- Ok(Self {
- query,
- variables: VariablePaymentInput {
- input: PaymentInput {
- payment_method_id: connector_mandate_id.into(),
- transaction: transaction_body,
- },
- },
- })
- }
-}
-
-impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>>
- for BraintreePaymentsRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- ) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConnectorConfig {
- config: "metadata",
- })?;
- utils::validate_currency(
- item.router_data.request.currency,
- Some(metadata.merchant_config_currency),
- )?;
- match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(_) => {
- if item.router_data.is_three_ds() {
- Ok(Self::CardThreeDs(BraintreeClientTokenRequest::try_from(
- metadata,
- )?))
- } else {
- Ok(Self::Card(CardPaymentRequest::try_from((item, metadata))?))
- }
- }
- domain::PaymentMethodData::MandatePayment => {
- let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "connector_mandate_id",
- },
- )?;
- Ok(Self::Mandate(MandatePaymentRequest::try_from((
- item,
- connector_mandate_id,
- metadata,
- ))?))
- }
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("braintree"),
- )
- .into())
- }
- }
- }
-}
-
-impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
- for BraintreePaymentsRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
- ) -> Result<Self, Self::Error> {
- match item.router_data.payment_method {
- api_models::enums::PaymentMethod::Card => {
- Ok(Self::Card(CardPaymentRequest::try_from(item)?))
- }
- api_models::enums::PaymentMethod::CardRedirect
- | api_models::enums::PaymentMethod::PayLater
- | api_models::enums::PaymentMethod::Wallet
- | api_models::enums::PaymentMethod::BankRedirect
- | api_models::enums::PaymentMethod::BankTransfer
- | api_models::enums::PaymentMethod::Crypto
- | api_models::enums::PaymentMethod::BankDebit
- | api_models::enums::PaymentMethod::Reward
- | api_models::enums::PaymentMethod::RealTimePayment
- | api_models::enums::PaymentMethod::Upi
- | api_models::enums::PaymentMethod::Voucher
- | api_models::enums::PaymentMethod::OpenBanking
- | api_models::enums::PaymentMethod::GiftCard => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message(
- "complete authorize flow",
- ),
- )
- .into())
- }
- }
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct AuthResponse {
- data: DataAuthResponse,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeAuthResponse {
- AuthResponse(Box<AuthResponse>),
- ClientTokenResponse(Box<ClientTokenResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeCompleteAuthResponse {
- AuthResponse(Box<AuthResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-struct PaymentMethodInfo {
- id: Secret<String>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TransactionAuthChargeResponseBody {
- id: String,
- status: BraintreePaymentStatus,
- payment_method: Option<PaymentMethodInfo>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DataAuthResponse {
- authorize_credit_card: AuthChargeCreditCard,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct AuthChargeCreditCard {
- transaction: TransactionAuthChargeResponseBody,
-}
-
-impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BraintreeAuthResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<
- F,
- BraintreeAuthResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeAuthResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreeAuthResponse::AuthResponse(auth_response) => {
- let transaction_data = auth_response.data.authorize_credit_card.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
- connector_mandate_id: Some(pm.id.clone().expose()),
- payment_method_id: None,
- }
- }),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- BraintreeAuthResponse::ClientTokenResponse(client_token_data) => Ok(Self {
- status: enums::AttemptStatus::AuthenticationPending,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(get_braintree_redirect_form(
- *client_token_data,
- item.data.get_payment_method_token()?,
- item.data.request.payment_method_data.clone(),
- )?),
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- }),
- }
- }
-}
-
-fn build_error_response<T>(
- response: &[ErrorDetails],
- http_code: u16,
-) -> Result<T, types::ErrorResponse> {
- let error_messages = response
- .iter()
- .map(|error| error.message.to_string())
- .collect::<Vec<String>>();
-
- let reason = match !error_messages.is_empty() {
- true => Some(error_messages.join(" ")),
- false => None,
- };
-
- get_error_response(
- response
- .first()
- .and_then(|err_details| err_details.extensions.as_ref())
- .and_then(|extensions| extensions.legacy_code.clone()),
- response
- .first()
- .map(|err_details| err_details.message.clone()),
- reason,
- http_code,
- )
-}
-
-fn get_error_response<T>(
- error_code: Option<String>,
- error_msg: Option<String>,
- error_reason: Option<String>,
- http_code: u16,
-) -> Result<T, types::ErrorResponse> {
- Err(types::ErrorResponse {
- code: error_code.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
- message: error_msg.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
- reason: error_reason,
- status_code: http_code,
- attempt_status: None,
- connector_transaction_id: None,
- })
-}
-
-// Using Auth type from braintree/transformer.rs, need this in later time when we use graphql version
-// pub struct BraintreeAuthType {
-// pub(super) auth_header: String,
-// pub(super) merchant_id: Secret<String>,
-// }
-
-// impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType {
-// type Error = error_stack::Report<errors::ConnectorError>;
-// fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
-// if let types::ConnectorAuthType::SignatureKey {
-// api_key: public_key,
-// key1: merchant_id,
-// api_secret: private_key,
-// } = item
-// {
-// let auth_key = format!("{}:{}", public_key.peek(), private_key.peek());
-// let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
-// Ok(Self {
-// auth_header,
-// merchant_id: merchant_id.to_owned(),
-// })
-// } else {
-// Err(errors::ConnectorError::FailedToObtainAuthType)?
-// }
-// }
-// }
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum BraintreePaymentStatus {
- Authorized,
- Authorizing,
- AuthorizedExpired,
- Failed,
- ProcessorDeclined,
- GatewayRejected,
- Voided,
- Settling,
- Settled,
- SettlementPending,
- SettlementDeclined,
- SettlementConfirmed,
- SubmittedForSettlement,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct ErrorDetails {
- pub message: String,
- pub extensions: Option<AdditionalErrorDetails>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AdditionalErrorDetails {
- pub legacy_code: Option<String>,
-}
-
-impl From<BraintreePaymentStatus> for enums::AttemptStatus {
- fn from(item: BraintreePaymentStatus) -> Self {
- match item {
- BraintreePaymentStatus::Settling
- | BraintreePaymentStatus::Settled
- | BraintreePaymentStatus::SettlementConfirmed => Self::Charged,
- BraintreePaymentStatus::Authorizing => Self::Authorizing,
- BraintreePaymentStatus::AuthorizedExpired => Self::AuthorizationFailed,
- BraintreePaymentStatus::Failed
- | BraintreePaymentStatus::GatewayRejected
- | BraintreePaymentStatus::ProcessorDeclined
- | BraintreePaymentStatus::SettlementDeclined => Self::Failure,
- BraintreePaymentStatus::Authorized => Self::Authorized,
- BraintreePaymentStatus::Voided => Self::Voided,
- BraintreePaymentStatus::SubmittedForSettlement
- | BraintreePaymentStatus::SettlementPending => Self::Pending,
- }
- }
-}
-
-impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BraintreePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<
- F,
- BraintreePaymentsResponse,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreePaymentsResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors.clone(), item.http_code),
- ..item.data
- }),
- BraintreePaymentsResponse::PaymentsResponse(payment_response) => {
- let transaction_data = payment_response.data.charge_credit_card.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
- connector_mandate_id: Some(pm.id.clone().expose()),
- payment_method_id: None,
- }
- }),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- BraintreePaymentsResponse::ClientTokenResponse(client_token_data) => Ok(Self {
- status: enums::AttemptStatus::AuthenticationPending,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
- redirection_data: Some(get_braintree_redirect_form(
- *client_token_data,
- item.data.get_payment_method_token()?,
- item.data.request.payment_method_data.clone(),
- )?),
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- }),
- }
- }
-}
-
-impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BraintreeCompleteChargeResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<
- F,
- BraintreeCompleteChargeResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeCompleteChargeResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors.clone(), item.http_code),
- ..item.data
- }),
- BraintreeCompleteChargeResponse::PaymentsResponse(payment_response) => {
- let transaction_data = payment_response.data.charge_credit_card.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
- connector_mandate_id: Some(pm.id.clone().expose()),
- payment_method_id: None,
- }
- }),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- }
- }
-}
-
-impl<F>
- TryFrom<
- types::ResponseRouterData<
- F,
- BraintreeCompleteAuthResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<
- F,
- BraintreeCompleteAuthResponse,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- >,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeCompleteAuthResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreeCompleteAuthResponse::AuthResponse(auth_response) => {
- let transaction_data = auth_response.data.authorize_credit_card.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
- MandateReference {
- connector_mandate_id: Some(pm.id.clone().expose()),
- payment_method_id: None,
- }
- }),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- }
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct PaymentsResponse {
- data: DataResponse,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreePaymentsResponse {
- PaymentsResponse(Box<PaymentsResponse>),
- ClientTokenResponse(Box<ClientTokenResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeCompleteChargeResponse {
- PaymentsResponse(Box<PaymentsResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DataResponse {
- charge_credit_card: AuthChargeCreditCard,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct RefundInputData {
- amount: String,
- merchant_account_id: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeRefundInput {
- transaction_id: String,
- refund: RefundInputData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeRefundVariables {
- input: BraintreeRefundInput,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeRefundRequest {
- query: String,
- variables: BraintreeRefundVariables,
-}
-
-impl<F> TryFrom<BraintreeRouterData<&types::RefundsRouterData<F>>> for BraintreeRefundRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: BraintreeRouterData<&types::RefundsRouterData<F>>,
- ) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConnectorConfig {
- config: "metadata",
- })?;
-
- utils::validate_currency(
- item.router_data.request.currency,
- Some(metadata.merchant_config_currency),
- )?;
- let query = REFUND_TRANSACTION_MUTATION.to_string();
- let variables = BraintreeRefundVariables {
- input: BraintreeRefundInput {
- transaction_id: item.router_data.request.connector_transaction_id.clone(),
- refund: RefundInputData {
- amount: item.amount,
- merchant_account_id: metadata.merchant_account_id,
- },
- },
- };
- Ok(Self { query, variables })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum BraintreeRefundStatus {
- SettlementPending,
- Settling,
- Settled,
- SubmittedForSettlement,
- Failed,
-}
-
-impl From<BraintreeRefundStatus> for enums::RefundStatus {
- fn from(item: BraintreeRefundStatus) -> Self {
- match item {
- BraintreeRefundStatus::Settled | BraintreeRefundStatus::Settling => Self::Success,
- BraintreeRefundStatus::SubmittedForSettlement
- | BraintreeRefundStatus::SettlementPending => Self::Pending,
- BraintreeRefundStatus::Failed => Self::Failure,
- }
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct BraintreeRefundTransactionBody {
- pub id: String,
- pub status: BraintreeRefundStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct BraintreeRefundTransaction {
- pub refund: BraintreeRefundTransactionBody,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeRefundResponseData {
- pub refund_transaction: BraintreeRefundTransaction,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-
-pub struct RefundResponse {
- pub data: BraintreeRefundResponseData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeRefundResponse {
- RefundResponse(Box<RefundResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, BraintreeRefundResponse>>
- for types::RefundsRouterData<api::Execute>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, BraintreeRefundResponse>,
- ) -> Result<Self, Self::Error> {
- Ok(Self {
- response: match item.response {
- BraintreeRefundResponse::ErrorResponse(error_response) => {
- build_error_response(&error_response.errors, item.http_code)
- }
- BraintreeRefundResponse::RefundResponse(refund_data) => {
- let refund_data = refund_data.data.refund_transaction.refund;
-
- Ok(types::RefundsResponseData {
- connector_refund_id: refund_data.id.clone(),
- refund_status: enums::RefundStatus::from(refund_data.status),
- })
- }
- },
- ..item.data
- })
- }
-}
-
-#[derive(Debug, Serialize)]
-pub struct BraintreeRSyncRequest {
- query: String,
-}
-
-impl TryFrom<&types::RefundSyncRouterData> for BraintreeRSyncRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta = utils::to_connector_meta_from_secret(
- item.connector_meta_data.clone(),
- )
- .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
- utils::validate_currency(
- item.request.currency,
- Some(metadata.merchant_config_currency),
- )?;
- let refund_id = item.request.get_connector_refund_id()?;
- let query = format!("query {{ search {{ refunds(input: {{ id: {{is: \"{}\"}} }}, first: 1) {{ edges {{ node {{ id status createdAt amount {{ value currencyCode }} orderId }} }} }} }} }}",refund_id);
-
- Ok(Self { query })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncNodeData {
- id: String,
- status: BraintreeRefundStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncEdgeData {
- node: RSyncNodeData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RefundData {
- edges: Vec<RSyncEdgeData>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncSearchData {
- refunds: RefundData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncResponseData {
- search: RSyncSearchData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct RSyncResponse {
- data: RSyncResponseData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeRSyncResponse {
- RSyncResponse(Box<RSyncResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, BraintreeRSyncResponse>>
- for types::RefundsRouterData<api::RSync>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, BraintreeRSyncResponse>,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeRSyncResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreeRSyncResponse::RSyncResponse(rsync_response) => {
- let edge_data = rsync_response
- .data
- .search
- .refunds
- .edges
- .first()
- .ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
- let connector_refund_id = &edge_data.node.id;
- let response = Ok(types::RefundsResponseData {
- connector_refund_id: connector_refund_id.to_string(),
- refund_status: enums::RefundStatus::from(edge_data.node.status.clone()),
- });
- Ok(Self {
- response,
- ..item.data
- })
- }
- }
- }
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CreditCardData {
- number: cards::CardNumber,
- expiration_year: Secret<String>,
- expiration_month: Secret<String>,
- cvv: Secret<String>,
- cardholder_name: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClientTokenInput {
- merchant_account_id: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct InputData {
- credit_card: CreditCardData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct InputClientTokenData {
- client_token: ClientTokenInput,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct VariableInput {
- input: InputData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct VariableClientTokenInput {
- input: InputClientTokenData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeTokenRequest {
- query: String,
- variables: VariableInput,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeClientTokenRequest {
- query: String,
- variables: VariableClientTokenInput,
-}
-
-impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
- match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(card_data) => {
- let query = TOKENIZE_CREDIT_CARD.to_string();
- let input = InputData {
- credit_card: CreditCardData {
- number: card_data.card_number,
- expiration_year: card_data.card_exp_year,
- expiration_month: card_data.card_exp_month,
- cvv: card_data.card_cvc,
- cardholder_name: item
- .get_optional_billing_full_name()
- .unwrap_or(Secret::new("".to_string())),
- },
- };
- Ok(Self {
- query,
- variables: VariableInput { input },
- })
- }
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("braintree"),
- )
- .into())
- }
- }
- }
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct TokenizePaymentMethodData {
- id: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TokenizeCreditCardData {
- payment_method: TokenizePaymentMethodData,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClientToken {
- client_token: Secret<String>,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TokenizeCreditCard {
- tokenize_credit_card: TokenizeCreditCardData,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClientTokenData {
- create_client_token: ClientToken,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct ClientTokenResponse {
- data: ClientTokenData,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct TokenResponse {
- data: TokenizeCreditCard,
-}
-
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct ErrorResponse {
- errors: Vec<ErrorDetails>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeTokenResponse {
- TokenResponse(Box<TokenResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BraintreeTokenResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<F, BraintreeTokenResponse, T, types::PaymentsResponseData>,
- ) -> Result<Self, Self::Error> {
- Ok(Self {
- response: match item.response {
- BraintreeTokenResponse::ErrorResponse(error_response) => {
- build_error_response(error_response.errors.as_ref(), item.http_code)
- }
-
- BraintreeTokenResponse::TokenResponse(token_response) => {
- Ok(types::PaymentsResponseData::TokenizationResponse {
- token: token_response
- .data
- .tokenize_credit_card
- .payment_method
- .id
- .expose()
- .clone(),
- })
- }
- },
- ..item.data
- })
- }
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CaptureTransactionBody {
- amount: String,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CaptureInputData {
- transaction_id: String,
- transaction: CaptureTransactionBody,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct VariableCaptureInput {
- input: CaptureInputData,
-}
-
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeCaptureRequest {
- query: String,
- variables: VariableCaptureInput,
-}
-
-impl TryFrom<&BraintreeRouterData<&types::PaymentsCaptureRouterData>> for BraintreeCaptureRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &BraintreeRouterData<&types::PaymentsCaptureRouterData>,
- ) -> Result<Self, Self::Error> {
- let query = CAPTURE_TRANSACTION_MUTATION.to_string();
- let variables = VariableCaptureInput {
- input: CaptureInputData {
- transaction_id: item.router_data.request.connector_transaction_id.clone(),
- transaction: CaptureTransactionBody {
- amount: item.amount.to_owned(),
- },
- },
- };
- Ok(Self { query, variables })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CaptureResponseTransactionBody {
- id: String,
- status: BraintreePaymentStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CaptureTransactionData {
- transaction: CaptureResponseTransactionBody,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CaptureResponseData {
- capture_transaction: CaptureTransactionData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CaptureResponse {
- data: CaptureResponseData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeCaptureResponse {
- CaptureResponse(Box<CaptureResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl TryFrom<types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>>
- for types::PaymentsCaptureRouterData
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeCaptureResponse::CaptureResponse(capture_data) => {
- let transaction_data = capture_data.data.capture_transaction.transaction;
-
- Ok(Self {
- status: enums::AttemptStatus::from(transaction_data.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- BraintreeCaptureResponse::ErrorResponse(error_data) => Ok(Self {
- response: build_error_response(&error_data.errors, item.http_code),
- ..item.data
- }),
- }
- }
-}
-
-#[derive(Debug, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CancelInputData {
- transaction_id: String,
-}
-
-#[derive(Debug, Serialize)]
-pub struct VariableCancelInput {
- input: CancelInputData,
-}
-
-#[derive(Debug, Serialize)]
-pub struct BraintreeCancelRequest {
- query: String,
- variables: VariableCancelInput,
-}
-
-impl TryFrom<&types::PaymentsCancelRouterData> for BraintreeCancelRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
- let query = VOID_TRANSACTION_MUTATION.to_string();
- let variables = VariableCancelInput {
- input: CancelInputData {
- transaction_id: item.request.connector_transaction_id.clone(),
- },
- };
- Ok(Self { query, variables })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CancelResponseTransactionBody {
- id: String,
- status: BraintreePaymentStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CancelTransactionData {
- reversal: CancelResponseTransactionBody,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CancelResponseData {
- reverse_transaction: CancelTransactionData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct CancelResponse {
- data: CancelResponseData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreeCancelResponse {
- CancelResponse(Box<CancelResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BraintreeCancelResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<F, BraintreeCancelResponse, T, types::PaymentsResponseData>,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreeCancelResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreeCancelResponse::CancelResponse(void_response) => {
- let void_data = void_response.data.reverse_transaction.reversal;
-
- let transaction_id = void_data.id;
- Ok(Self {
- status: enums::AttemptStatus::from(void_data.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(transaction_id),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- }
- }
-}
-
-#[derive(Debug, Serialize)]
-pub struct BraintreePSyncRequest {
- query: String,
-}
-
-impl TryFrom<&types::PaymentsSyncRouterData> for BraintreePSyncRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
- let transaction_id = item
- .request
- .connector_transaction_id
- .get_connector_transaction_id()
- .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
- let query = format!("query {{ search {{ transactions(input: {{ id: {{is: \"{}\"}} }}, first: 1) {{ edges {{ node {{ id status createdAt amount {{ value currencyCode }} orderId }} }} }} }} }}", transaction_id);
- Ok(Self { query })
- }
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct NodeData {
- id: String,
- status: BraintreePaymentStatus,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct EdgeData {
- node: NodeData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct TransactionData {
- edges: Vec<EdgeData>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct SearchData {
- transactions: TransactionData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct PSyncResponseData {
- search: SearchData,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum BraintreePSyncResponse {
- PSyncResponse(Box<PSyncResponse>),
- ErrorResponse(Box<ErrorResponse>),
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct PSyncResponse {
- data: PSyncResponseData,
-}
-
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BraintreePSyncResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<F, BraintreePSyncResponse, T, types::PaymentsResponseData>,
- ) -> Result<Self, Self::Error> {
- match item.response {
- BraintreePSyncResponse::ErrorResponse(error_response) => Ok(Self {
- response: build_error_response(&error_response.errors, item.http_code),
- ..item.data
- }),
- BraintreePSyncResponse::PSyncResponse(psync_response) => {
- let edge_data = psync_response
- .data
- .search
- .transactions
- .edges
- .first()
- .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
- let transaction_id = &edge_data.node.id;
- Ok(Self {
- status: enums::AttemptStatus::from(edge_data.node.status.clone()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- transaction_id.to_string(),
- ),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: None,
- incremental_authorization_allowed: None,
- charge_id: None,
- }),
- ..item.data
- })
- }
- }
- }
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeThreeDsResponse {
- pub nonce: Secret<String>,
- pub liability_shifted: bool,
- pub liability_shift_possible: bool,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeThreeDsErrorResponse {
- pub code: String,
- pub message: String,
-}
-
-#[derive(Debug, Deserialize)]
-pub struct BraintreeRedirectionResponse {
- pub authentication_response: String,
-}
-
-impl TryFrom<BraintreeMeta> for BraintreeClientTokenRequest {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(metadata: BraintreeMeta) -> Result<Self, Self::Error> {
- Ok(Self {
- query: CLIENT_TOKEN_MUTATION.to_owned(),
- variables: VariableClientTokenInput {
- input: InputClientTokenData {
- client_token: ClientTokenInput {
- merchant_account_id: metadata.merchant_account_id,
- },
- },
- },
- })
- }
-}
-
-impl
- TryFrom<(
- &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- BraintreeMeta,
- )> for CardPaymentRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- (item, metadata): (
- &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
- BraintreeMeta,
- ),
- ) -> Result<Self, Self::Error> {
- let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
- (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
- false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Vault(VaultTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- vault_payment_method_after_transacting: TransactionTiming {
- when: "ALWAYS".to_string(),
- },
- }),
- )
- } else {
- (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
- false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Regular(RegularTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- }),
- )
- };
- Ok(Self {
- query,
- variables: VariablePaymentInput {
- input: PaymentInput {
- payment_method_id: match item.router_data.get_payment_method_token()? {
- types::PaymentMethodToken::Token(token) => token,
- types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
- unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"),
- )?,
- },
- transaction: transaction_body,
- },
- },
- })
- }
-}
-
-impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
- for CardPaymentRequest
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
- ) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConnectorConfig {
- config: "metadata",
- })?;
- utils::validate_currency(
- item.router_data.request.currency,
- Some(metadata.merchant_config_currency),
- )?;
- let payload_data = PaymentsCompleteAuthorizeRequestData::get_redirect_response_payload(
- &item.router_data.request,
- )?
- .expose();
- let redirection_response: BraintreeRedirectionResponse = serde_json::from_value(
- payload_data,
- )
- .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
- field_name: "redirection_response",
- })?;
- let three_ds_data = serde_json::from_str::<BraintreeThreeDsResponse>(
- &redirection_response.authentication_response,
- )
- .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
- field_name: "three_ds_data",
- })?;
-
- let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
- (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
- false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Vault(VaultTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- vault_payment_method_after_transacting: TransactionTiming {
- when: "ALWAYS".to_string(),
- },
- }),
- )
- } else {
- (
- match item.router_data.request.is_auto_capture()? {
- true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
- false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
- },
- TransactionBody::Regular(RegularTransactionBody {
- amount: item.amount.to_owned(),
- merchant_account_id: metadata.merchant_account_id,
- }),
- )
- };
- Ok(Self {
- query,
- variables: VariablePaymentInput {
- input: PaymentInput {
- payment_method_id: three_ds_data.nonce,
- transaction: transaction_body,
- },
- },
- })
- }
-}
-
-fn get_braintree_redirect_form(
- client_token_data: ClientTokenResponse,
- payment_method_token: types::PaymentMethodToken,
- card_details: domain::PaymentMethodData,
-) -> Result<services::RedirectForm, error_stack::Report<errors::ConnectorError>> {
- Ok(services::RedirectForm::Braintree {
- client_token: client_token_data
- .data
- .create_client_token
- .client_token
- .expose(),
- card_token: match payment_method_token {
- types::PaymentMethodToken::Token(token) => token.expose(),
- types::PaymentMethodToken::ApplePayDecrypt(_) => Err(unimplemented_payment_method!(
- "Apple Pay",
- "Simplified",
- "Braintree"
- ))?,
- },
- bin: match card_details {
- domain::PaymentMethodData::Card(card_details) => {
- card_details.card_number.get_card_isin()
- }
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_) => Err(
- errors::ConnectorError::NotImplemented("given payment method".to_owned()),
- )?,
- },
- })
-}
-
-#[derive(Debug, Deserialize)]
-pub struct BraintreeWebhookResponse {
- pub bt_signature: String,
- pub bt_payload: String,
-}
-
-#[derive(Debug, Deserialize, Serialize)]
-#[serde(rename_all = "kebab-case")]
-pub struct Notification {
- pub kind: String, // xml parse only string to fields
- pub timestamp: String,
- pub dispute: Option<BraintreeDisputeData>,
-}
-impl types::transformers::ForeignFrom<&str> for api_models::webhooks::IncomingWebhookEvent {
- fn foreign_from(status: &str) -> Self {
- match status {
- "dispute_opened" => Self::DisputeOpened,
- "dispute_lost" => Self::DisputeLost,
- "dispute_won" => Self::DisputeWon,
- "dispute_accepted" | "dispute_auto_accepted" => Self::DisputeAccepted,
- "dispute_expired" => Self::DisputeExpired,
- "dispute_disputed" => Self::DisputeChallenged,
- _ => Self::EventNotSupported,
- }
- }
-}
-
-#[derive(Debug, Deserialize, Serialize)]
-pub struct BraintreeDisputeData {
- pub amount_disputed: i64,
- pub amount_won: Option<String>,
- pub case_number: Option<String>,
- pub chargeback_protection_level: Option<String>,
- pub currency_iso_code: String,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub created_at: Option<PrimitiveDateTime>,
- pub evidence: Option<DisputeEvidence>,
- pub id: String,
- pub kind: String, // xml parse only string to fields
- pub status: String,
- pub reason: Option<String>,
- pub reason_code: Option<String>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub updated_at: Option<PrimitiveDateTime>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub reply_by_date: Option<PrimitiveDateTime>,
- pub transaction: DisputeTransaction,
-}
-
-#[derive(Debug, Deserialize, Serialize)]
-pub struct DisputeTransaction {
- pub amount: String,
- pub id: String,
-}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct DisputeEvidence {
- pub comment: String,
- pub id: Secret<String>,
- pub created_at: Option<PrimitiveDateTime>,
- pub url: url::Url,
-}
-
-pub(crate) fn get_dispute_stage(code: &str) -> Result<enums::DisputeStage, errors::ConnectorError> {
- match code {
- "CHARGEBACK" => Ok(enums::DisputeStage::Dispute),
- "PRE_ARBITATION" => Ok(enums::DisputeStage::PreArbitration),
- "RETRIEVAL" => Ok(enums::DisputeStage::PreDispute),
- _ => Err(errors::ConnectorError::WebhookBodyDecodingFailed),
- }
-}
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index 717c4afc195..8a4ce8126dd 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -1,175 +1,308 @@
-use api_models::payments;
-use base64::Engine;
-use masking::{ExposeInterface, PeekInterface, Secret};
+use common_utils::{pii, types::StringMajorUnit};
+use error_stack::ResultExt;
+use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
+use time::PrimitiveDateTime;
use crate::{
- connector::utils::{self},
+ connector::utils::{
+ self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
+ RefundsRequestData, RouterData,
+ },
consts,
core::errors,
- types::{self, api, domain, storage::enums},
+ services,
+ types::{self, api, domain, storage::enums, MandateReference},
+ unimplemented_payment_method,
};
+pub const CHANNEL_CODE: &str = "HyperSwitchBT_Ecom";
+pub const CLIENT_TOKEN_MUTATION: &str = "mutation createClientToken($input: CreateClientTokenInput!) { createClientToken(input: $input) { clientToken}}";
+pub const TOKENIZE_CREDIT_CARD: &str = "mutation tokenizeCreditCard($input: TokenizeCreditCardInput!) { tokenizeCreditCard(input: $input) { clientMutationId paymentMethod { id } } }";
+pub const CHARGE_CREDIT_CARD_MUTATION: &str = "mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id legacyId createdAt amount { value currencyCode } status } } }";
+pub const AUTHORIZE_CREDIT_CARD_MUTATION: &str = "mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id legacyId amount { value currencyCode } status } } }";
+pub const CAPTURE_TRANSACTION_MUTATION: &str = "mutation captureTransaction($input: CaptureTransactionInput!) { captureTransaction(input: $input) { clientMutationId transaction { id legacyId amount { value currencyCode } status } } }";
+pub const VOID_TRANSACTION_MUTATION: &str = "mutation voidTransaction($input: ReverseTransactionInput!) { reverseTransaction(input: $input) { clientMutationId reversal { ... on Transaction { id legacyId amount { value currencyCode } status } } } }";
+pub const REFUND_TRANSACTION_MUTATION: &str = "mutation refundTransaction($input: RefundTransactionInput!) { refundTransaction(input: $input) {clientMutationId refund { id legacyId amount { value currencyCode } status } } }";
+pub const AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION: &str="mutation authorizeCreditCard($input: AuthorizeCreditCardInput!) { authorizeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
+pub const CHARGE_AND_VAULT_TRANSACTION_MUTATION: &str ="mutation ChargeCreditCard($input: ChargeCreditCardInput!) { chargeCreditCard(input: $input) { transaction { id status createdAt paymentMethod { id } } } }";
+pub const TRANSACTION_QUERY: &str = "query($input: TransactionSearchInput!) { search { transactions(input: $input) { edges { node { id status } } } } }";
+pub const REFUND_QUERY: &str = "query($input: RefundSearchInput!) { search { refunds(input: $input, first: 1) { edges { node { id status createdAt amount { value currencyCode } orderId } } } } }";
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct DeviceData;
+pub type CardPaymentRequest = GenericBraintreeRequest<VariablePaymentInput>;
+pub type MandatePaymentRequest = GenericBraintreeRequest<VariablePaymentInput>;
+pub type BraintreeClientTokenRequest = GenericBraintreeRequest<VariableClientTokenInput>;
+pub type BraintreeTokenRequest = GenericBraintreeRequest<VariableInput>;
+pub type BraintreeCaptureRequest = GenericBraintreeRequest<VariableCaptureInput>;
+pub type BraintreeRefundRequest = GenericBraintreeRequest<BraintreeRefundVariables>;
+pub type BraintreePSyncRequest = GenericBraintreeRequest<PSyncInput>;
+pub type BraintreeRSyncRequest = GenericBraintreeRequest<RSyncInput>;
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct PaymentOptions {
- submit_for_settlement: bool,
+pub type BraintreeRefundResponse = GenericBraintreeResponse<RefundResponse>;
+pub type BraintreeCaptureResponse = GenericBraintreeResponse<CaptureResponse>;
+pub type BraintreePSyncResponse = GenericBraintreeResponse<PSyncResponse>;
+
+pub type VariablePaymentInput = GenericVariableInput<PaymentInput>;
+pub type VariableClientTokenInput = GenericVariableInput<InputClientTokenData>;
+pub type VariableInput = GenericVariableInput<InputData>;
+pub type VariableCaptureInput = GenericVariableInput<CaptureInputData>;
+pub type BraintreeRefundVariables = GenericVariableInput<BraintreeRefundInput>;
+pub type PSyncInput = GenericVariableInput<TransactionSearchInput>;
+pub type RSyncInput = GenericVariableInput<RefundSearchInput>;
+
+#[derive(Debug, Clone, Serialize)]
+pub struct GenericBraintreeRequest<T> {
+ query: String,
+ variables: T,
+}
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum GenericBraintreeResponse<T> {
+ SuccessResponse(Box<T>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+#[derive(Debug, Clone, Serialize)]
+pub struct GenericVariableInput<T> {
+ input: T,
}
-#[derive(Debug, Deserialize)]
-pub struct BraintreeMeta {
- merchant_account_id: Option<Secret<String>>,
- merchant_config_currency: Option<enums::Currency>,
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+
+pub struct BraintreeApiErrorResponse {
+ pub api_error_response: ApiErrorResponse,
}
-#[derive(Debug, Serialize, Eq, PartialEq)]
-pub struct BraintreePaymentsRequest {
- transaction: TransactionBody,
+#[derive(Debug, Deserialize, Serialize)]
+
+pub struct ErrorsObject {
+ pub errors: Vec<ErrorObject>,
+
+ pub transaction: Option<TransactionError>,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct BraintreeApiVersion {
- version: String,
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+
+pub struct TransactionError {
+ pub errors: Vec<ErrorObject>,
+ pub credit_card: Option<CreditCardError>,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct BraintreeSessionRequest {
- client_token: BraintreeApiVersion,
+#[derive(Debug, Deserialize, Serialize)]
+pub struct CreditCardError {
+ pub errors: Vec<ErrorObject>,
+}
+#[derive(Debug, Serialize)]
+pub struct BraintreeRouterData<T> {
+ pub amount: StringMajorUnit,
+ pub router_data: T,
}
-impl TryFrom<&types::PaymentsSessionRouterData> for BraintreeSessionRequest {
+impl<T> TryFrom<(StringMajorUnit, T)> for BraintreeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(_item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(_item.connector_meta_data.clone())?;
-
- utils::validate_currency(_item.request.currency, metadata.merchant_config_currency)?;
+ fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
- client_token: BraintreeApiVersion {
- version: "2".to_string(),
- },
+ amount,
+ router_data: item,
})
}
}
+#[derive(Debug, Deserialize, Serialize)]
+pub struct ErrorObject {
+ pub code: String,
+ pub message: String,
+}
-#[derive(Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct TransactionBody {
- amount: String,
- merchant_account_id: Option<Secret<String>>,
- device_data: DeviceData,
- options: PaymentOptions,
- #[serde(flatten)]
- payment_method_data_type: PaymentMethodType,
- #[serde(rename = "type")]
- kind: String,
-}
-
-#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct BraintreeErrorResponse {
+ pub errors: String,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
-#[serde(tag = "type")]
-pub enum PaymentMethodType {
- CreditCard(Card),
- PaymentMethodNonce(Nonce),
+#[serde(untagged)]
+
+pub enum ErrorResponses {
+ BraintreeApiErrorResponse(Box<BraintreeApiErrorResponse>),
+ BraintreeErrorResponse(Box<BraintreeErrorResponse>),
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct Nonce {
- payment_method_nonce: Secret<String>,
+#[derive(Debug, Deserialize, Serialize)]
+pub struct ApiErrorResponse {
+ pub message: String,
+ pub errors: ErrorsObject,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-#[serde(rename_all = "camelCase")]
-pub struct Card {
- credit_card: CardDetails,
+pub struct BraintreeAuthType {
+ pub(super) public_key: Secret<String>,
+ pub(super) private_key: Secret<String>,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let types::ConnectorAuthType::SignatureKey {
+ api_key,
+ api_secret,
+ key1: _merchant_id,
+ } = item
+ {
+ Ok(Self {
+ public_key: api_key.to_owned(),
+ private_key: api_secret.to_owned(),
+ })
+ } else {
+ Err(errors::ConnectorError::FailedToObtainAuthType)?
+ }
+ }
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct CardDetails {
- number: cards::CardNumber,
- expiration_month: Secret<String>,
- expiration_year: Secret<String>,
- cvv: Secret<String>,
+pub struct PaymentInput {
+ payment_method_id: Secret<String>,
+ transaction: TransactionBody,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(untagged)]
+pub enum BraintreePaymentsRequest {
+ Card(CardPaymentRequest),
+ CardThreeDs(BraintreeClientTokenRequest),
+ Mandate(MandatePaymentRequest),
+}
+
+#[derive(Debug, Deserialize)]
+pub struct BraintreeMeta {
+ merchant_account_id: Secret<String>,
+ merchant_config_currency: enums::Currency,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest {
+impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.connector_meta_data.clone())?;
+ fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
+ let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+ Ok(metadata)
+ }
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RegularTransactionBody {
+ amount: StringMajorUnit,
+ merchant_account_id: Secret<String>,
+ channel: String,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultTransactionBody {
+ amount: StringMajorUnit,
+ merchant_account_id: Secret<String>,
+ vault_payment_method_after_transacting: TransactionTiming,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(untagged)]
+pub enum TransactionBody {
+ Regular(RegularTransactionBody),
+ Vault(VaultTransactionBody),
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TransactionTiming {
+ when: String,
+}
- utils::validate_currency(item.request.currency, metadata.merchant_config_currency)?;
- let submit_for_settlement = matches!(
- item.request.capture_method,
- Some(enums::CaptureMethod::Automatic) | None
+impl
+ TryFrom<(
+ &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ String,
+ BraintreeMeta,
+ )> for MandatePaymentRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, connector_mandate_id, metadata): (
+ &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ String,
+ BraintreeMeta,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (query, transaction_body) = (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
+ false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Regular(RegularTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ channel: CHANNEL_CODE.to_string(),
+ }),
);
- let merchant_account_id = metadata.merchant_account_id;
- let amount = utils::to_currency_base_unit(item.request.amount, item.request.currency)?;
- let device_data = DeviceData {};
- let options = PaymentOptions {
- submit_for_settlement,
- };
- let kind = "sale".to_string();
-
- let payment_method_data_type = match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => Ok(PaymentMethodType::CreditCard(Card {
- credit_card: CardDetails {
- number: ccard.card_number,
- expiration_month: ccard.card_exp_month,
- expiration_year: ccard.card_exp_year,
- cvv: ccard.card_cvc,
+ Ok(Self {
+ query,
+ variables: VariablePaymentInput {
+ input: PaymentInput {
+ payment_method_id: connector_mandate_id.into(),
+ transaction: transaction_body,
},
- })),
- domain::PaymentMethodData::Wallet(ref wallet_data) => {
- Ok(PaymentMethodType::PaymentMethodNonce(Nonce {
- payment_method_nonce: match wallet_data {
- domain::WalletData::PaypalSdk(wallet_data) => {
- Ok(wallet_data.token.to_owned())
- }
- domain::WalletData::ApplePay(_)
- | domain::WalletData::GooglePay(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalRedirect(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::Mifinity(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("braintree"),
- ))
- }
- }?
- .into(),
- }))
+ },
+ })
+ }
+}
+
+impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>>
+ for BraintreePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let metadata: BraintreeMeta =
+ utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+ utils::validate_currency(
+ item.router_data.request.currency,
+ Some(metadata.merchant_config_currency),
+ )?;
+ match item.router_data.request.payment_method_data.clone() {
+ domain::PaymentMethodData::Card(_) => {
+ if item.router_data.is_three_ds() {
+ Ok(Self::CardThreeDs(BraintreeClientTokenRequest::try_from(
+ metadata,
+ )?))
+ } else {
+ Ok(Self::Card(CardPaymentRequest::try_from((item, metadata))?))
+ }
+ }
+ domain::PaymentMethodData::MandatePayment => {
+ let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_mandate_id",
+ },
+ )?;
+ Ok(Self::Mandate(MandatePaymentRequest::try_from((
+ item,
+ connector_mandate_id,
+ metadata,
+ ))?))
}
- domain::PaymentMethodData::PayLater(_)
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
| domain::PaymentMethodData::BankRedirect(_)
| domain::PaymentMethodData::BankDebit(_)
| domain::PaymentMethodData::BankTransfer(_)
| domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::MandatePayment
| domain::PaymentMethodData::Reward
| domain::PaymentMethodData::RealTimePayment(_)
| domain::PaymentMethodData::Upi(_)
@@ -179,74 +312,253 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BraintreePaymentsRequest {
| domain::PaymentMethodData::CardToken(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("braintree"),
- ))
+ )
+ .into())
}
- }?;
- let braintree_transaction_body = TransactionBody {
- amount,
- merchant_account_id,
- device_data,
- options,
- payment_method_data_type,
- kind,
- };
- Ok(Self {
- transaction: braintree_transaction_body,
- })
+ }
}
}
-pub struct BraintreeAuthType {
- pub(super) auth_header: String,
- pub(super) merchant_id: Secret<String>,
+impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
+ for BraintreePaymentsRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.payment_method {
+ api_models::enums::PaymentMethod::Card => {
+ Ok(Self::Card(CardPaymentRequest::try_from(item)?))
+ }
+ api_models::enums::PaymentMethod::CardRedirect
+ | api_models::enums::PaymentMethod::PayLater
+ | api_models::enums::PaymentMethod::Wallet
+ | api_models::enums::PaymentMethod::BankRedirect
+ | api_models::enums::PaymentMethod::BankTransfer
+ | api_models::enums::PaymentMethod::Crypto
+ | api_models::enums::PaymentMethod::BankDebit
+ | api_models::enums::PaymentMethod::Reward
+ | api_models::enums::PaymentMethod::RealTimePayment
+ | api_models::enums::PaymentMethod::Upi
+ | api_models::enums::PaymentMethod::OpenBanking
+ | api_models::enums::PaymentMethod::Voucher
+ | api_models::enums::PaymentMethod::GiftCard => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message(
+ "complete authorize flow",
+ ),
+ )
+ .into())
+ }
+ }
+ }
}
-impl TryFrom<&types::ConnectorAuthType> for BraintreeAuthType {
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct AuthResponse {
+ data: DataAuthResponse,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeAuthResponse {
+ AuthResponse(Box<AuthResponse>),
+ ClientTokenResponse(Box<ClientTokenResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeCompleteAuthResponse {
+ AuthResponse(Box<AuthResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+struct PaymentMethodInfo {
+ id: Secret<String>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TransactionAuthChargeResponseBody {
+ id: String,
+ status: BraintreePaymentStatus,
+ payment_method: Option<PaymentMethodInfo>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DataAuthResponse {
+ authorize_credit_card: AuthChargeCreditCard,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct AuthChargeCreditCard {
+ transaction: TransactionAuthChargeResponseBody,
+}
+
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BraintreeAuthResponse,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::SignatureKey {
- api_key: public_key,
- key1: merchant_id,
- api_secret: private_key,
- } = item
- {
- let auth_key = format!("{}:{}", public_key.peek(), private_key.peek());
- let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
- Ok(Self {
- auth_header,
- merchant_id: merchant_id.to_owned(),
- })
- } else {
- Err(errors::ConnectorError::FailedToObtainAuthType)?
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BraintreeAuthResponse,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeAuthResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
+ }),
+ BraintreeAuthResponse::AuthResponse(auth_response) => {
+ let transaction_data = auth_response.data.authorize_credit_card.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
+ MandateReference {
+ connector_mandate_id: Some(pm.id.clone().expose()),
+ payment_method_id: None,
+ }
+ }),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ BraintreeAuthResponse::ClientTokenResponse(client_token_data) => Ok(Self {
+ status: enums::AttemptStatus::AuthenticationPending,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::NoResponseId,
+ redirection_data: Some(get_braintree_redirect_form(
+ *client_token_data,
+ item.data.get_payment_method_token()?,
+ item.data.request.payment_method_data.clone(),
+ )?),
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ }),
}
}
}
-#[derive(Debug, Default, Clone, Deserialize, Eq, PartialEq, Serialize)]
-#[serde(rename_all = "snake_case")]
+fn build_error_response<T>(
+ response: &[ErrorDetails],
+ http_code: u16,
+) -> Result<T, types::ErrorResponse> {
+ let error_messages = response
+ .iter()
+ .map(|error| error.message.to_string())
+ .collect::<Vec<String>>();
+
+ let reason = match !error_messages.is_empty() {
+ true => Some(error_messages.join(" ")),
+ false => None,
+ };
+
+ get_error_response(
+ response
+ .first()
+ .and_then(|err_details| err_details.extensions.as_ref())
+ .and_then(|extensions| extensions.legacy_code.clone()),
+ response
+ .first()
+ .map(|err_details| err_details.message.clone()),
+ reason,
+ http_code,
+ )
+}
+
+fn get_error_response<T>(
+ error_code: Option<String>,
+ error_msg: Option<String>,
+ error_reason: Option<String>,
+ http_code: u16,
+) -> Result<T, types::ErrorResponse> {
+ Err(types::ErrorResponse {
+ code: error_code.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
+ message: error_msg.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
+ reason: error_reason,
+ status_code: http_code,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, strum::Display)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BraintreePaymentStatus {
- Succeeded,
- Failed,
Authorized,
+ Authorizing,
AuthorizedExpired,
+ Failed,
ProcessorDeclined,
GatewayRejected,
Voided,
- SubmittedForSettlement,
- #[default]
Settling,
Settled,
SettlementPending,
SettlementDeclined,
SettlementConfirmed,
+ SubmittedForSettlement,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct ErrorDetails {
+ pub message: String,
+ pub extensions: Option<AdditionalErrorDetails>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AdditionalErrorDetails {
+ pub legacy_code: Option<String>,
}
impl From<BraintreePaymentStatus> for enums::AttemptStatus {
fn from(item: BraintreePaymentStatus) -> Self {
match item {
- BraintreePaymentStatus::Succeeded
- | BraintreePaymentStatus::Settling
- | BraintreePaymentStatus::Settled => Self::Charged,
+ BraintreePaymentStatus::Settling
+ | BraintreePaymentStatus::Settled
+ | BraintreePaymentStatus::SettlementConfirmed => Self::Charged,
+ BraintreePaymentStatus::Authorizing => Self::Authorizing,
BraintreePaymentStatus::AuthorizedExpired => Self::AuthorizationFailed,
BraintreePaymentStatus::Failed
| BraintreePaymentStatus::GatewayRejected
@@ -255,234 +567,1221 @@ impl From<BraintreePaymentStatus> for enums::AttemptStatus {
BraintreePaymentStatus::Authorized => Self::Authorized,
BraintreePaymentStatus::Voided => Self::Voided,
BraintreePaymentStatus::SubmittedForSettlement
- | BraintreePaymentStatus::SettlementPending
- | BraintreePaymentStatus::SettlementConfirmed => Self::Pending,
+ | BraintreePaymentStatus::SettlementPending => Self::Pending,
}
}
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, BraintreePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BraintreePaymentsResponse,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
BraintreePaymentsResponse,
- T,
+ types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- let id = item.response.transaction.id.clone();
- Ok(Self {
- status: enums::AttemptStatus::from(item.response.transaction.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(id.clone()),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: Some(id),
- incremental_authorization_allowed: None,
- charge_id: None,
+ match item.response {
+ BraintreePaymentsResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors.clone(), item.http_code),
+ ..item.data
}),
- ..item.data
- })
+ BraintreePaymentsResponse::PaymentsResponse(payment_response) => {
+ let transaction_data = payment_response.data.charge_credit_card.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
+ MandateReference {
+ connector_mandate_id: Some(pm.id.clone().expose()),
+ payment_method_id: None,
+ }
+ }),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ BraintreePaymentsResponse::ClientTokenResponse(client_token_data) => Ok(Self {
+ status: enums::AttemptStatus::AuthenticationPending,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::NoResponseId,
+ redirection_data: Some(get_braintree_redirect_form(
+ *client_token_data,
+ item.data.get_payment_method_token()?,
+ item.data.request.payment_method_data.clone(),
+ )?),
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ }),
+ }
}
}
-impl<F, T>
+impl<F>
TryFrom<
- types::ResponseRouterData<F, BraintreeSessionTokenResponse, T, types::PaymentsResponseData>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+ types::ResponseRouterData<
+ F,
+ BraintreeCompleteChargeResponse,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
- BraintreeSessionTokenResponse,
- T,
+ BraintreeCompleteChargeResponse,
+ types::CompleteAuthorizeData,
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
- Ok(Self {
- response: Ok(types::PaymentsResponseData::SessionResponse {
- session_token: api::SessionToken::Paypal(Box::new(
- payments::PaypalSessionTokenResponse {
- session_token: item.response.client_token.value.expose(),
- connector: "braintree".to_string(),
- sdk_next_action: payments::SdkNextAction {
- next_action: payments::NextActionCall::Confirm,
- },
- },
- )),
+ match item.response {
+ BraintreeCompleteChargeResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors.clone(), item.http_code),
+ ..item.data
}),
- ..item.data
- })
+ BraintreeCompleteChargeResponse::PaymentsResponse(payment_response) => {
+ let transaction_data = payment_response.data.charge_credit_card.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
+ MandateReference {
+ connector_mandate_id: Some(pm.id.clone().expose()),
+ payment_method_id: None,
+ }
+ }),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ }
}
}
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreePaymentsResponse {
- transaction: TransactionResponse,
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BraintreeCompleteAuthResponse,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BraintreeCompleteAuthResponse,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeCompleteAuthResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
+ }),
+ BraintreeCompleteAuthResponse::AuthResponse(auth_response) => {
+ let transaction_data = auth_response.data.authorize_credit_card.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: transaction_data.payment_method.as_ref().map(|pm| {
+ MandateReference {
+ connector_mandate_id: Some(pm.id.clone().expose()),
+ payment_method_id: None,
+ }
+ }),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ }
+ }
}
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClientToken {
- pub value: Secret<String>,
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct PaymentsResponse {
+ data: DataResponse,
}
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeSessionTokenResponse {
- pub client_token: ClientToken,
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreePaymentsResponse {
+ PaymentsResponse(Box<PaymentsResponse>),
+ ClientTokenResponse(Box<ClientTokenResponse>),
+ ErrorResponse(Box<ErrorResponse>),
}
-#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq, Serialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeCompleteChargeResponse {
+ PaymentsResponse(Box<PaymentsResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct TransactionResponse {
- id: String,
- currency_iso_code: String,
- amount: String,
- status: BraintreePaymentStatus,
+pub struct DataResponse {
+ charge_credit_card: AuthChargeCreditCard,
}
-#[derive(Debug, Deserialize, Serialize)]
+#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct BraintreeApiErrorResponse {
- pub api_error_response: ApiErrorResponse,
+pub struct RefundInputData {
+ amount: StringMajorUnit,
+ merchant_account_id: Secret<String>,
+}
+#[derive(Serialize, Debug, Clone)]
+struct IdFilter {
+ is: String,
}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct ErrorsObject {
- pub errors: Vec<ErrorObject>,
- pub transaction: Option<TransactionError>,
+#[derive(Debug, Clone, Serialize)]
+pub struct TransactionSearchInput {
+ id: IdFilter,
}
-#[derive(Debug, Deserialize, Serialize)]
+#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct TransactionError {
- pub errors: Vec<ErrorObject>,
- pub credit_card: Option<CreditCardError>,
+pub struct BraintreeRefundInput {
+ transaction_id: String,
+ refund: RefundInputData,
}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct CreditCardError {
- pub errors: Vec<ErrorObject>,
+impl<F> TryFrom<BraintreeRouterData<&types::RefundsRouterData<F>>> for BraintreeRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: BraintreeRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
+ let metadata: BraintreeMeta =
+ utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+
+ utils::validate_currency(
+ item.router_data.request.currency,
+ Some(metadata.merchant_config_currency),
+ )?;
+ let query = REFUND_TRANSACTION_MUTATION.to_string();
+ let variables = BraintreeRefundVariables {
+ input: BraintreeRefundInput {
+ transaction_id: item.router_data.request.connector_transaction_id.clone(),
+ refund: RefundInputData {
+ amount: item.amount,
+ merchant_account_id: metadata.merchant_account_id,
+ },
+ },
+ };
+ Ok(Self { query, variables })
+ }
}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct ErrorObject {
- pub code: String,
- pub message: String,
+#[derive(Debug, Clone, Deserialize, Serialize, strum::Display)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum BraintreeRefundStatus {
+ SettlementPending,
+ Settling,
+ Settled,
+ SubmittedForSettlement,
+ Failed,
}
-#[derive(Debug, Default, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BraintreeErrorResponse {
- pub errors: String,
+impl From<BraintreeRefundStatus> for enums::RefundStatus {
+ fn from(item: BraintreeRefundStatus) -> Self {
+ match item {
+ BraintreeRefundStatus::Settled | BraintreeRefundStatus::Settling => Self::Success,
+ BraintreeRefundStatus::SubmittedForSettlement
+ | BraintreeRefundStatus::SettlementPending => Self::Pending,
+ BraintreeRefundStatus::Failed => Self::Failure,
+ }
+ }
}
-#[derive(Debug, Deserialize, Serialize)]
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct BraintreeRefundTransactionBody {
+ pub id: String,
+ pub status: BraintreeRefundStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct BraintreeRefundTransaction {
+ pub refund: BraintreeRefundTransactionBody,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
+pub struct BraintreeRefundResponseData {
+ pub refund_transaction: BraintreeRefundTransaction,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+
+pub struct RefundResponse {
+ pub data: BraintreeRefundResponseData,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, BraintreeRefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, BraintreeRefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: match item.response {
+ BraintreeRefundResponse::ErrorResponse(error_response) => {
+ build_error_response(&error_response.errors, item.http_code)
+ }
+ BraintreeRefundResponse::SuccessResponse(refund_data) => {
+ let refund_data = refund_data.data.refund_transaction.refund;
+ let refund_status = enums::RefundStatus::from(refund_data.status.clone());
+ if utils::is_refund_failure(refund_status) {
+ Err(types::ErrorResponse {
+ code: refund_data.status.to_string().clone(),
+ message: refund_data.status.to_string().clone(),
+ reason: Some(refund_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(refund_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::RefundsResponseData {
+ connector_refund_id: refund_data.id.clone(),
+ refund_status,
+ })
+ }
+ }
+ },
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct RefundSearchInput {
+ id: IdFilter,
+}
+impl TryFrom<&types::RefundSyncRouterData> for BraintreeRSyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
+ let metadata: BraintreeMeta = utils::to_connector_meta_from_secret(
+ item.connector_meta_data.clone(),
+ )
+ .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
+ utils::validate_currency(
+ item.request.currency,
+ Some(metadata.merchant_config_currency),
+ )?;
+ let refund_id = item.request.get_connector_refund_id()?;
+ Ok(Self {
+ query: REFUND_QUERY.to_string(),
+ variables: RSyncInput {
+ input: RefundSearchInput {
+ id: IdFilter { is: refund_id },
+ },
+ },
+ })
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncNodeData {
+ id: String,
+ status: BraintreeRefundStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncEdgeData {
+ node: RSyncNodeData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RefundData {
+ edges: Vec<RSyncEdgeData>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncSearchData {
+ refunds: RefundData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncResponseData {
+ search: RSyncSearchData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct RSyncResponse {
+ data: RSyncResponseData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
+pub enum BraintreeRSyncResponse {
+ RSyncResponse(Box<RSyncResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
-pub enum ErrorResponse {
- BraintreeApiErrorResponse(Box<BraintreeApiErrorResponse>),
- BraintreeErrorResponse(Box<BraintreeErrorResponse>),
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, BraintreeRSyncResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, BraintreeRSyncResponse>,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeRSyncResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
+ }),
+ BraintreeRSyncResponse::RSyncResponse(rsync_response) => {
+ let edge_data = rsync_response
+ .data
+ .search
+ .refunds
+ .edges
+ .first()
+ .ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
+ let connector_refund_id = &edge_data.node.id;
+ let response = Ok(types::RefundsResponseData {
+ connector_refund_id: connector_refund_id.to_string(),
+ refund_status: enums::RefundStatus::from(edge_data.node.status.clone()),
+ });
+ Ok(Self {
+ response,
+ ..item.data
+ })
+ }
+ }
+ }
}
-#[derive(Debug, Deserialize, Serialize)]
-pub struct ApiErrorResponse {
- pub message: String,
- pub errors: ErrorsObject,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CreditCardData {
+ number: cards::CardNumber,
+ expiration_year: Secret<String>,
+ expiration_month: Secret<String>,
+ cvv: Secret<String>,
+ cardholder_name: Secret<String>,
}
-#[derive(Default, Debug, Clone, Serialize)]
-pub struct BraintreeRefundRequest {
- transaction: Amount,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ClientTokenInput {
+ merchant_account_id: Secret<String>,
}
-#[derive(Default, Debug, Serialize, Clone)]
-pub struct Amount {
- amount: Option<String>,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct InputData {
+ credit_card: CreditCardData,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct InputClientTokenData {
+ client_token: ClientTokenInput,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for BraintreeRefundRequest {
+impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
- let metadata: BraintreeMeta =
- utils::to_connector_meta_from_secret(item.connector_meta_data.clone())?;
+ fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
+ match item.request.payment_method_data.clone() {
+ domain::PaymentMethodData::Card(card_data) => Ok(Self {
+ query: TOKENIZE_CREDIT_CARD.to_string(),
+ variables: VariableInput {
+ input: InputData {
+ credit_card: CreditCardData {
+ number: card_data.card_number,
+ expiration_year: card_data.card_exp_year,
+ expiration_month: card_data.card_exp_month,
+ cvv: card_data.card_cvc,
+ cardholder_name: item
+ .get_optional_billing_full_name()
+ .unwrap_or(Secret::new("".to_string())),
+ },
+ },
+ },
+ }),
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::OpenBanking(_)
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::RealTimePayment(_)
+ | domain::PaymentMethodData::Upi(_)
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("braintree"),
+ )
+ .into())
+ }
+ }
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct TokenizePaymentMethodData {
+ id: Secret<String>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TokenizeCreditCardData {
+ payment_method: TokenizePaymentMethodData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ClientToken {
+ client_token: Secret<String>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TokenizeCreditCard {
+ tokenize_credit_card: TokenizeCreditCardData,
+}
- utils::validate_currency(item.request.currency, metadata.merchant_config_currency)?;
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ClientTokenData {
+ create_client_token: ClientToken,
+}
- let refund_amount =
- utils::to_currency_base_unit(item.request.refund_amount, item.request.currency)?;
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct ClientTokenResponse {
+ data: ClientTokenData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct TokenResponse {
+ data: TokenizeCreditCard,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct ErrorResponse {
+ errors: Vec<ErrorDetails>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeTokenResponse {
+ TokenResponse(Box<TokenResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, BraintreeTokenResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, BraintreeTokenResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- transaction: Amount {
- amount: Some(refund_amount),
+ response: match item.response {
+ BraintreeTokenResponse::ErrorResponse(error_response) => {
+ build_error_response(error_response.errors.as_ref(), item.http_code)
+ }
+
+ BraintreeTokenResponse::TokenResponse(token_response) => {
+ Ok(types::PaymentsResponseData::TokenizationResponse {
+ token: token_response
+ .data
+ .tokenize_credit_card
+ .payment_method
+ .id
+ .expose()
+ .clone(),
+ })
+ }
},
+ ..item.data
})
}
}
-#[allow(dead_code)]
-#[derive(Debug, Default, Deserialize, Clone, Serialize)]
-pub enum RefundStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptureTransactionBody {
+ amount: StringMajorUnit,
}
-impl From<RefundStatus> for enums::RefundStatus {
- fn from(item: RefundStatus) -> Self {
- match item {
- RefundStatus::Succeeded => Self::Success,
- RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptureInputData {
+ transaction_id: String,
+ transaction: CaptureTransactionBody,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PsyncInputData {
+ transaction_id: String,
+}
+
+impl TryFrom<&BraintreeRouterData<&types::PaymentsCaptureRouterData>> for BraintreeCaptureRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BraintreeRouterData<&types::PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let query = CAPTURE_TRANSACTION_MUTATION.to_string();
+ let variables = VariableCaptureInput {
+ input: CaptureInputData {
+ transaction_id: item.router_data.request.connector_transaction_id.clone(),
+ transaction: CaptureTransactionBody {
+ amount: item.amount.to_owned(),
+ },
+ },
+ };
+ Ok(Self { query, variables })
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CaptureResponseTransactionBody {
+ id: String,
+ status: BraintreePaymentStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CaptureTransactionData {
+ transaction: CaptureResponseTransactionBody,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CaptureResponseData {
+ capture_transaction: CaptureTransactionData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CaptureResponse {
+ data: CaptureResponseData,
+}
+
+impl TryFrom<types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>>
+ for types::PaymentsCaptureRouterData
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeCaptureResponse::SuccessResponse(capture_data) => {
+ let transaction_data = capture_data.data.capture_transaction.transaction;
+ let status = enums::AttemptStatus::from(transaction_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: transaction_data.status.to_string().clone(),
+ message: transaction_data.status.to_string().clone(),
+ reason: Some(transaction_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: Some(transaction_data.id),
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_data.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ BraintreeCaptureResponse::ErrorResponse(error_data) => Ok(Self {
+ response: build_error_response(&error_data.errors, item.http_code),
+ ..item.data
+ }),
}
}
}
-#[derive(Default, Debug, Clone, Deserialize, Serialize)]
-pub struct RefundResponse {
- pub id: String,
- pub status: RefundStatus,
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CancelInputData {
+ transaction_id: String,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
+#[derive(Debug, Serialize)]
+pub struct VariableCancelInput {
+ input: CancelInputData,
+}
+
+#[derive(Debug, Serialize)]
+pub struct BraintreeCancelRequest {
+ query: String,
+ variables: VariableCancelInput,
+}
+
+impl TryFrom<&types::PaymentsCancelRouterData> for BraintreeCancelRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ let query = VOID_TRANSACTION_MUTATION.to_string();
+ let variables = VariableCancelInput {
+ input: CancelInputData {
+ transaction_id: item.request.connector_transaction_id.clone(),
+ },
+ };
+ Ok(Self { query, variables })
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CancelResponseTransactionBody {
+ id: String,
+ status: BraintreePaymentStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CancelTransactionData {
+ reversal: CancelResponseTransactionBody,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CancelResponseData {
+ reverse_transaction: CancelTransactionData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct CancelResponse {
+ data: CancelResponseData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum BraintreeCancelResponse {
+ CancelResponse(Box<CancelResponse>),
+ ErrorResponse(Box<ErrorResponse>),
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, BraintreeCancelResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: types::ResponseRouterData<F, BraintreeCancelResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreeCancelResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
+ }),
+ BraintreeCancelResponse::CancelResponse(void_response) => {
+ let void_data = void_response.data.reverse_transaction.reversal;
+ let status = enums::AttemptStatus::from(void_data.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: void_data.status.to_string().clone(),
+ message: void_data.status.to_string().clone(),
+ reason: Some(void_data.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: None,
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::NoResponseId,
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ }
+ }
+}
+
+impl TryFrom<&types::PaymentsSyncRouterData> for BraintreePSyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
+ let transaction_id = item
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(Self {
- response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id,
- refund_status: enums::RefundStatus::from(item.response.status),
+ query: TRANSACTION_QUERY.to_string(),
+ variables: PSyncInput {
+ input: TransactionSearchInput {
+ id: IdFilter { is: transaction_id },
+ },
+ },
+ })
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct NodeData {
+ id: String,
+ status: BraintreePaymentStatus,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct EdgeData {
+ node: NodeData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct TransactionData {
+ edges: Vec<EdgeData>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct SearchData {
+ transactions: TransactionData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct PSyncResponseData {
+ search: SearchData,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct PSyncResponse {
+ data: PSyncResponseData,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, BraintreePSyncResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, BraintreePSyncResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BraintreePSyncResponse::ErrorResponse(error_response) => Ok(Self {
+ response: build_error_response(&error_response.errors, item.http_code),
+ ..item.data
}),
- ..item.data
+ BraintreePSyncResponse::SuccessResponse(psync_response) => {
+ let edge_data = psync_response
+ .data
+ .search
+ .transactions
+ .edges
+ .first()
+ .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
+ let status = enums::AttemptStatus::from(edge_data.node.status.clone());
+ let response = if utils::is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: edge_data.node.status.to_string().clone(),
+ message: edge_data.node.status.to_string().clone(),
+ reason: Some(edge_data.node.status.to_string().clone()),
+ attempt_status: None,
+ connector_transaction_id: None,
+ status_code: item.http_code,
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ edge_data.node.id.clone(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ })
+ };
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+ }
+ }
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BraintreeThreeDsResponse {
+ pub nonce: Secret<String>,
+ pub liability_shifted: bool,
+ pub liability_shift_possible: bool,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BraintreeThreeDsErrorResponse {
+ pub code: String,
+ pub message: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct BraintreeRedirectionResponse {
+ pub authentication_response: String,
+}
+
+impl TryFrom<BraintreeMeta> for BraintreeClientTokenRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(metadata: BraintreeMeta) -> Result<Self, Self::Error> {
+ Ok(Self {
+ query: CLIENT_TOKEN_MUTATION.to_owned(),
+ variables: VariableClientTokenInput {
+ input: InputClientTokenData {
+ client_token: ClientTokenInput {
+ merchant_account_id: metadata.merchant_account_id,
+ },
+ },
+ },
})
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
+impl
+ TryFrom<(
+ &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ BraintreeMeta,
+ )> for CardPaymentRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ (item, metadata): (
+ &BraintreeRouterData<&types::PaymentsAuthorizeRouterData>,
+ BraintreeMeta,
+ ),
) -> Result<Self, Self::Error> {
+ let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
+ (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
+ false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Vault(VaultTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ vault_payment_method_after_transacting: TransactionTiming {
+ when: "ALWAYS".to_string(),
+ },
+ }),
+ )
+ } else {
+ (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
+ false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Regular(RegularTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ channel: CHANNEL_CODE.to_string(),
+ }),
+ )
+ };
Ok(Self {
- response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id,
- refund_status: enums::RefundStatus::from(item.response.status),
- }),
- ..item.data
+ query,
+ variables: VariablePaymentInput {
+ input: PaymentInput {
+ payment_method_id: match item.router_data.get_payment_method_token()? {
+ types::PaymentMethodToken::Token(token) => token,
+ types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
+ unimplemented_payment_method!("Apple Pay", "Simplified", "Braintree"),
+ )?,
+ },
+ transaction: transaction_body,
+ },
+ },
+ })
+ }
+}
+
+impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
+ for CardPaymentRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let metadata: BraintreeMeta =
+ utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+ utils::validate_currency(
+ item.router_data.request.currency,
+ Some(metadata.merchant_config_currency),
+ )?;
+ let payload_data = PaymentsCompleteAuthorizeRequestData::get_redirect_response_payload(
+ &item.router_data.request,
+ )?
+ .expose();
+ let redirection_response: BraintreeRedirectionResponse = serde_json::from_value(
+ payload_data,
+ )
+ .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
+ field_name: "redirection_response",
+ })?;
+ let three_ds_data = serde_json::from_str::<BraintreeThreeDsResponse>(
+ &redirection_response.authentication_response,
+ )
+ .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
+ field_name: "three_ds_data",
+ })?;
+
+ let (query, transaction_body) = if item.router_data.request.is_mandate_payment() {
+ (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_AND_VAULT_TRANSACTION_MUTATION.to_string(),
+ false => AUTHORIZE_AND_VAULT_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Vault(VaultTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ vault_payment_method_after_transacting: TransactionTiming {
+ when: "ALWAYS".to_string(),
+ },
+ }),
+ )
+ } else {
+ (
+ match item.router_data.request.is_auto_capture()? {
+ true => CHARGE_CREDIT_CARD_MUTATION.to_string(),
+ false => AUTHORIZE_CREDIT_CARD_MUTATION.to_string(),
+ },
+ TransactionBody::Regular(RegularTransactionBody {
+ amount: item.amount.to_owned(),
+ merchant_account_id: metadata.merchant_account_id,
+ channel: CHANNEL_CODE.to_string(),
+ }),
+ )
+ };
+ Ok(Self {
+ query,
+ variables: VariablePaymentInput {
+ input: PaymentInput {
+ payment_method_id: three_ds_data.nonce,
+ transaction: transaction_body,
+ },
+ },
})
}
}
+
+fn get_braintree_redirect_form(
+ client_token_data: ClientTokenResponse,
+ payment_method_token: types::PaymentMethodToken,
+ card_details: domain::PaymentMethodData,
+) -> Result<services::RedirectForm, error_stack::Report<errors::ConnectorError>> {
+ Ok(services::RedirectForm::Braintree {
+ client_token: client_token_data
+ .data
+ .create_client_token
+ .client_token
+ .expose(),
+ card_token: match payment_method_token {
+ types::PaymentMethodToken::Token(token) => token.expose(),
+ types::PaymentMethodToken::ApplePayDecrypt(_) => Err(unimplemented_payment_method!(
+ "Apple Pay",
+ "Simplified",
+ "Braintree"
+ ))?,
+ },
+ bin: match card_details {
+ domain::PaymentMethodData::Card(card_details) => {
+ card_details.card_number.get_card_isin()
+ }
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::OpenBanking(_)
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::RealTimePayment(_)
+ | domain::PaymentMethodData::Upi(_)
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => Err(
+ errors::ConnectorError::NotImplemented("given payment method".to_owned()),
+ )?,
+ },
+ })
+}
+
+#[derive(Debug, Deserialize)]
+pub struct BraintreeWebhookResponse {
+ pub bt_signature: String,
+ pub bt_payload: String,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "kebab-case")]
+pub struct Notification {
+ pub kind: String, // xml parse only string to fields
+ pub timestamp: String,
+ pub dispute: Option<BraintreeDisputeData>,
+}
+impl types::transformers::ForeignFrom<&str> for api_models::webhooks::IncomingWebhookEvent {
+ fn foreign_from(status: &str) -> Self {
+ match status {
+ "dispute_opened" => Self::DisputeOpened,
+ "dispute_lost" => Self::DisputeLost,
+ "dispute_won" => Self::DisputeWon,
+ "dispute_accepted" | "dispute_auto_accepted" => Self::DisputeAccepted,
+ "dispute_expired" => Self::DisputeExpired,
+ "dispute_disputed" => Self::DisputeChallenged,
+ _ => Self::EventNotSupported,
+ }
+ }
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct BraintreeDisputeData {
+ pub amount_disputed: i64,
+ pub amount_won: Option<String>,
+ pub case_number: Option<String>,
+ pub chargeback_protection_level: Option<String>,
+ pub currency_iso_code: String,
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub created_at: Option<PrimitiveDateTime>,
+ pub evidence: Option<DisputeEvidence>,
+ pub id: String,
+ pub kind: String, // xml parse only string to fields
+ pub status: String,
+ pub reason: Option<String>,
+ pub reason_code: Option<String>,
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub updated_at: Option<PrimitiveDateTime>,
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub reply_by_date: Option<PrimitiveDateTime>,
+ pub transaction: DisputeTransaction,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct DisputeTransaction {
+ pub amount: StringMajorUnit,
+ pub id: String,
+}
+#[derive(Debug, Deserialize, Serialize)]
+pub struct DisputeEvidence {
+ pub comment: String,
+ pub id: Secret<String>,
+ pub created_at: Option<PrimitiveDateTime>,
+ pub url: url::Url,
+}
+
+pub(crate) fn get_dispute_stage(code: &str) -> Result<enums::DisputeStage, errors::ConnectorError> {
+ match code {
+ "CHARGEBACK" => Ok(enums::DisputeStage::Dispute),
+ "PRE_ARBITATION" => Ok(enums::DisputeStage::PreArbitration),
+ "RETRIEVAL" => Ok(enums::DisputeStage::PreDispute),
+ _ => Err(errors::ConnectorError::WebhookBodyDecodingFailed),
+ }
+}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 51fffea3b53..30eee259ce5 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1292,9 +1292,7 @@ impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> {
}
api_enums::Connector::Braintree => {
braintree::transformers::BraintreeAuthType::try_from(self.auth_type)?;
- braintree::braintree_graphql_transformers::BraintreeMeta::try_from(
- self.connector_meta_data,
- )?;
+ braintree::transformers::BraintreeMeta::try_from(self.connector_meta_data)?;
Ok(())
}
api_enums::Connector::Cashtocode => {
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index ec474242d25..11ab940dabe 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -375,7 +375,7 @@ impl ConnectorData {
}
enums::Connector::Boku => Ok(ConnectorEnum::Old(Box::new(&connector::Boku))),
enums::Connector::Braintree => {
- Ok(ConnectorEnum::Old(Box::new(&connector::Braintree)))
+ Ok(ConnectorEnum::Old(Box::new(connector::Braintree::new())))
}
enums::Connector::Cashtocode => {
Ok(ConnectorEnum::Old(Box::new(connector::Cashtocode::new())))
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index f080fd550d8..2bc9e5ccc83 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -88,8 +88,7 @@ bitpay.base_url = "https://test.bitpay.com"
bluesnap.base_url = "https://sandbox.bluesnap.com/"
bluesnap.secondary_base_url = "https://sandpay.bluesnap.com/"
boku.base_url = "https://country-api4-stage.boku.com"
-braintree.base_url = "https://api.sandbox.braintreegateway.com/"
-braintree.secondary_base_url = "https://payments.sandbox.braintree-api.com/graphql"
+braintree.base_url = "https://payments.sandbox.braintree-api.com/graphql"
cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"
checkout.base_url = "https://api.sandbox.checkout.com/"
coinbase.base_url = "https://api.commerce.coinbase.com"
@@ -286,9 +285,6 @@ discord_invite_url = "https://discord.gg/wJZ7DVW8mm"
[payouts]
payout_eligibility = true
-[multiple_api_version_supported_connectors]
-supported_connectors = "braintree"
-
[mandates.supported_payment_methods]
pay_later.klarna = {connector_list = "adyen"}
wallet.google_pay = {connector_list = "stripe,adyen,bankofamerica"}
|
2024-07-10T05:35:20Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Removed Braintree SDK Flow support. Only Graphql Supported now
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
Basic Flow test :
**3DS**
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"card_cvc": "124"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
**Response**
{
"payment_id": "pay_ZMsZRMAjlDTm7mTnknHN",
"merchant_id": "merchant_1722842775",
"status": "requires_customer_action",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 2500,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_ZMsZRMAjlDTm7mTnknHN_secret_IBMfy3TysVyYKVzozo1F",
"created": "2024-08-05T11:03:19.789Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_ZMsZRMAjlDTm7mTnknHN/merchant_1722842775/pay_ZMsZRMAjlDTm7mTnknHN_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:18:19.789Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T11:03:22.426Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
**Non-3ds**
```
**Request**
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"card_cvc": "124"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
**Response**
{
"payment_id": "pay_yXxOTAlvdiTP6fIhkX7a",
"merchant_id": "merchant_1722842775",
"status": "processing",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 0,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_yXxOTAlvdiTP6fIhkX7a_secret_U4PE2hcifkfPIABqIpy5",
"created": "2024-08-05T11:04:27.891Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "dHJhbnNhY3Rpb25fcWF2eWcyeWs",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:19:27.891Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T11:04:30.272Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
Refunds
```
**Request**
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"payment_id": "pay_yXxOTAlvdiTP6fIhkX7a",
"amount": 2000,
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
**Response**
{
"refund_id": "ref_wyHmoQg4HOoULxqCLHSZ",
"payment_id": "pay_yXxOTAlvdiTP6fIhkX7a",
"amount": 2000,
"currency": "USD",
"status": "pending",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-08-05T11:06:48.010Z",
"updated_at": "2024-08-05T11:06:49.108Z",
"connector": "braintree",
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"charges": null
}
```
**Capture**
```
**Request**
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"card_cvc": "124"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
**Response**
{
"payment_id": "pay_u9sqbc5XCaQAvrBEPCAs",
"merchant_id": "merchant_1722842775",
"status": "requires_capture",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 2500,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_u9sqbc5XCaQAvrBEPCAs_secret_8BygWx4zVWcacDLr4ywC",
"created": "2024-08-05T11:07:47.605Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "dHJhbnNhY3Rpb25fZjl0M2MzeXc",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:22:47.605Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T11:07:48.803Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
**Void**
```
curl --location 'http://localhost:8080/payments/pay_u9sqbc5XCaQAvrBEPCAs/cancel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{"cancellation_reason":"requested_by_customer"}'
Response
{
"payment_id": "pay_u9sqbc5XCaQAvrBEPCAs",
"merchant_id": "merchant_1722842775",
"status": "cancelled",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 0,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_u9sqbc5XCaQAvrBEPCAs_secret_8BygWx4zVWcacDLr4ywC",
"created": "2024-08-05T11:07:47.605Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": "requested_by_customer",
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "dHJhbnNhY3Rpb25fZjl0M2MzeXc",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:22:47.605Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T11:10:02.295Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
**Non-Zero Mandate**
**Request**
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data-raw '{
"amount": 12345,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "mandate_customer_new",
"email": "guest@example.com",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_yrlSedzFMxzvk3n85oev"
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"authentication_type": "no_three_ds"
}'
```
**Response**
```
Response
{
"payment_id": "pay_NzF4Wpvw1GxestklJTz5",
"merchant_id": "merchant_1722842775",
"status": "processing",
"amount": 12345,
"net_amount": 12345,
"amount_capturable": 0,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_NzF4Wpvw1GxestklJTz5_secret_cFbgsFDyDSb0QMcn4B32",
"created": "2024-08-05T11:13:44.274Z",
"currency": "USD",
"customer_id": "mandate_customer_new",
"customer": {
"id": "mandate_customer_new",
"name": "Joseph Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "01",
"card_exp_year": "39",
"card_holder_name": "John T",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "mandate_customer_new",
"created_at": 1722856424,
"expires": 1722860024,
"secret": "epk_45cecd7501a64de384de1588cf088213"
},
"manual_retry_allowed": false,
"connector_transaction_id": "dHJhbnNhY3Rpb25fYm44cGV2OGY",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:28:44.274Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_yrlSedzFMxzvk3n85oev",
"payment_method_status": "active",
"updated": "2024-08-05T11:13:46.073Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a3ad0d92d71f654b3843bff550322f665d26223f
|
Basic Flow test :
**3DS**
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"card_cvc": "124"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
**Response**
{
"payment_id": "pay_ZMsZRMAjlDTm7mTnknHN",
"merchant_id": "merchant_1722842775",
"status": "requires_customer_action",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 2500,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_ZMsZRMAjlDTm7mTnknHN_secret_IBMfy3TysVyYKVzozo1F",
"created": "2024-08-05T11:03:19.789Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_ZMsZRMAjlDTm7mTnknHN/merchant_1722842775/pay_ZMsZRMAjlDTm7mTnknHN_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:18:19.789Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T11:03:22.426Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
**Non-3ds**
```
**Request**
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"card_cvc": "124"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
**Response**
{
"payment_id": "pay_yXxOTAlvdiTP6fIhkX7a",
"merchant_id": "merchant_1722842775",
"status": "processing",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 0,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_yXxOTAlvdiTP6fIhkX7a_secret_U4PE2hcifkfPIABqIpy5",
"created": "2024-08-05T11:04:27.891Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "dHJhbnNhY3Rpb25fcWF2eWcyeWs",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:19:27.891Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T11:04:30.272Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
Refunds
```
**Request**
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"payment_id": "pay_yXxOTAlvdiTP6fIhkX7a",
"amount": 2000,
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
**Response**
{
"refund_id": "ref_wyHmoQg4HOoULxqCLHSZ",
"payment_id": "pay_yXxOTAlvdiTP6fIhkX7a",
"amount": 2000,
"currency": "USD",
"status": "pending",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-08-05T11:06:48.010Z",
"updated_at": "2024-08-05T11:06:49.108Z",
"connector": "braintree",
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"charges": null
}
```
**Capture**
```
**Request**
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{
"amount": 2500,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"card_cvc": "124"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
**Response**
{
"payment_id": "pay_u9sqbc5XCaQAvrBEPCAs",
"merchant_id": "merchant_1722842775",
"status": "requires_capture",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 2500,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_u9sqbc5XCaQAvrBEPCAs_secret_8BygWx4zVWcacDLr4ywC",
"created": "2024-08-05T11:07:47.605Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "dHJhbnNhY3Rpb25fZjl0M2MzeXc",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:22:47.605Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T11:07:48.803Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
**Void**
```
curl --location 'http://localhost:8080/payments/pay_u9sqbc5XCaQAvrBEPCAs/cancel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data '{"cancellation_reason":"requested_by_customer"}'
Response
{
"payment_id": "pay_u9sqbc5XCaQAvrBEPCAs",
"merchant_id": "merchant_1722842775",
"status": "cancelled",
"amount": 2500,
"net_amount": 2500,
"amount_capturable": 0,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_u9sqbc5XCaQAvrBEPCAs_secret_8BygWx4zVWcacDLr4ywC",
"created": "2024-08-05T11:07:47.605Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "09",
"card_exp_year": "99",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": "requested_by_customer",
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "dHJhbnNhY3Rpb25fZjl0M2MzeXc",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:22:47.605Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-08-05T11:10:02.295Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
**Non-Zero Mandate**
**Request**
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:' \
--data-raw '{
"amount": 12345,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "mandate_customer_new",
"email": "guest@example.com",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_yrlSedzFMxzvk3n85oev"
},
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"authentication_type": "no_three_ds"
}'
```
**Response**
```
Response
{
"payment_id": "pay_NzF4Wpvw1GxestklJTz5",
"merchant_id": "merchant_1722842775",
"status": "processing",
"amount": 12345,
"net_amount": 12345,
"amount_capturable": 0,
"amount_received": null,
"connector": "braintree",
"client_secret": "pay_NzF4Wpvw1GxestklJTz5_secret_cFbgsFDyDSb0QMcn4B32",
"created": "2024-08-05T11:13:44.274Z",
"currency": "USD",
"customer_id": "mandate_customer_new",
"customer": {
"id": "mandate_customer_new",
"name": "Joseph Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "01",
"card_exp_year": "39",
"card_holder_name": "John T",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "test",
"country": "US",
"line1": "here",
"line2": "there",
"line3": "anywhere",
"zip": "560095",
"state": "Washington",
"first_name": "One",
"last_name": "Two"
},
"phone": {
"number": "1234567890",
"country_code": "+1"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "mandate_customer_new",
"created_at": 1722856424,
"expires": 1722860024,
"secret": "epk_45cecd7501a64de384de1588cf088213"
},
"manual_retry_allowed": false,
"connector_transaction_id": "dHJhbnNhY3Rpb25fYm44cGV2OGY",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_wLEKv9TwK4RabjeK5kUt",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_CuboB7cXkPtl5fULfa30",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-08-05T11:28:44.274Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_yrlSedzFMxzvk3n85oev",
"payment_method_status": "active",
"updated": "2024-08-05T11:13:46.073Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4797
|
Bug: [Kafka] - Consolidate payment logs into a single topic for sessionizing
Consolidate intent, attempt, dispute, refund events into a single topic `hyperswitch-consolidated-events` for sessionizer to consume
#### Initial log structure
```json
{
"log": {
"merchant_id": "test",
"payment_id": "p1",
"attempt_id": "a1",
...
}
"log_type": "payment_attempt"
}
```
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 5433d7a8e46..5d40d0e55ef 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -263,8 +263,7 @@ stripe = { banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,ba
# This data is used to call respective connectors for wallets and cards
[connectors.supported]
-wallets = ["klarna",
- "mifinity", "braintree", "applepay"]
+wallets = ["klarna", "mifinity", "braintree", "applepay"]
rewards = ["cashtocode", "zen"]
cards = [
"adyen",
@@ -352,8 +351,8 @@ email_role_arn = "" # The amazon resource name ( arn ) of the role which
sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session.
[user]
-password_validity_in_days = 90 # Number of days after which password should be updated
-two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside
+password_validity_in_days = 90 # Number of days after which password should be updated
+two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
@@ -364,7 +363,7 @@ stax = { long_lived_token = true, payment_method = "card,bank_debit" }
square = { long_lived_token = false, payment_method = "card" }
braintree = { long_lived_token = false, payment_method = "card" }
gocardless = { long_lived_token = true, payment_method = "bank_debit" }
-billwerk = {long_lived_token = false, payment_method = "card"}
+billwerk = { long_lived_token = false, payment_method = "card" }
[temp_locker_enable_config]
stripe = { payment_method = "bank_transfer" }
@@ -397,16 +396,16 @@ slack_invite_url = "https://www.example.com/" # Slack invite url for hyperswit
discord_invite_url = "https://www.example.com/" # Discord invite url for hyperswitch
[mandates.supported_payment_methods]
-card.credit = { connector_list = "stripe,adyen,cybersource,bankofamerica"} # Mandate supported payment method type and connector for card
-wallet.paypal = { connector_list = "adyen" } # Mandate supported payment method type and connector for wallets
-pay_later.klarna = { connector_list = "adyen" } # Mandate supported payment method type and connector for pay_later
-bank_debit.ach = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit
-bank_debit.becs = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit
-bank_debit.sepa = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit
-bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay" } # Mandate supported payment method type and connector for bank_redirect
+card.credit = { connector_list = "stripe,adyen,cybersource,bankofamerica" } # Mandate supported payment method type and connector for card
+wallet.paypal = { connector_list = "adyen" } # Mandate supported payment method type and connector for wallets
+pay_later.klarna = { connector_list = "adyen" } # Mandate supported payment method type and connector for pay_later
+bank_debit.ach = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit
+bank_debit.becs = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit
+bank_debit.sepa = { connector_list = "gocardless" } # Mandate supported payment method type and connector for bank_debit
+bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay" } # Mandate supported payment method type and connector for bank_redirect
bank_redirect.sofort = { connector_list = "stripe,adyen,globalpay" }
wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica" }
-wallet.google_pay = { connector_list = "bankofamerica"}
+wallet.google_pay = { connector_list = "bankofamerica" }
bank_redirect.giropay = { connector_list = "adyen,globalpay" }
@@ -589,6 +588,7 @@ outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webh
dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events
audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events
payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events
+consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events
# File storage configuration
[file_storage]
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index fc02335dcf5..7215e1931a4 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -81,6 +81,7 @@ outgoing_webhook_logs_topic = "topic" # Kafka topic to be used for outgoing webh
dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute events
audit_events_topic = "topic" # Kafka topic to be used for Payment Audit events
payout_analytics_topic = "topic" # Kafka topic to be used for Payouts and PayoutAttempt events
+consolidated_events_topic = "topic" # Kafka topic to be used for Consolidated events
# File storage configuration
[file_storage]
diff --git a/config/development.toml b/config/development.toml
index 56d74e67489..496ce6477a8 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -89,8 +89,7 @@ vault_private_key = ""
tunnel_private_key = ""
[connectors.supported]
-wallets = ["klarna",
- "mifinity", "braintree", "applepay", "adyen"]
+wallets = ["klarna", "mifinity", "braintree", "applepay", "adyen"]
rewards = ["cashtocode", "zen"]
cards = [
"aci",
@@ -559,7 +558,7 @@ redis_lock_expiry_seconds = 180 # 3 * 60 seconds
delay_between_retries_in_milliseconds = 500
[kv_config]
-ttl = 900 # 15 * 60 seconds
+ttl = 900 # 15 * 60 seconds
soft_kill = false
[frm]
@@ -579,6 +578,7 @@ outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events"
dispute_analytics_topic = "hyperswitch-dispute-events"
audit_events_topic = "hyperswitch-audit-events"
payout_analytics_topic = "hyperswitch-payout-events"
+consolidated_events_topic = "hyperswitch-consolidated-events"
[analytics]
source = "sqlx"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 3dac84e21d8..b94b5c8afbb 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -180,8 +180,7 @@ zsl.base_url = "https://api.sitoffalb.net/"
apple_pay = { country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US,KR,VN,MA,ZA,VA,CL,SV,GT,HN,PA", currency = "AED,AUD,CHF,CAD,EUR,GBP,HKD,SGD,USD" }
[connectors.supported]
-wallets = ["klarna",
- "mifinity", "braintree", "applepay"]
+wallets = ["klarna", "mifinity", "braintree", "applepay"]
rewards = ["cashtocode", "zen"]
cards = [
"aci",
@@ -239,7 +238,7 @@ cards = [
"worldline",
"worldpay",
"zen",
- "zsl"
+ "zsl",
]
[delayed_session_response]
@@ -269,7 +268,7 @@ stax = { long_lived_token = true, payment_method = "card,bank_debit" }
square = { long_lived_token = false, payment_method = "card" }
braintree = { long_lived_token = false, payment_method = "card" }
gocardless = { long_lived_token = true, payment_method = "bank_debit" }
-billwerk = {long_lived_token = false, payment_method = "card"}
+billwerk = { long_lived_token = false, payment_method = "card" }
[temp_locker_enable_config]
stripe = { payment_method = "bank_transfer" }
@@ -433,6 +432,7 @@ outgoing_webhook_logs_topic = "hyperswitch-outgoing-webhook-events"
dispute_analytics_topic = "hyperswitch-dispute-events"
audit_events_topic = "hyperswitch-audit-events"
payout_analytics_topic = "hyperswitch-payout-events"
+consolidated_events_topic = "hyperswitch-consolidated-events"
[analytics]
source = "sqlx"
@@ -454,7 +454,7 @@ connection_timeout = 10
queue_strategy = "Fifo"
[kv_config]
-ttl = 900 # 15 * 60 seconds
+ttl = 900 # 15 * 60 seconds
soft_kill = false
[frm]
diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs
index 4bca5824835..e1ecd09804c 100644
--- a/crates/router/src/events.rs
+++ b/crates/router/src/events.rs
@@ -30,6 +30,7 @@ pub enum EventType {
AuditEvent,
#[cfg(feature = "payouts")]
Payout,
+ Consolidated,
}
#[derive(Debug, Default, Deserialize, Clone)]
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index 6f2aa9fcd10..3523ab9261f 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -12,9 +12,13 @@ use rdkafka::{
pub mod payout;
use crate::events::EventType;
mod dispute;
+mod dispute_event;
mod payment_attempt;
+mod payment_attempt_event;
mod payment_intent;
+mod payment_intent_event;
mod refund;
+mod refund_event;
use diesel_models::refund::Refund;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use serde::Serialize;
@@ -23,8 +27,10 @@ use time::{OffsetDateTime, PrimitiveDateTime};
#[cfg(feature = "payouts")]
use self::payout::KafkaPayout;
use self::{
- dispute::KafkaDispute, payment_attempt::KafkaPaymentAttempt,
- payment_intent::KafkaPaymentIntent, refund::KafkaRefund,
+ dispute::KafkaDispute, dispute_event::KafkaDisputeEvent, payment_attempt::KafkaPaymentAttempt,
+ payment_attempt_event::KafkaPaymentAttemptEvent, payment_intent::KafkaPaymentIntent,
+ payment_intent_event::KafkaPaymentIntentEvent, refund::KafkaRefund,
+ refund_event::KafkaRefundEvent,
};
use crate::types::storage::Dispute;
@@ -89,6 +95,42 @@ impl<'a, T: KafkaMessage> KafkaMessage for KafkaEvent<'a, T> {
}
}
+#[derive(serde::Serialize, Debug)]
+struct KafkaConsolidatedLog<'a, T: KafkaMessage> {
+ #[serde(flatten)]
+ event: &'a T,
+ tenant_id: TenantID,
+}
+
+#[derive(serde::Serialize, Debug)]
+struct KafkaConsolidatedEvent<'a, T: KafkaMessage> {
+ log: KafkaConsolidatedLog<'a, T>,
+ log_type: EventType,
+}
+
+impl<'a, T: KafkaMessage> KafkaConsolidatedEvent<'a, T> {
+ fn new(event: &'a T, tenant_id: TenantID) -> Self {
+ Self {
+ log: KafkaConsolidatedLog { event, tenant_id },
+ log_type: event.event_type(),
+ }
+ }
+}
+
+impl<'a, T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'a, T> {
+ fn key(&self) -> String {
+ self.log.event.key()
+ }
+
+ fn event_type(&self) -> EventType {
+ EventType::Consolidated
+ }
+
+ fn creation_timestamp(&self) -> Option<i64> {
+ self.log.event.creation_timestamp()
+ }
+}
+
#[derive(Debug, serde::Deserialize, Clone, Default)]
#[serde(default)]
pub struct KafkaSettings {
@@ -103,6 +145,7 @@ pub struct KafkaSettings {
audit_events_topic: String,
#[cfg(feature = "payouts")]
payout_analytics_topic: String,
+ consolidated_events_topic: String,
}
impl KafkaSettings {
@@ -175,6 +218,12 @@ impl KafkaSettings {
))
})?;
+ common_utils::fp_utils::when(self.consolidated_events_topic.is_default_or_empty(), || {
+ Err(ApplicationError::InvalidConfigurationValueError(
+ "Consolidated Events topic must not be empty".into(),
+ ))
+ })?;
+
Ok(())
}
}
@@ -192,6 +241,7 @@ pub struct KafkaProducer {
audit_events_topic: String,
#[cfg(feature = "payouts")]
payout_analytics_topic: String,
+ consolidated_events_topic: String,
}
struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>);
@@ -233,23 +283,13 @@ impl KafkaProducer {
audit_events_topic: conf.audit_events_topic.clone(),
#[cfg(feature = "payouts")]
payout_analytics_topic: conf.payout_analytics_topic.clone(),
+ consolidated_events_topic: conf.consolidated_events_topic.clone(),
})
}
pub fn log_event<T: KafkaMessage>(&self, event: &T) -> MQResult<()> {
router_env::logger::debug!("Logging Kafka Event {event:?}");
- let topic = match event.event_type() {
- EventType::PaymentIntent => &self.intent_analytics_topic,
- EventType::PaymentAttempt => &self.attempt_analytics_topic,
- EventType::Refund => &self.refund_analytics_topic,
- EventType::ApiLogs => &self.api_logs_topic,
- EventType::ConnectorApiLogs => &self.connector_logs_topic,
- EventType::OutgoingWebhookLogs => &self.outgoing_webhook_logs_topic,
- EventType::Dispute => &self.dispute_analytics_topic,
- EventType::AuditEvent => &self.audit_events_topic,
- #[cfg(feature = "payouts")]
- EventType::Payout => &self.payout_analytics_topic,
- };
+ let topic = self.get_topic(event.event_type());
self.producer
.0
.send(
@@ -281,11 +321,18 @@ impl KafkaProducer {
format!("Failed to add negative attempt event {negative_event:?}")
})?;
};
+
self.log_event(&KafkaEvent::new(
&KafkaPaymentAttempt::from_storage(attempt),
tenant_id.clone(),
))
- .attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}"))
+ .attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}"))?;
+
+ self.log_event(&KafkaConsolidatedEvent::new(
+ &KafkaPaymentAttemptEvent::from_storage(attempt),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| format!("Failed to add consolidated attempt event {attempt:?}"))
}
pub async fn log_payment_attempt_delete(
@@ -317,11 +364,18 @@ impl KafkaProducer {
format!("Failed to add negative intent event {negative_event:?}")
})?;
};
+
self.log_event(&KafkaEvent::new(
&KafkaPaymentIntent::from_storage(intent),
tenant_id.clone(),
))
- .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))
+ .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))?;
+
+ self.log_event(&KafkaConsolidatedEvent::new(
+ &KafkaPaymentIntentEvent::from_storage(intent),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| format!("Failed to add consolidated intent event {intent:?}"))
}
pub async fn log_payment_intent_delete(
@@ -353,11 +407,18 @@ impl KafkaProducer {
format!("Failed to add negative refund event {negative_event:?}")
})?;
};
+
self.log_event(&KafkaEvent::new(
&KafkaRefund::from_storage(refund),
tenant_id.clone(),
))
- .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))
+ .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))?;
+
+ self.log_event(&KafkaConsolidatedEvent::new(
+ &KafkaRefundEvent::from_storage(refund),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| format!("Failed to add consolidated refund event {refund:?}"))
}
pub async fn log_refund_delete(
@@ -389,11 +450,18 @@ impl KafkaProducer {
format!("Failed to add negative dispute event {negative_event:?}")
})?;
};
+
self.log_event(&KafkaEvent::new(
&KafkaDispute::from_storage(dispute),
tenant_id.clone(),
))
- .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))
+ .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))?;
+
+ self.log_event(&KafkaConsolidatedEvent::new(
+ &KafkaDisputeEvent::from_storage(dispute),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| format!("Failed to add consolidated dispute event {dispute:?}"))
}
#[cfg(feature = "payouts")]
@@ -437,6 +505,7 @@ impl KafkaProducer {
EventType::AuditEvent => &self.audit_events_topic,
#[cfg(feature = "payouts")]
EventType::Payout => &self.payout_analytics_topic,
+ EventType::Consolidated => &self.consolidated_events_topic,
}
}
}
diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs
new file mode 100644
index 00000000000..71e0a11e04d
--- /dev/null
+++ b/crates/router/src/services/kafka/dispute_event.rs
@@ -0,0 +1,77 @@
+use diesel_models::enums as storage_enums;
+use masking::Secret;
+use time::OffsetDateTime;
+
+use crate::types::storage::dispute::Dispute;
+
+#[serde_with::skip_serializing_none]
+#[derive(serde::Serialize, Debug)]
+pub struct KafkaDisputeEvent<'a> {
+ pub dispute_id: &'a String,
+ pub dispute_amount: i64,
+ pub currency: &'a String,
+ pub dispute_stage: &'a storage_enums::DisputeStage,
+ pub dispute_status: &'a storage_enums::DisputeStatus,
+ pub payment_id: &'a String,
+ pub attempt_id: &'a String,
+ pub merchant_id: &'a String,
+ pub connector_status: &'a String,
+ pub connector_dispute_id: &'a String,
+ pub connector_reason: Option<&'a String>,
+ pub connector_reason_code: Option<&'a String>,
+ #[serde(default, with = "time::serde::timestamp::milliseconds::option")]
+ pub challenge_required_by: Option<OffsetDateTime>,
+ #[serde(default, with = "time::serde::timestamp::milliseconds::option")]
+ pub connector_created_at: Option<OffsetDateTime>,
+ #[serde(default, with = "time::serde::timestamp::milliseconds::option")]
+ pub connector_updated_at: Option<OffsetDateTime>,
+ #[serde(default, with = "time::serde::timestamp::milliseconds")]
+ pub created_at: OffsetDateTime,
+ #[serde(default, with = "time::serde::timestamp::milliseconds")]
+ pub modified_at: OffsetDateTime,
+ pub connector: &'a String,
+ pub evidence: &'a Secret<serde_json::Value>,
+ pub profile_id: Option<&'a String>,
+ pub merchant_connector_id: Option<&'a String>,
+}
+
+impl<'a> KafkaDisputeEvent<'a> {
+ pub fn from_storage(dispute: &'a Dispute) -> Self {
+ Self {
+ dispute_id: &dispute.dispute_id,
+ dispute_amount: dispute.amount.parse::<i64>().unwrap_or_default(),
+ currency: &dispute.currency,
+ dispute_stage: &dispute.dispute_stage,
+ dispute_status: &dispute.dispute_status,
+ payment_id: &dispute.payment_id,
+ attempt_id: &dispute.attempt_id,
+ merchant_id: &dispute.merchant_id,
+ connector_status: &dispute.connector_status,
+ connector_dispute_id: &dispute.connector_dispute_id,
+ connector_reason: dispute.connector_reason.as_ref(),
+ connector_reason_code: dispute.connector_reason_code.as_ref(),
+ challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()),
+ connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()),
+ connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()),
+ created_at: dispute.created_at.assume_utc(),
+ modified_at: dispute.modified_at.assume_utc(),
+ connector: &dispute.connector,
+ evidence: &dispute.evidence,
+ profile_id: dispute.profile_id.as_ref(),
+ merchant_connector_id: dispute.merchant_connector_id.as_ref(),
+ }
+ }
+}
+
+impl<'a> super::KafkaMessage for KafkaDisputeEvent<'a> {
+ fn key(&self) -> String {
+ format!(
+ "{}_{}_{}",
+ self.merchant_id, self.payment_id, self.dispute_id
+ )
+ }
+
+ fn event_type(&self) -> crate::events::EventType {
+ crate::events::EventType::Dispute
+ }
+}
diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs
new file mode 100644
index 00000000000..bb4d69eda27
--- /dev/null
+++ b/crates/router/src/services/kafka/payment_attempt_event.rs
@@ -0,0 +1,119 @@
+// use diesel_models::enums::MandateDetails;
+use common_utils::types::MinorUnit;
+use diesel_models::enums as storage_enums;
+use hyperswitch_domain_models::{
+ mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
+};
+use time::OffsetDateTime;
+
+#[serde_with::skip_serializing_none]
+#[derive(serde::Serialize, Debug)]
+pub struct KafkaPaymentAttemptEvent<'a> {
+ pub payment_id: &'a String,
+ pub merchant_id: &'a String,
+ pub attempt_id: &'a String,
+ pub status: storage_enums::AttemptStatus,
+ pub amount: MinorUnit,
+ pub currency: Option<storage_enums::Currency>,
+ pub save_to_locker: Option<bool>,
+ pub connector: Option<&'a String>,
+ pub error_message: Option<&'a String>,
+ pub offer_amount: Option<MinorUnit>,
+ pub surcharge_amount: Option<MinorUnit>,
+ pub tax_amount: Option<MinorUnit>,
+ pub payment_method_id: Option<&'a String>,
+ pub payment_method: Option<storage_enums::PaymentMethod>,
+ pub connector_transaction_id: Option<&'a String>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ #[serde(default, with = "time::serde::timestamp::milliseconds::option")]
+ pub capture_on: Option<OffsetDateTime>,
+ pub confirm: bool,
+ pub authentication_type: Option<storage_enums::AuthenticationType>,
+ #[serde(with = "time::serde::timestamp::milliseconds")]
+ pub created_at: OffsetDateTime,
+ #[serde(with = "time::serde::timestamp::milliseconds")]
+ pub modified_at: OffsetDateTime,
+ #[serde(default, with = "time::serde::timestamp::milliseconds::option")]
+ pub last_synced: Option<OffsetDateTime>,
+ pub cancellation_reason: Option<&'a String>,
+ pub amount_to_capture: Option<MinorUnit>,
+ pub mandate_id: Option<&'a String>,
+ pub browser_info: Option<String>,
+ pub error_code: Option<&'a String>,
+ pub connector_metadata: Option<String>,
+ // TODO: These types should implement copy ideally
+ pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
+ pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>,
+ pub payment_method_data: Option<String>,
+ pub error_reason: Option<&'a String>,
+ pub multiple_capture_count: Option<i16>,
+ pub amount_capturable: MinorUnit,
+ pub merchant_connector_id: Option<&'a String>,
+ pub net_amount: MinorUnit,
+ pub unified_code: Option<&'a String>,
+ pub unified_message: Option<&'a String>,
+ pub mandate_data: Option<&'a MandateDetails>,
+ pub client_source: Option<&'a String>,
+ pub client_version: Option<&'a String>,
+}
+
+impl<'a> KafkaPaymentAttemptEvent<'a> {
+ pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
+ Self {
+ payment_id: &attempt.payment_id,
+ merchant_id: &attempt.merchant_id,
+ attempt_id: &attempt.attempt_id,
+ status: attempt.status,
+ amount: attempt.amount,
+ currency: attempt.currency,
+ save_to_locker: attempt.save_to_locker,
+ connector: attempt.connector.as_ref(),
+ error_message: attempt.error_message.as_ref(),
+ offer_amount: attempt.offer_amount,
+ surcharge_amount: attempt.surcharge_amount,
+ tax_amount: attempt.tax_amount,
+ payment_method_id: attempt.payment_method_id.as_ref(),
+ payment_method: attempt.payment_method,
+ connector_transaction_id: attempt.connector_transaction_id.as_ref(),
+ capture_method: attempt.capture_method,
+ capture_on: attempt.capture_on.map(|i| i.assume_utc()),
+ confirm: attempt.confirm,
+ authentication_type: attempt.authentication_type,
+ created_at: attempt.created_at.assume_utc(),
+ modified_at: attempt.modified_at.assume_utc(),
+ last_synced: attempt.last_synced.map(|i| i.assume_utc()),
+ cancellation_reason: attempt.cancellation_reason.as_ref(),
+ amount_to_capture: attempt.amount_to_capture,
+ mandate_id: attempt.mandate_id.as_ref(),
+ browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()),
+ error_code: attempt.error_code.as_ref(),
+ connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()),
+ payment_experience: attempt.payment_experience.as_ref(),
+ payment_method_type: attempt.payment_method_type.as_ref(),
+ payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()),
+ error_reason: attempt.error_reason.as_ref(),
+ multiple_capture_count: attempt.multiple_capture_count,
+ amount_capturable: attempt.amount_capturable,
+ merchant_connector_id: attempt.merchant_connector_id.as_ref(),
+ net_amount: attempt.net_amount,
+ unified_code: attempt.unified_code.as_ref(),
+ unified_message: attempt.unified_message.as_ref(),
+ mandate_data: attempt.mandate_data.as_ref(),
+ client_source: attempt.client_source.as_ref(),
+ client_version: attempt.client_version.as_ref(),
+ }
+ }
+}
+
+impl<'a> super::KafkaMessage for KafkaPaymentAttemptEvent<'a> {
+ fn key(&self) -> String {
+ format!(
+ "{}_{}_{}",
+ self.merchant_id, self.payment_id, self.attempt_id
+ )
+ }
+
+ fn event_type(&self) -> crate::events::EventType {
+ crate::events::EventType::PaymentAttempt
+ }
+}
diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs
new file mode 100644
index 00000000000..a3fbd9ddc45
--- /dev/null
+++ b/crates/router/src/services/kafka/payment_intent_event.rs
@@ -0,0 +1,75 @@
+use common_utils::{id_type, types::MinorUnit};
+use diesel_models::enums as storage_enums;
+use hyperswitch_domain_models::payments::PaymentIntent;
+use time::OffsetDateTime;
+
+#[serde_with::skip_serializing_none]
+#[derive(serde::Serialize, Debug)]
+pub struct KafkaPaymentIntentEvent<'a> {
+ pub payment_id: &'a String,
+ pub merchant_id: &'a String,
+ pub status: storage_enums::IntentStatus,
+ pub amount: MinorUnit,
+ pub currency: Option<storage_enums::Currency>,
+ pub amount_captured: Option<MinorUnit>,
+ pub customer_id: Option<&'a id_type::CustomerId>,
+ pub description: Option<&'a String>,
+ pub return_url: Option<&'a String>,
+ pub connector_id: Option<&'a String>,
+ pub statement_descriptor_name: Option<&'a String>,
+ pub statement_descriptor_suffix: Option<&'a String>,
+ #[serde(with = "time::serde::timestamp::milliseconds")]
+ pub created_at: OffsetDateTime,
+ #[serde(with = "time::serde::timestamp::milliseconds")]
+ pub modified_at: OffsetDateTime,
+ #[serde(default, with = "time::serde::timestamp::milliseconds::option")]
+ pub last_synced: Option<OffsetDateTime>,
+ pub setup_future_usage: Option<storage_enums::FutureUsage>,
+ pub off_session: Option<bool>,
+ pub client_secret: Option<&'a String>,
+ pub active_attempt_id: String,
+ pub business_country: Option<storage_enums::CountryAlpha2>,
+ pub business_label: Option<&'a String>,
+ pub attempt_count: i16,
+ pub payment_confirm_source: Option<storage_enums::PaymentSource>,
+}
+
+impl<'a> KafkaPaymentIntentEvent<'a> {
+ pub fn from_storage(intent: &'a PaymentIntent) -> Self {
+ Self {
+ payment_id: &intent.payment_id,
+ merchant_id: &intent.merchant_id,
+ status: intent.status,
+ amount: intent.amount,
+ currency: intent.currency,
+ amount_captured: intent.amount_captured,
+ customer_id: intent.customer_id.as_ref(),
+ description: intent.description.as_ref(),
+ return_url: intent.return_url.as_ref(),
+ connector_id: intent.connector_id.as_ref(),
+ statement_descriptor_name: intent.statement_descriptor_name.as_ref(),
+ statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(),
+ created_at: intent.created_at.assume_utc(),
+ modified_at: intent.modified_at.assume_utc(),
+ last_synced: intent.last_synced.map(|i| i.assume_utc()),
+ setup_future_usage: intent.setup_future_usage,
+ off_session: intent.off_session,
+ client_secret: intent.client_secret.as_ref(),
+ active_attempt_id: intent.active_attempt.get_id(),
+ business_country: intent.business_country,
+ business_label: intent.business_label.as_ref(),
+ attempt_count: intent.attempt_count,
+ payment_confirm_source: intent.payment_confirm_source,
+ }
+ }
+}
+
+impl<'a> super::KafkaMessage for KafkaPaymentIntentEvent<'a> {
+ fn key(&self) -> String {
+ format!("{}_{}", self.merchant_id, self.payment_id)
+ }
+
+ fn event_type(&self) -> crate::events::EventType {
+ crate::events::EventType::PaymentIntent
+ }
+}
diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs
new file mode 100644
index 00000000000..6aa80b243c1
--- /dev/null
+++ b/crates/router/src/services/kafka/refund_event.rs
@@ -0,0 +1,74 @@
+use common_utils::types::MinorUnit;
+use diesel_models::{enums as storage_enums, refund::Refund};
+use time::OffsetDateTime;
+
+#[serde_with::skip_serializing_none]
+#[derive(serde::Serialize, Debug)]
+pub struct KafkaRefundEvent<'a> {
+ pub internal_reference_id: &'a String,
+ pub refund_id: &'a String, //merchant_reference id
+ pub payment_id: &'a String,
+ pub merchant_id: &'a String,
+ pub connector_transaction_id: &'a String,
+ pub connector: &'a String,
+ pub connector_refund_id: Option<&'a String>,
+ pub external_reference_id: Option<&'a String>,
+ pub refund_type: &'a storage_enums::RefundType,
+ pub total_amount: &'a MinorUnit,
+ pub currency: &'a storage_enums::Currency,
+ pub refund_amount: &'a MinorUnit,
+ pub refund_status: &'a storage_enums::RefundStatus,
+ pub sent_to_gateway: &'a bool,
+ pub refund_error_message: Option<&'a String>,
+ pub refund_arn: Option<&'a String>,
+ #[serde(default, with = "time::serde::timestamp::milliseconds")]
+ pub created_at: OffsetDateTime,
+ #[serde(default, with = "time::serde::timestamp::milliseconds")]
+ pub modified_at: OffsetDateTime,
+ pub description: Option<&'a String>,
+ pub attempt_id: &'a String,
+ pub refund_reason: Option<&'a String>,
+ pub refund_error_code: Option<&'a String>,
+}
+
+impl<'a> KafkaRefundEvent<'a> {
+ pub fn from_storage(refund: &'a Refund) -> Self {
+ Self {
+ internal_reference_id: &refund.internal_reference_id,
+ refund_id: &refund.refund_id,
+ payment_id: &refund.payment_id,
+ merchant_id: &refund.merchant_id,
+ connector_transaction_id: &refund.connector_transaction_id,
+ connector: &refund.connector,
+ connector_refund_id: refund.connector_refund_id.as_ref(),
+ external_reference_id: refund.external_reference_id.as_ref(),
+ refund_type: &refund.refund_type,
+ total_amount: &refund.total_amount,
+ currency: &refund.currency,
+ refund_amount: &refund.refund_amount,
+ refund_status: &refund.refund_status,
+ sent_to_gateway: &refund.sent_to_gateway,
+ refund_error_message: refund.refund_error_message.as_ref(),
+ refund_arn: refund.refund_arn.as_ref(),
+ created_at: refund.created_at.assume_utc(),
+ modified_at: refund.updated_at.assume_utc(),
+ description: refund.description.as_ref(),
+ attempt_id: &refund.attempt_id,
+ refund_reason: refund.refund_reason.as_ref(),
+ refund_error_code: refund.refund_error_code.as_ref(),
+ }
+ }
+}
+
+impl<'a> super::KafkaMessage for KafkaRefundEvent<'a> {
+ fn key(&self) -> String {
+ format!(
+ "{}_{}_{}_{}",
+ self.merchant_id, self.payment_id, self.attempt_id, self.refund_id
+ )
+ }
+
+ fn event_type(&self) -> crate::events::EventType {
+ crate::events::EventType::Refund
+ }
+}
|
2024-05-28T14:10:35Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
- add consolidated payment events to a single topic for sessionizing
- add millisecond precision to timestamp fields
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
[#4797](https://github.com/juspay/hyperswitch/issues/4797)
## How did you test it?
- Create payment, refund, dispute
- check `topic: hyperswitch-consolidated-events` for combined logs for above events


## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
865007717c5c7e617ca1b447ea5f9bb3d274cac3
|
- Create payment, refund, dispute
- check `topic: hyperswitch-consolidated-events` for combined logs for above events


|
|
juspay/hyperswitch
|
juspay__hyperswitch-4816
|
Bug: Code changes to get the certificates from the certificates column with fallback
The migration api can be run on the deployment environment only after the 100% deployment of the specific version of hyperswitch, because there are probabilities of merchant account being created even during the deployments. Once deployment beings the apple pay details must be read from the metadata only until the migrations are done. Hence we need a fallback here which tries to read the apple pay data from the newly added column whenever need and if it fails we just log the error and try to read the apple pay data from the metadata.
Once the migration is done we can check for the error log lines during the read form newly added column, if there are no logs we can remove the fallback in future. Else we might need to rerun the migrations for the specific merchant connector account.
|
diff --git a/crates/api_models/src/apple_pay_certificates_migration.rs b/crates/api_models/src/apple_pay_certificates_migration.rs
new file mode 100644
index 00000000000..796734f53e4
--- /dev/null
+++ b/crates/api_models/src/apple_pay_certificates_migration.rs
@@ -0,0 +1,12 @@
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct ApplePayCertificatesMigrationResponse {
+ pub migration_successful: Vec<String>,
+ pub migration_failed: Vec<String>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
+pub struct ApplePayCertificatesMigrationRequest {
+ pub merchant_ids: Vec<String>,
+}
+
+impl common_utils::events::ApiEventMetric for ApplePayCertificatesMigrationRequest {}
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 9c26576e77b..078c27e6db9 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -1,3 +1,4 @@
+pub mod apple_pay_certificates_migration;
pub mod connector_onboarding;
pub mod customer;
pub mod dispute;
diff --git a/crates/api_models/src/events/apple_pay_certificates_migration.rs b/crates/api_models/src/events/apple_pay_certificates_migration.rs
new file mode 100644
index 00000000000..f194443bea0
--- /dev/null
+++ b/crates/api_models/src/events/apple_pay_certificates_migration.rs
@@ -0,0 +1,9 @@
+use common_utils::events::ApiEventMetric;
+
+use crate::apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse;
+
+impl ApiEventMetric for ApplePayCertificatesMigrationResponse {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::ApplePayCertificatesMigration)
+ }
+}
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs
index a0bc6f6362d..d6d6deaa235 100644
--- a/crates/api_models/src/lib.rs
+++ b/crates/api_models/src/lib.rs
@@ -2,6 +2,7 @@
pub mod admin;
pub mod analytics;
pub mod api_keys;
+pub mod apple_pay_certificates_migration;
pub mod blocklist;
pub mod cards_info;
pub mod conditional_configs;
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index cda13289aa5..8ccfa14eaf6 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4208,6 +4208,23 @@ pub struct SessionTokenInfo {
pub initiative_context: String,
#[schema(value_type = Option<CountryAlpha2>)]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
+ #[serde(flatten)]
+ pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(tag = "payment_processing_details_at")]
+pub enum PaymentProcessingDetailsAt {
+ Hyperswitch(PaymentProcessingDetails),
+ Connector,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)]
+pub struct PaymentProcessingDetails {
+ #[schema(value_type = String)]
+ pub payment_processing_certificate: Secret<String>,
+ #[schema(value_type = String)]
+ pub payment_processing_certificate_key: Secret<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 3df291d5681..f20d2b821dd 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2284,11 +2284,6 @@ pub enum ReconStatus {
Active,
Disabled,
}
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum ApplePayFlow {
- Simplified,
- Manual,
-}
#[derive(
Clone,
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index 8939e07a76c..1052840dbc8 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -50,6 +50,7 @@ pub enum ApiEventsType {
// TODO: This has to be removed once the corresponding apiEventTypes are created
Miscellaneous,
RustLocker,
+ ApplePayCertificatesMigration,
FraudCheck,
Recon,
Dispute {
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index d7c505f7942..b411b1a7acd 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -67,7 +67,7 @@ pub enum ConnectorAuthType {
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(untagged)]
pub enum ApplePayTomlConfig {
- Standard(payments::ApplePayMetadata),
+ Standard(Box<payments::ApplePayMetadata>),
Zen(ZenApplePay),
}
diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs
index e45ef002626..680e3dacc85 100644
--- a/crates/diesel_models/src/merchant_connector_account.rs
+++ b/crates/diesel_models/src/merchant_connector_account.rs
@@ -43,6 +43,7 @@ pub struct MerchantConnectorAccount {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: storage_enums::ConnectorStatus,
+ pub connector_wallets_details: Option<Encryption>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -72,6 +73,7 @@ pub struct MerchantConnectorAccountNew {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: storage_enums::ConnectorStatus,
+ pub connector_wallets_details: Option<Encryption>,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
@@ -96,6 +98,7 @@ pub struct MerchantConnectorAccountUpdateInternal {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: Option<storage_enums::ConnectorStatus>,
+ pub connector_wallets_details: Option<Encryption>,
}
impl MerchantConnectorAccountUpdateInternal {
diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs
index 0527ff3a181..682766679fd 100644
--- a/crates/diesel_models/src/query/generics.rs
+++ b/crates/diesel_models/src/query/generics.rs
@@ -166,7 +166,8 @@ where
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
- _ => Err(report!(errors::DatabaseError::Others))
+ Err(error) => Err(error)
+ .change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
}
}
@@ -252,7 +253,8 @@ where
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
- _ => Err(report!(errors::DatabaseError::Others))
+ Err(error) => Err(error)
+ .change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 6074fdc10b7..7baaa337259 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -679,6 +679,7 @@ diesel::table! {
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
pm_auth_config -> Nullable<Jsonb>,
status -> ConnectorStatus,
+ connector_wallets_details -> Nullable<Bytea>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 065290b6b2d..8dca0c86a2a 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -22,6 +22,12 @@ pub enum PaymentMethodData {
CardToken(CardToken),
}
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ApplePayFlow {
+ Simplified(api_models::payments::PaymentProcessingDetails),
+ Manual,
+}
+
impl PaymentMethodData {
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
match self {
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index b5d96a5c53f..00e13f5fce9 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -3,7 +3,7 @@ use std::{collections::HashMap, marker::PhantomData};
use common_utils::id_type;
use masking::Secret;
-use crate::payment_address::PaymentAddress;
+use crate::{payment_address::PaymentAddress, payment_method_data};
#[derive(Debug, Clone)]
pub struct RouterData<Flow, Request, Response> {
@@ -22,6 +22,7 @@ pub struct RouterData<Flow, Request, Response> {
pub address: PaymentAddress,
pub auth_type: common_enums::enums::AuthenticationType,
pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
+ pub connector_wallets_details: Option<common_utils::pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
pub access_token: Option<AccessToken>,
pub session_token: Option<String>,
@@ -56,7 +57,7 @@ pub struct RouterData<Flow, Request, Response> {
pub connector_http_status_code: Option<u16>,
pub external_latency: Option<u128>,
/// Contains apple pay flow type simplified or manual
- pub apple_pay_flow: Option<common_enums::enums::ApplePayFlow>,
+ pub apple_pay_flow: Option<payment_method_data::ApplePayFlow>,
pub frm_metadata: Option<common_utils::pii::SecretSerdeValue>,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 237cddcf94e..f4fc5fc8473 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -309,6 +309,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::FeatureMetadata,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
+ api_models::payments::PaymentProcessingDetailsAt,
+ api_models::payments::PaymentProcessingDetails,
api_models::payments::SwishQrData,
api_models::payments::AirwallexData,
api_models::payments::NoonData,
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index 02a5873429f..53787fe04ab 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -1,6 +1,7 @@
pub mod admin;
pub mod api_keys;
pub mod api_locking;
+pub mod apple_pay_certificates_migration;
pub mod authentication;
pub mod blocklist;
pub mod cache;
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 6b582c2c957..0578945006f 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -937,7 +937,7 @@ pub async fn create_payment_connector(
payment_methods_enabled,
test_mode: req.test_mode,
disabled,
- metadata: req.metadata,
+ metadata: req.metadata.clone(),
frm_configs,
connector_label: Some(connector_label.clone()),
business_country: req.business_country,
@@ -961,6 +961,7 @@ pub async fn create_payment_connector(
applepay_verified_domains: None,
pm_auth_config: req.pm_auth_config.clone(),
status: connector_status,
+ connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(&key_store, &req.metadata).await?,
};
let transaction_type = match req.connector_type {
@@ -1200,6 +1201,7 @@ pub async fn update_payment_connector(
expected_format: "auth_type and api_key".to_string(),
})?;
let metadata = req.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 {
@@ -1275,6 +1277,10 @@ pub async fn update_payment_connector(
applepay_verified_domains: None,
pm_auth_config: req.pm_auth_config,
status: Some(connector_status),
+ connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(
+ &key_store, &metadata,
+ )
+ .await?,
};
// Profile id should always be present
diff --git a/crates/router/src/core/apple_pay_certificates_migration.rs b/crates/router/src/core/apple_pay_certificates_migration.rs
new file mode 100644
index 00000000000..327358bda50
--- /dev/null
+++ b/crates/router/src/core/apple_pay_certificates_migration.rs
@@ -0,0 +1,109 @@
+use api_models::apple_pay_certificates_migration;
+use common_utils::errors::CustomResult;
+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},
+};
+
+pub async fn apple_pay_certificates_migration(
+ state: SessionState,
+ req: &apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest,
+) -> CustomResult<
+ services::ApplicationResponse<
+ apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse,
+ >,
+ errors::ApiErrorResponse,
+> {
+ let db = state.store.as_ref();
+
+ let merchant_id_list = &req.merchant_ids;
+
+ let mut migration_successful_merchant_ids = vec![];
+ let mut migration_failed_merchant_ids = vec![];
+
+ for merchant_id in merchant_id_list {
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ let merchant_connector_accounts = db
+ .find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ merchant_id,
+ true,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
+
+ let mut mca_to_update = vec![];
+
+ for connector_account in merchant_connector_accounts {
+ let connector_apple_pay_metadata =
+ helpers::get_applepay_metadata(connector_account.clone().metadata)
+ .map_err(|error| {
+ logger::error!(
+ "Apple pay metadata parsing failed for {:?} in certificates migrations api {:?}",
+ connector_account.clone().connector_name,
+ error
+ )
+ })
+ .ok();
+ if let Some(apple_pay_metadata) = connector_apple_pay_metadata {
+ let encrypted_apple_pay_metadata = domain_types::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")?,
+ ),
+ key_store.key.get_inner().peek(),
+ )
+ .await
+ .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.to_string());
+ }
+ Err(error) => {
+ logger::debug!(
+ "Merchant connector accounts update failed with error {error} for merchant id {merchant_id}");
+ migration_failed_merchant_ids.push(merchant_id.to_string());
+ }
+ };
+ }
+
+ Ok(services::api::ApplicationResponse::Json(
+ apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse {
+ migration_successful: migration_successful_merchant_ids,
+ migration_failed: migration_failed_merchant_ids,
+ },
+ ))
+}
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index 2255e1ff582..704784c485e 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -153,6 +153,7 @@ pub fn construct_router_data<F: Clone, Req, Res>(
address,
auth_type: common_enums::AuthenticationType::NoThreeDs,
connector_meta_data: merchant_connector_account.get_metadata(),
+ connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: None,
access_token: None,
session_token: None,
diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
index 74353e83b3d..679a5dad29a 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -67,6 +67,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: FraudCheckCheckoutData {
amount: self.payment_attempt.amount.get_amount_as_i64(),
diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
index f91d87c808c..855b87f3ffb 100644
--- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
@@ -72,6 +72,7 @@ pub async fn construct_fulfillment_router_data<'a>(
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()),
diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs
index b8f8810f09b..ac661231ecc 100644
--- a/crates/router/src/core/fraud_check/flows/record_return.rs
+++ b/crates/router/src/core/fraud_check/flows/record_return.rs
@@ -65,6 +65,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: FraudCheckRecordReturnData {
amount: self.payment_attempt.amount.get_amount_as_i64(),
diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs
index b605c540656..6dbde23e3d2 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -62,6 +62,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: FraudCheckSaleData {
amount: self.payment_attempt.amount.get_amount_as_i64(),
diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
index 8c496792a81..4f5d0b30aa9 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -72,6 +72,7 @@ impl
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: FraudCheckTransactionData {
amount: self.payment_attempt.amount.get_amount_as_i64(),
diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs
index ec438ee6d78..811b69e4562 100644
--- a/crates/router/src/core/mandate/utils.rs
+++ b/crates/router/src/core/mandate/utils.rs
@@ -44,6 +44,7 @@ pub async fn construct_mandate_revoke_router_data(
address: PaymentAddress::default(),
auth_type: diesel_models::enums::AuthenticationType::default(),
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index caaecdc8629..8ee8dce6393 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1475,44 +1475,47 @@ where
// Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay
// and the connector supports Apple Pay predecrypt
- if matches!(
- tokenization_action,
- TokenizationAction::DecryptApplePayToken
- | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt
- ) {
- let apple_pay_data = match payment_data.payment_method_data.clone() {
- Some(payment_data) => {
- let domain_data = domain::PaymentMethodData::from(payment_data);
- match domain_data {
- domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(
- wallet_data,
- )) => Some(
- ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data))
- .change_context(errors::ApiErrorResponse::InternalServerError)?
- .decrypt(state)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- ),
- _ => None,
+ match &tokenization_action {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
+ | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ ) => {
+ let apple_pay_data = match payment_data.payment_method_data.clone() {
+ Some(payment_method_data) => {
+ let domain_data = domain::PaymentMethodData::from(payment_method_data);
+ match domain_data {
+ domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(
+ wallet_data,
+ )) => Some(
+ ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data))
+ .change_context(errors::ApiErrorResponse::InternalServerError)?
+ .decrypt(
+ &payment_processing_details.payment_processing_certificate,
+ &payment_processing_details.payment_processing_certificate_key,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ ),
+ _ => None,
+ }
}
- }
- _ => None,
- };
-
- let apple_pay_predecrypt = apple_pay_data
- .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>(
- "ApplePayPredecryptData",
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ _ => None,
+ };
- logger::debug!(?apple_pay_predecrypt);
+ let apple_pay_predecrypt = apple_pay_data
+ .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>(
+ "ApplePayPredecryptData",
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
- router_data.payment_method_token = Some(
- hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(Box::new(
- apple_pay_predecrypt,
- )),
- );
- }
+ router_data.payment_method_token = Some(
+ hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(
+ Box::new(apple_pay_predecrypt),
+ ),
+ );
+ }
+ _ => (),
+ };
let pm_token = router_data
.add_payment_method_token(state, &connector, &tokenization_action)
@@ -2053,7 +2056,7 @@ fn is_payment_method_tokenization_enabled_for_connector(
connector_name: &str,
payment_method: &storage::enums::PaymentMethod,
payment_method_type: &Option<storage::enums::PaymentMethodType>,
- apple_pay_flow: &Option<enums::ApplePayFlow>,
+ apple_pay_flow: &Option<domain::ApplePayFlow>,
) -> RouterResult<bool> {
let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name);
@@ -2078,13 +2081,13 @@ fn is_payment_method_tokenization_enabled_for_connector(
fn is_apple_pay_pre_decrypt_type_connector_tokenization(
payment_method_type: &Option<storage::enums::PaymentMethodType>,
- apple_pay_flow: &Option<enums::ApplePayFlow>,
+ apple_pay_flow: &Option<domain::ApplePayFlow>,
apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>,
) -> bool {
match (payment_method_type, apple_pay_flow) {
(
Some(storage::enums::PaymentMethodType::ApplePay),
- Some(enums::ApplePayFlow::Simplified),
+ Some(domain::ApplePayFlow::Simplified(_)),
) => !matches!(
apple_pay_pre_decrypt_flow_filter,
Some(ApplePayPreDecryptFlow::NetworkTokenization)
@@ -2094,18 +2097,22 @@ fn is_apple_pay_pre_decrypt_type_connector_tokenization(
}
fn decide_apple_pay_flow(
+ state: &SessionState,
payment_method_type: &Option<enums::PaymentMethodType>,
merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>,
-) -> Option<enums::ApplePayFlow> {
+) -> Option<domain::ApplePayFlow> {
payment_method_type.and_then(|pmt| match pmt {
- enums::PaymentMethodType::ApplePay => check_apple_pay_metadata(merchant_connector_account),
+ 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<enums::ApplePayFlow> {
+) -> Option<domain::ApplePayFlow> {
merchant_connector_account.and_then(|mca| {
let metadata = mca.get_metadata();
metadata.and_then(|apple_pay_metadata| {
@@ -2139,14 +2146,34 @@ fn check_apple_pay_metadata(
apple_pay_combined,
) => match apple_pay_combined {
api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => {
- enums::ApplePayFlow::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 { .. } => {
- enums::ApplePayFlow::Manual
+ 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(_) => {
- enums::ApplePayFlow::Manual
+ domain::ApplePayFlow::Manual
}
})
})
@@ -2173,23 +2200,21 @@ async fn decide_payment_method_tokenize_action(
payment_method: &storage::enums::PaymentMethod,
pm_parent_token: Option<&String>,
is_connector_tokenization_enabled: bool,
- apple_pay_flow: Option<enums::ApplePayFlow>,
+ apple_pay_flow: Option<domain::ApplePayFlow>,
) -> RouterResult<TokenizationAction> {
- let is_apple_pay_predecrypt_supported =
- matches!(apple_pay_flow, Some(enums::ApplePayFlow::Simplified));
-
match pm_parent_token {
- None => {
- if is_connector_tokenization_enabled && is_apple_pay_predecrypt_supported {
- Ok(TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt)
- } else if is_connector_tokenization_enabled {
- Ok(TokenizationAction::TokenizeInConnectorAndRouter)
- } else if is_apple_pay_predecrypt_supported {
- Ok(TokenizationAction::DecryptApplePayToken)
- } else {
- Ok(TokenizationAction::TokenizeInRouter)
+ None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {
+ (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ )
}
- }
+ (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,
+ (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
+ }
+ (false, _) => TokenizationAction::TokenizeInRouter,
+ }),
Some(token) => {
let redis_conn = state
.store
@@ -2212,17 +2237,18 @@ async fn decide_payment_method_tokenize_action(
match connector_token_option {
Some(connector_token) => Ok(TokenizationAction::ConnectorToken(connector_token)),
- None => {
- if is_connector_tokenization_enabled && is_apple_pay_predecrypt_supported {
- Ok(TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt)
- } else if is_connector_tokenization_enabled {
- Ok(TokenizationAction::TokenizeInConnectorAndRouter)
- } else if is_apple_pay_predecrypt_supported {
- Ok(TokenizationAction::DecryptApplePayToken)
- } else {
- Ok(TokenizationAction::TokenizeInRouter)
+ None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {
+ (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ )
}
- }
+ (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,
+ (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
+ }
+ (false, _) => TokenizationAction::TokenizeInRouter,
+ }),
}
}
}
@@ -2235,8 +2261,8 @@ pub enum TokenizationAction {
TokenizeInConnectorAndRouter,
ConnectorToken(String),
SkipConnectorTokenization,
- DecryptApplePayToken,
- TokenizeInConnectorAndApplepayPreDecrypt,
+ DecryptApplePayToken(payments_api::PaymentProcessingDetails),
+ TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails),
}
#[allow(clippy::too_many_arguments)]
@@ -2277,7 +2303,7 @@ where
let payment_method_type = &payment_data.payment_attempt.payment_method_type;
let apple_pay_flow =
- decide_apple_pay_flow(payment_method_type, Some(merchant_connector_account));
+ decide_apple_pay_flow(state, payment_method_type, Some(merchant_connector_account));
let is_connector_tokenization_enabled =
is_payment_method_tokenization_enabled_for_connector(
@@ -2346,12 +2372,14 @@ where
TokenizationAction::SkipConnectorTokenization => {
TokenizationAction::SkipConnectorTokenization
}
- TokenizationAction::DecryptApplePayToken => {
- TokenizationAction::DecryptApplePayToken
- }
- TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt => {
- TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt
+ TokenizationAction::DecryptApplePayToken(payment_processing_details) => {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
}
+ TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ ),
};
(payment_data.to_owned(), connector_tokenization_action)
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 76441f40759..14a3b9327dc 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -166,8 +166,20 @@ async fn create_applepay_session_token(
)
} else {
// Get the apple pay metadata
- let apple_pay_metadata =
- helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?;
+ let connector_apple_pay_wallet_details =
+ helpers::get_applepay_metadata(router_data.connector_wallets_details.clone())
+ .map_err(|error| {
+ logger::debug!(
+ "Apple pay connector wallets details parsing failed in create_applepay_session_token {:?}",
+ error
+ )
+ })
+ .ok();
+
+ let apple_pay_metadata = match connector_apple_pay_wallet_details {
+ Some(apple_pay_wallet_details) => apple_pay_wallet_details,
+ None => helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?,
+ };
// Get payment request data , apple pay session request and merchant keys
let (
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index a58a6ae32b2..6610b048606 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -6,6 +6,7 @@ use api_models::{
};
use base64::Engine;
use common_utils::{
+ crypto::Encryptable,
ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt},
fp_utils, generate_id, id_type, pii,
types::MinorUnit,
@@ -3169,6 +3170,13 @@ impl MerchantConnectorAccountType {
}
}
+ pub fn get_connector_wallets_details(&self) -> Option<masking::Secret<serde_json::Value>> {
+ match self {
+ Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(),
+ Self::CacheVal(_) => None,
+ }
+ }
+
pub fn is_disabled(&self) -> bool {
match self {
Self::DbVal(ref inner) => inner.disabled.unwrap_or(false),
@@ -3368,6 +3376,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
refund_id: router_data.refund_id,
dispute_id: router_data.dispute_id,
connector_response: router_data.connector_response,
+ connector_wallets_details: router_data.connector_wallets_details,
}
}
@@ -3905,17 +3914,32 @@ pub fn validate_customer_access(
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
+ connector_wallets_details: 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 {:?}",
+ let connector_apple_pay_wallet_details =
+ get_applepay_metadata(connector_wallets_details)
+ .map_err(|error| {
+ logger::debug!(
+ "Apple pay connector wallets details parsing failed for {:?} in is_apple_pay_simplified_flow {:?}",
+ connector_name,
+ error
+ )
+ })
+ .ok();
+
+ let option_apple_pay_metadata = match connector_apple_pay_wallet_details {
+ Some(apple_pay_wallet_details) => Some(apple_pay_wallet_details),
+ None => get_applepay_metadata(connector_metadata)
+ .map_err(|error| {
+ logger::debug!(
+ "Apple pay metadata parsing failed for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
- })
- .ok();
+ })
+ .ok(),
+ };
// return true only if the apple flow type is simplified
Ok(matches!(
@@ -3928,6 +3952,38 @@ pub fn is_apple_pay_simplified_flow(
))
}
+pub async fn get_encrypted_apple_pay_connector_wallets_details(
+ key_store: &domain::MerchantKeyStore,
+ connector_metadata: &Option<masking::Secret<tera::Value>>,
+) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> {
+ let apple_pay_metadata = get_applepay_metadata(connector_metadata.clone())
+ .map_err(|error| {
+ logger::error!(
+ "Apple pay metadata parsing failed in get_encrypted_apple_pay_connector_wallets_details {:?}",
+ error
+ )
+ })
+ .ok();
+
+ let connector_apple_pay_details = apple_pay_metadata
+ .map(|metadata| {
+ serde_json::to_value(metadata)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize apple pay metadata as JSON")
+ })
+ .transpose()?
+ .map(masking::Secret::new);
+
+ let encrypted_connector_apple_pay_details = connector_apple_pay_details
+ .async_lift(|wallets_details| {
+ types::encrypt_optional(wallets_details, key_store.key.get_inner().peek())
+ })
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting connector wallets details")?;
+ Ok(encrypted_connector_apple_pay_details)
+}
+
pub fn get_applepay_metadata(
connector_metadata: Option<pii::SecretSerdeValue>,
) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> {
@@ -3991,6 +4047,7 @@ where
let connector_data_list = if is_apple_pay_simplified_flow(
merchant_connector_account_type.get_metadata(),
+ merchant_connector_account_type.get_connector_wallets_details(),
merchant_connector_account_type
.get_connector_name()
.as_ref(),
@@ -4010,6 +4067,10 @@ where
for merchant_connector_account in merchant_connector_account_list {
if is_apple_pay_simplified_flow(
merchant_connector_account.metadata,
+ merchant_connector_account
+ .connector_wallets_details
+ .as_deref()
+ .cloned(),
Some(&merchant_connector_account.connector_name),
)? {
let connector_data = api::ConnectorData::get_connector_by_name(
@@ -4064,10 +4125,11 @@ impl ApplePayData {
pub async fn decrypt(
&self,
- state: &SessionState,
+ 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(state).await?;
- let shared_secret = self.shared_secret(state).await?;
+ 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)
@@ -4075,17 +4137,11 @@ impl ApplePayData {
Ok(parsed_decrypted)
}
- pub async fn merchant_id(
+ pub fn merchant_id(
&self,
- state: &SessionState,
+ payment_processing_certificate: &masking::Secret<String>,
) -> CustomResult<String, errors::ApplePayDecryptionError> {
- let cert_data = state
- .conf
- .applepay_decrypt_keys
- .get_inner()
- .apple_pay_ppc
- .clone()
- .expose();
+ let cert_data = payment_processing_certificate.clone().expose();
let base64_decode_cert_data = BASE64_ENGINE
.decode(cert_data)
@@ -4120,9 +4176,9 @@ impl ApplePayData {
Ok(apple_pay_m_id)
}
- pub async fn shared_secret(
+ pub fn shared_secret(
&self,
- state: &SessionState,
+ 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())
@@ -4132,13 +4188,7 @@ impl ApplePayData {
.change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed)
.attach_printable("Failed to deserialize the public key")?;
- let decrypted_apple_pay_ppc_key = state
- .conf
- .applepay_decrypt_keys
- .get_inner()
- .apple_pay_ppc_key
- .clone()
- .expose();
+ 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())
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 48637a0d2b3..7016c7542be 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -727,7 +727,7 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>(
) -> RouterResult<Option<String>> {
match tokenization_action {
payments::TokenizationAction::TokenizeInConnector
- | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt => {
+ | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(_) => {
let connector_integration: services::BoxedConnectorIntegration<
'_,
api::PaymentMethodToken,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 8eca589ca28..02115a529c3 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -125,6 +125,7 @@ where
};
let apple_pay_flow = payments::decide_apple_pay_flow(
+ state,
&payment_data.payment_attempt.payment_method_type,
Some(merchant_connector_account),
);
@@ -154,6 +155,7 @@ where
.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
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 679838a6dd5..8201a8480c0 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -164,6 +164,7 @@ pub async fn construct_payout_router_data<'a, F>(
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,
payment_method_status: None,
request: types::PayoutsData {
@@ -316,6 +317,7 @@ pub async fn construct_refund_router_data<'a, F>(
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()),
@@ -565,6 +567,7 @@ pub async fn construct_accept_dispute_router_data<'a>(
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()),
@@ -661,6 +664,7 @@ pub async fn construct_submit_evidence_router_data<'a>(
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()),
@@ -755,6 +759,7 @@ pub async fn construct_upload_file_router_data<'a>(
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()),
@@ -853,6 +858,7 @@ pub async fn construct_defend_dispute_router_data<'a>(
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()),
@@ -942,6 +948,7 @@ pub async fn construct_retrieve_file_router_data<'a>(
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,
payment_method_status: None,
request: types::RetrieveFileRequestData {
diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs
index 7518091ee87..bfbc1cb8b44 100644
--- a/crates/router/src/core/verification/utils.rs
+++ b/crates/router/src/core/verification/utils.rs
@@ -61,6 +61,7 @@ pub async fn check_existence_and_add_domain_to_db(
pm_auth_config: None,
connector_label: None,
status: None,
+ connector_wallets_details: None,
};
state
.store
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index ad1aafd3125..1394c68cfa8 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -86,6 +86,7 @@ pub async fn construct_webhook_router_data<'a>(
address: PaymentAddress::default(),
auth_type: diesel_models::enums::AuthenticationType::default(),
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: types::VerifyWebhookSourceRequestData {
webhook_headers: request_details.headers.clone(),
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 910ad085f63..19603f81486 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -942,6 +942,17 @@ impl FileMetadataInterface for KafkaStore {
#[async_trait::async_trait]
impl MerchantConnectorAccountInterface for KafkaStore {
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ merchant_connector_accounts: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), errors::StorageError> {
+ self.diesel_store
+ .update_multiple_merchant_connector_accounts(merchant_connector_accounts)
+ .await
+ }
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
merchant_id: &str,
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index aea37b517be..ab66b52c32d 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -1,4 +1,6 @@
+use async_bb8_diesel::AsyncConnection;
use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode};
+use diesel_models::encryption::Encryption;
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
@@ -165,6 +167,14 @@ where
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ this: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), errors::StorageError>;
+
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
merchant_id: &str,
@@ -381,6 +391,104 @@ impl MerchantConnectorAccountInterface for Store {
.await
}
+ #[instrument(skip_all)]
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ merchant_connector_accounts: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+
+ async fn update_call(
+ connection: &diesel_models::PgPooledConn,
+ (merchant_connector_account, mca_update): (
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ ),
+ ) -> Result<(), error_stack::Report<storage_impl::errors::StorageError>> {
+ Conversion::convert(merchant_connector_account)
+ .await
+ .change_context(errors::StorageError::EncryptionError)?
+ .update(connection, mca_update)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?;
+ Ok(())
+ }
+
+ conn.transaction_async(|connection_pool| async move {
+ for (merchant_connector_account, update_merchant_connector_account) in
+ merchant_connector_accounts
+ {
+ let _connector_name = merchant_connector_account.connector_name.clone();
+ let _profile_id = merchant_connector_account.profile_id.clone().ok_or(
+ errors::StorageError::ValueNotFound("profile_id".to_string()),
+ )?;
+
+ let _merchant_id = merchant_connector_account.merchant_id.clone();
+ let _merchant_connector_id =
+ merchant_connector_account.merchant_connector_id.clone();
+
+ let update = update_call(
+ &connection_pool,
+ (
+ merchant_connector_account,
+ update_merchant_connector_account,
+ ),
+ );
+
+ #[cfg(feature = "accounts_cache")]
+ // Redact all caches as any of might be used because of backwards compatibility
+ cache::publish_and_redact_multiple(
+ self,
+ [
+ cache::CacheKind::Accounts(
+ format!("{}_{}", _profile_id, _connector_name).into(),
+ ),
+ cache::CacheKind::Accounts(
+ format!("{}_{}", _merchant_id, _merchant_connector_id).into(),
+ ),
+ cache::CacheKind::CGraph(
+ format!("cgraph_{}_{_profile_id}", _merchant_id).into(),
+ ),
+ ],
+ || update,
+ )
+ .await
+ .map_err(|error| {
+ // Returning `DatabaseConnectionError` after logging the actual error because
+ // -> it is not possible to get the underlying from `error_stack::Report<C>`
+ // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
+ // because of Rust's orphan rules
+ router_env::logger::error!(
+ ?error,
+ "DB transaction for updating multiple merchant connector account failed"
+ );
+ errors::StorageError::DatabaseConnectionError
+ })?;
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ update.await.map_err(|error| {
+ // Returning `DatabaseConnectionError` after logging the actual error because
+ // -> it is not possible to get the underlying from `error_stack::Report<C>`
+ // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
+ // because of Rust's orphan rules
+ router_env::logger::error!(
+ ?error,
+ "DB transaction for updating multiple merchant connector account failed"
+ );
+ errors::StorageError::DatabaseConnectionError
+ })?;
+ }
+ }
+ Ok::<_, errors::StorageError>(())
+ })
+ .await?;
+ Ok(())
+ }
+
#[instrument(skip_all)]
async fn update_merchant_connector_account(
&self,
@@ -417,7 +525,7 @@ impl MerchantConnectorAccountInterface for Store {
#[cfg(feature = "accounts_cache")]
{
- // Redact both the caches as any one or both might be used because of backwards compatibility
+ // Redact all caches as any of might be used because of backwards compatibility
cache::publish_and_redact_multiple(
self,
[
@@ -502,6 +610,17 @@ impl MerchantConnectorAccountInterface for Store {
#[async_trait::async_trait]
impl MerchantConnectorAccountInterface for MockDb {
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ _merchant_connector_accounts: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), errors::StorageError> {
+ // No need to implement this function for `MockDb` as this function will be removed after the
+ // apple pay certificate migration
+ Err(errors::StorageError::MockDbError)?
+ }
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
merchant_id: &str,
@@ -658,6 +777,7 @@ impl MerchantConnectorAccountInterface for MockDb {
applepay_verified_domains: t.applepay_verified_domains,
pm_auth_config: t.pm_auth_config,
status: t.status,
+ connector_wallets_details: t.connector_wallets_details.map(Encryption::from),
};
accounts.push(account.clone());
account
@@ -857,6 +977,14 @@ mod merchant_connector_account_cache_tests {
applepay_verified_domains: None,
pm_auth_config: None,
status: common_enums::ConnectorStatus::Inactive,
+ connector_wallets_details: Some(
+ domain::types::encrypt(
+ serde_json::Value::default().into(),
+ merchant_key.key.get_inner().peek(),
+ )
+ .await
+ .unwrap(),
+ ),
};
db.insert_merchant_connector_account(mca.clone(), &merchant_key)
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 7344b85d150..73ec0f1635d 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -144,6 +144,7 @@ pub fn mk_app(
.service(routes::Routing::server(state.clone()))
.service(routes::Blocklist::server(state.clone()))
.service(routes::Gsm::server(state.clone()))
+ .service(routes::ApplePayCertificatesMigration::server(state.clone()))
.service(routes::PaymentLink::server(state.clone()))
.service(routes::User::server(state.clone()))
.service(routes::ConnectorOnboarding::server(state.clone()))
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 9f13635ca90..cb229b5c802 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -1,6 +1,7 @@
pub mod admin;
pub mod api_keys;
pub mod app;
+pub mod apple_pay_certificates_migration;
#[cfg(feature = "olap")]
pub mod blocklist;
pub mod cache;
@@ -58,10 +59,10 @@ pub use self::app::Payouts;
#[cfg(all(feature = "olap", feature = "recon"))]
pub use self::app::Recon;
pub use self::app::{
- ApiKeys, AppState, BusinessProfile, Cache, Cards, Configs, ConnectorOnboarding, Customers,
- Disputes, EphemeralKey, Files, Gsm, Health, Mandates, MerchantAccount,
- MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll, Refunds, SessionState,
- User, Webhooks,
+ ApiKeys, AppState, ApplePayCertificatesMigration, BusinessProfile, Cache, Cards, Configs,
+ ConnectorOnboarding, Customers, Disputes, EphemeralKey, Files, Gsm, Health, Mandates,
+ MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll,
+ Refunds, SessionState, User, Webhooks,
};
#[cfg(feature = "olap")]
pub use self::app::{Blocklist, Routing, Verify, WebhookEvents};
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 2d1b77460a5..cd392756505 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -413,7 +413,7 @@ pub async fn payment_connector_delete(
merchant_connector_id,
})
.into_inner();
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -430,7 +430,7 @@ pub async fn payment_connector_delete(
req.headers(),
),
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
/// Merchant Account - Toggle KV
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 5af3a2bef25..5438535a15c 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -29,8 +29,8 @@ use super::routing as cloud_routing;
use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains};
#[cfg(feature = "olap")]
use super::{
- admin::*, api_keys::*, connector_onboarding::*, disputes::*, files::*, gsm::*, payment_link::*,
- user::*, user_role::*, webhook_events::*,
+ admin::*, api_keys::*, apple_pay_certificates_migration, connector_onboarding::*, disputes::*,
+ files::*, gsm::*, payment_link::*, user::*, user_role::*, webhook_events::*,
};
use super::{cache::*, health::*};
#[cfg(any(feature = "olap", feature = "oltp"))]
@@ -1117,6 +1117,19 @@ impl Configs {
}
}
+pub struct ApplePayCertificatesMigration;
+
+#[cfg(feature = "olap")]
+impl ApplePayCertificatesMigration {
+ pub fn server(state: AppState) -> Scope {
+ web::scope("/apple_pay_certificates_migration")
+ .app_data(web::Data::new(state))
+ .service(web::resource("").route(
+ web::post().to(apple_pay_certificates_migration::apple_pay_certificates_migration),
+ ))
+ }
+}
+
pub struct Poll;
#[cfg(feature = "oltp")]
diff --git a/crates/router/src/routes/apple_pay_certificates_migration.rs b/crates/router/src/routes/apple_pay_certificates_migration.rs
new file mode 100644
index 00000000000..8c9d507ba41
--- /dev/null
+++ b/crates/router/src/routes/apple_pay_certificates_migration.rs
@@ -0,0 +1,30 @@
+use actix_web::{web, HttpRequest, HttpResponse};
+use router_env::Flow;
+
+use super::AppState;
+use crate::{
+ core::{api_locking, apple_pay_certificates_migration},
+ services::{api, authentication as auth},
+};
+
+pub async fn apple_pay_certificates_migration(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<
+ api_models::apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest,
+ >,
+) -> HttpResponse {
+ let flow = Flow::ApplePayCertificatesMigration;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ &json_payload.into_inner(),
+ |state, _, req, _| {
+ apple_pay_certificates_migration::apple_pay_certificates_migration(state, req)
+ },
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index b4b9658a7e0..a64343757b5 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -35,6 +35,7 @@ pub enum ApiIdentifier {
ConnectorOnboarding,
Recon,
Poll,
+ ApplePayCertificatesMigration,
}
impl From<Flow> for ApiIdentifier {
@@ -186,6 +187,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::GsmRuleUpdate
| Flow::GsmRuleDelete => Self::Gsm,
+ Flow::ApplePayCertificatesMigration => Self::ApplePayCertificatesMigration,
+
Flow::UserConnectAccount
| Flow::UserSignUp
| Flow::UserSignIn
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index e17ec791637..21aea14caf5 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -805,6 +805,7 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
+ connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
@@ -865,6 +866,7 @@ impl<F1, F2>
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
+ connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 0b932f9aeb1..7e296d0b4a8 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -85,6 +85,7 @@ impl VerifyConnectorData {
connector_customer: None,
connector_auth_type: self.connector_auth.clone(),
connector_meta_data: None,
+ connector_wallets_details: None,
payment_method_token: None,
connector_api_version: None,
recurring_mandate_payment_data: None,
diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs
index 0e7f5b081c3..6c2f6a06e1e 100644
--- a/crates/router/src/types/domain/merchant_connector_account.rs
+++ b/crates/router/src/types/domain/merchant_connector_account.rs
@@ -11,7 +11,10 @@ use diesel_models::{
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
-use super::{behaviour, types::TypeEncryption};
+use super::{
+ behaviour,
+ types::{self, AsyncLift, TypeEncryption},
+};
#[derive(Clone, Debug)]
pub struct MerchantConnectorAccount {
pub id: Option<i32>,
@@ -36,6 +39,7 @@ pub struct MerchantConnectorAccount {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: enums::ConnectorStatus,
+ pub connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>,
}
#[derive(Debug)]
@@ -56,6 +60,10 @@ pub enum MerchantConnectorAccountUpdate {
pm_auth_config: Option<serde_json::Value>,
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
+ connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ },
+ ConnectorWalletDetailsUpdate {
+ connector_wallets_details: Encryptable<Secret<serde_json::Value>>,
},
}
@@ -92,6 +100,7 @@ impl behaviour::Conversion for MerchantConnectorAccount {
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
+ connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
},
)
}
@@ -132,6 +141,13 @@ impl behaviour::Conversion for MerchantConnectorAccount {
applepay_verified_domains: other.applepay_verified_domains,
pm_auth_config: other.pm_auth_config,
status: other.status,
+ connector_wallets_details: other
+ .connector_wallets_details
+ .async_lift(|inner| types::decrypt(inner, key.peek()))
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting connector wallets details".to_string(),
+ })?,
})
}
@@ -160,6 +176,7 @@ impl behaviour::Conversion for MerchantConnectorAccount {
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
+ connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
})
}
}
@@ -183,6 +200,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
pm_auth_config,
connector_label,
status,
+ connector_wallets_details,
} => Self {
merchant_id,
connector_type,
@@ -201,6 +219,29 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
pm_auth_config,
connector_label,
status,
+ connector_wallets_details: connector_wallets_details.map(Encryption::from),
+ },
+ MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {
+ connector_wallets_details,
+ } => Self {
+ connector_wallets_details: Some(Encryption::from(connector_wallets_details)),
+ merchant_id: None,
+ connector_type: None,
+ connector_name: None,
+ connector_account_details: None,
+ connector_label: None,
+ test_mode: None,
+ disabled: None,
+ merchant_connector_id: None,
+ payment_methods_enabled: None,
+ frm_configs: None,
+ metadata: None,
+ modified_at: None,
+ connector_webhook_details: None,
+ frm_config: None,
+ applepay_verified_domains: None,
+ pm_auth_config: None,
+ status: None,
},
}
}
diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs
index 51d3210a70f..021505c644f 100644
--- a/crates/router/src/types/domain/payments.rs
+++ b/crates/router/src/types/domain/payments.rs
@@ -1,10 +1,10 @@
pub use hyperswitch_domain_models::payment_method_data::{
- AliPayQr, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, BankDebitData,
- BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData, CardToken,
- CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, GoPayRedirection,
- GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData,
- GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection,
- MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData,
+ AliPayQr, ApplePayFlow, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod,
+ BankDebitData, BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData,
+ CardToken, CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails,
+ GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData,
+ GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData,
+ KakaoPayRedirection, MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData,
SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, UpiCollectData, UpiData,
UpiIntentData, VoucherData, WalletData, WeChatPayQr,
};
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index b83d3138b7c..e71219b6a9e 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -707,13 +707,13 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
}
pub fn add_apple_pay_flow_metrics(
- apple_pay_flow: &Option<enums::ApplePayFlow>,
+ apple_pay_flow: &Option<domain::ApplePayFlow>,
connector: Option<String>,
merchant_id: String,
) {
if let Some(flow) = apple_pay_flow {
match flow {
- enums::ApplePayFlow::Simplified => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add(
+ domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add(
&metrics::CONTEXT,
1,
&[
@@ -724,7 +724,7 @@ pub fn add_apple_pay_flow_metrics(
metrics::request::add_attributes("merchant_id", merchant_id.to_owned()),
],
),
- enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add(
+ domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add(
&metrics::CONTEXT,
1,
&[
@@ -741,14 +741,14 @@ pub fn add_apple_pay_flow_metrics(
pub fn add_apple_pay_payment_status_metrics(
payment_attempt_status: enums::AttemptStatus,
- apple_pay_flow: Option<enums::ApplePayFlow>,
+ apple_pay_flow: Option<domain::ApplePayFlow>,
connector: Option<String>,
merchant_id: String,
) {
if payment_attempt_status == enums::AttemptStatus::Charged {
if let Some(flow) = apple_pay_flow {
match flow {
- enums::ApplePayFlow::Simplified => {
+ domain::ApplePayFlow::Simplified(_) => {
metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add(
&metrics::CONTEXT,
1,
@@ -761,7 +761,7 @@ pub fn add_apple_pay_payment_status_metrics(
],
)
}
- enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT
+ domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT
.add(
&metrics::CONTEXT,
1,
@@ -778,7 +778,7 @@ pub fn add_apple_pay_payment_status_metrics(
} else if payment_attempt_status == enums::AttemptStatus::Failure {
if let Some(flow) = apple_pay_flow {
match flow {
- enums::ApplePayFlow::Simplified => {
+ domain::ApplePayFlow::Simplified(_) => {
metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add(
&metrics::CONTEXT,
1,
@@ -791,7 +791,7 @@ pub fn add_apple_pay_payment_status_metrics(
],
)
}
- enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add(
+ domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add(
&metrics::CONTEXT,
1,
&[
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 10e8b366530..b01c5abb968 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -97,6 +97,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
None,
),
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
@@ -159,6 +160,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
response: Err(types::ErrorResponse::default()),
address: PaymentAddress::default(),
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 0de19f17b54..be86d377299 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -540,6 +540,7 @@ pub trait ConnectorActions: Connector {
connector_meta_data: info
.clone()
.and_then(|a| a.connector_meta_data.map(Secret::new)),
+ connector_wallets_details: None,
amount_captured: None,
access_token: info.clone().and_then(|a| a.access_token),
session_token: None,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 110532f524d..51f762e3713 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -298,6 +298,8 @@ pub enum Flow {
GsmRuleRetrieve,
/// Gsm Rule Update flow
GsmRuleUpdate,
+ /// Apple pay certificates migration
+ ApplePayCertificatesMigration,
/// Gsm Rule Delete flow
GsmRuleDelete,
/// User Sign Up
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index 4356b6b7997..b153c47b882 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -101,6 +101,12 @@ impl From<error_stack::Report<RedisError>> for StorageError {
}
}
+impl From<diesel::result::Error> for StorageError {
+ fn from(err: diesel::result::Error) -> Self {
+ Self::from(error_stack::report!(DatabaseError::from(err)))
+ }
+}
+
impl From<error_stack::Report<DatabaseError>> for StorageError {
fn from(err: error_stack::Report<DatabaseError>) -> Self {
Self::DatabaseError(err)
diff --git a/migrations/2024-05-28-054439_connector_wallets_details/down.sql b/migrations/2024-05-28-054439_connector_wallets_details/down.sql
new file mode 100644
index 00000000000..dea26bbd1eb
--- /dev/null
+++ b/migrations/2024-05-28-054439_connector_wallets_details/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS connector_wallets_details;
\ No newline at end of file
diff --git a/migrations/2024-05-28-054439_connector_wallets_details/up.sql b/migrations/2024-05-28-054439_connector_wallets_details/up.sql
new file mode 100644
index 00000000000..c75de9204df
--- /dev/null
+++ b/migrations/2024-05-28-054439_connector_wallets_details/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS connector_wallets_details BYTEA DEFAULT NULL;
\ No newline at end of file
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index f42481798a4..ba0d8946192 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -13697,6 +13697,63 @@
},
"additionalProperties": false
},
+ "PaymentProcessingDetails": {
+ "type": "object",
+ "required": [
+ "payment_processing_certificate",
+ "payment_processing_certificate_key"
+ ],
+ "properties": {
+ "payment_processing_certificate": {
+ "type": "string"
+ },
+ "payment_processing_certificate_key": {
+ "type": "string"
+ }
+ }
+ },
+ "PaymentProcessingDetailsAt": {
+ "oneOf": [
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentProcessingDetails"
+ },
+ {
+ "type": "object",
+ "required": [
+ "payment_processing_details_at"
+ ],
+ "properties": {
+ "payment_processing_details_at": {
+ "type": "string",
+ "enum": [
+ "Hyperswitch"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "required": [
+ "payment_processing_details_at"
+ ],
+ "properties": {
+ "payment_processing_details_at": {
+ "type": "string",
+ "enum": [
+ "Connector"
+ ]
+ }
+ }
+ }
+ ],
+ "discriminator": {
+ "propertyName": "payment_processing_details_at"
+ }
+ },
"PaymentRetrieveBody": {
"type": "object",
"properties": {
@@ -18394,43 +18451,55 @@
}
},
"SessionTokenInfo": {
- "type": "object",
- "required": [
- "certificate",
- "certificate_keys",
- "merchant_identifier",
- "display_name",
- "initiative",
- "initiative_context"
- ],
- "properties": {
- "certificate": {
- "type": "string"
- },
- "certificate_keys": {
- "type": "string"
- },
- "merchant_identifier": {
- "type": "string"
- },
- "display_name": {
- "type": "string"
- },
- "initiative": {
- "type": "string"
- },
- "initiative_context": {
- "type": "string"
- },
- "merchant_business_country": {
+ "allOf": [
+ {
"allOf": [
{
- "$ref": "#/components/schemas/CountryAlpha2"
+ "$ref": "#/components/schemas/PaymentProcessingDetailsAt"
}
],
"nullable": true
+ },
+ {
+ "type": "object",
+ "required": [
+ "certificate",
+ "certificate_keys",
+ "merchant_identifier",
+ "display_name",
+ "initiative",
+ "initiative_context"
+ ],
+ "properties": {
+ "certificate": {
+ "type": "string"
+ },
+ "certificate_keys": {
+ "type": "string"
+ },
+ "merchant_identifier": {
+ "type": "string"
+ },
+ "display_name": {
+ "type": "string"
+ },
+ "initiative": {
+ "type": "string"
+ },
+ "initiative_context": {
+ "type": "string"
+ },
+ "merchant_business_country": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CountryAlpha2"
+ }
+ ],
+ "nullable": true
+ }
+ }
}
- }
+ ]
},
"StraightThroughAlgorithm": {
"oneOf": [
|
2024-05-28T13:19:09Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently apple pay related details are being stored in the connector metadata, as in future we are going to add apple pay decrypted flow support for ios app we will be collecting the apple pay payment processing certificates as well. As this ppc and ppc key needs to be securely stored, we need to move the existing certificates to a new column which stores the encrypted certificates.
This pr adds a api end point (`/apple_pay_certificates_migration`) to migrate the apple pay details form the merchant connector account `metadata` to the newly added column connector (`connector_wallets_details`). This api takes list of `merchant_ids` as input and then lists all the configured merchant connector accounts for that merchant id. After which it checks for the apple pay details in the metadata in the merchant connector account, if present it is encrypted by merchant's DEK (Data Encryption Key) and will be stored in the newly added column (`connector_wallets_details`) in the merchant connector account. Response contains the list of merchant_ids for migration succeeded (`migration_successful`) and failed (`migraiton_failed`).
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Apple pay certificate migration api
```
curl --location 'http://localhost:8080/apple_pay_certificates_migration' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_ids": ["merchant_1713176513", "merchant_1714122879"]
}'
```
<img width="719" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bb66cc2c-69f7-4c6e-bb3c-1e184944bbd2">
-> Check the db for connector_wallets_details of mca belonging to above merchants
<img width="862" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/24d5c9ed-f091-49cd-983b-839724024118">
-> Create MCA with apple pay `simplified` and manual `flow`
metadata for apple pay `simplified`
```
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
metadata for apple pay `manual` flow
```
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "",
"display_name": "applepay",
"certificate_keys": "",
"merchant_business_coountry": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Confirm an apple pay payment with above flows
<img width="1159" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a70ebc44-948a-421d-bcdf-3f9a2adb4361">
-> Create a apple pay payment with the below metadata
```
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "",
"display_name": "applepay",
"certificate_keys": "",
"payment_processing_details_at": "Hyperswitch",
"payment_processing_certificate": "",
"payment_processing_certificate_key": "",
"initiative_context": "sdk-test-app.netlify.app",
"merchant_identifier": "",
"merchant_business_coountry": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Confirm apple pay payment
<img width="1055" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4460d4e3-24e9-4348-ac1c-c05d6bef5e3e">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d242850b63173f314fb259451139464f09e0a9e9
|
-> Apple pay certificate migration api
```
curl --location 'http://localhost:8080/apple_pay_certificates_migration' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_ids": ["merchant_1713176513", "merchant_1714122879"]
}'
```
<img width="719" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bb66cc2c-69f7-4c6e-bb3c-1e184944bbd2">
-> Check the db for connector_wallets_details of mca belonging to above merchants
<img width="862" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/24d5c9ed-f091-49cd-983b-839724024118">
-> Create MCA with apple pay `simplified` and manual `flow`
metadata for apple pay `simplified`
```
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
metadata for apple pay `manual` flow
```
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "",
"display_name": "applepay",
"certificate_keys": "",
"merchant_business_coountry": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Confirm an apple pay payment with above flows
<img width="1159" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a70ebc44-948a-421d-bcdf-3f9a2adb4361">
-> Create a apple pay payment with the below metadata
```
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "",
"display_name": "applepay",
"certificate_keys": "",
"payment_processing_details_at": "Hyperswitch",
"payment_processing_certificate": "",
"payment_processing_certificate_key": "",
"initiative_context": "sdk-test-app.netlify.app",
"merchant_identifier": "",
"merchant_business_coountry": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Confirm apple pay payment
<img width="1055" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4460d4e3-24e9-4348-ac1c-c05d6bef5e3e">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4796
|
Bug: [FIX] implement `StrongEq` for `StrongSecre<Vec<u8>>`
|
diff --git a/crates/masking/src/strong_secret.rs b/crates/masking/src/strong_secret.rs
index fd1335f6993..51c0f2cb3fe 100644
--- a/crates/masking/src/strong_secret.rs
+++ b/crates/masking/src/strong_secret.rs
@@ -117,3 +117,12 @@ impl StrongEq for String {
bool::from(lhs.ct_eq(rhs))
}
}
+
+impl StrongEq for Vec<u8> {
+ fn strong_eq(&self, other: &Self) -> bool {
+ let lhs = &self;
+ let rhs = &other;
+
+ bool::from(lhs.ct_eq(rhs))
+ }
+}
|
2024-05-28T14:04:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Enhancement
## Description
<!-- Describe your changes in detail -->
Implement `StrongEq` for `Vec<u8>`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Implement `StrongEq` for deriving `Eq` for `StrongSecret<Vec<u8>>`.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
NA. Testing is not needed, compiler guided.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
84e032e6c28afc410c82e73e51deb629b0c4a81a
|
NA. Testing is not needed, compiler guided.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4793
|
Bug: Filter the apple pay retryable connectors for a specific business profile
Currently while fetching the apple pay retry connector list all the enabled merchant connector accounts for that specific merchant id is included. But we need to retry the connector with only the connectors in that specific profile id with which the payment attempt was created.
|
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 7bc0b532239..b64e7479c4d 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3165,11 +3165,11 @@ where
routing_data.business_sub_label = choice.sub_label.clone();
}
- #[cfg(feature = "retry")]
+ #[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))]
let should_do_retry =
retry::config_should_call_gsm(&*state.store, &merchant_account.merchant_id).await;
- #[cfg(feature = "retry")]
+ #[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))]
if payment_data.payment_attempt.payment_method_type
== Some(storage_enums::PaymentMethodType::ApplePay)
&& should_do_retry
@@ -3180,15 +3180,15 @@ where
payment_data,
key_store,
connector_data.clone(),
- #[cfg(feature = "connector_choice_mca_id")]
choice.merchant_connector_id.clone().as_ref(),
- #[cfg(not(feature = "connector_choice_mca_id"))]
- None,
)
.await?;
if let Some(connector_data_list) = retryable_connector_data {
- return Ok(ConnectorCallType::Retryable(connector_data_list));
+ if connector_data_list.len() > 1 {
+ logger::info!("Constructed apple pay retryable connector list");
+ return Ok(ConnectorCallType::Retryable(connector_data_list));
+ }
}
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 8f7ed4da256..74bfea22f2c 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3961,6 +3961,7 @@ pub fn get_applepay_metadata(
})
}
+#[cfg(all(feature = "retry", feature = "connector_choice_mca_id"))]
pub async fn get_apple_pay_retryable_connectors<F>(
state: AppState,
merchant_account: &domain::MerchantAccount,
@@ -3986,7 +3987,7 @@ where
merchant_account.merchant_id.as_str(),
payment_data.creds_identifier.to_owned(),
key_store,
- profile_id, // need to fix this
+ profile_id,
&decided_connector_data.connector_name.to_string(),
merchant_connector_id,
)
@@ -4008,9 +4009,14 @@ where
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
+ let profile_specific_merchant_connector_account_list = filter_mca_based_on_business_profile(
+ merchant_connector_account_list,
+ Some(profile_id.to_string()),
+ );
+
let mut connector_data_list = vec![decided_connector_data.clone()];
- for merchant_connector_account in merchant_connector_account_list {
+ for merchant_connector_account in profile_specific_merchant_connector_account_list {
if is_apple_pay_simplified_flow(
merchant_connector_account.metadata,
Some(&merchant_connector_account.connector_name),
@@ -4031,7 +4037,33 @@ where
}
}
}
- Some(connector_data_list)
+
+ let fallback_connetors_list = crate::core::routing::helpers::get_merchant_default_config(
+ &*state.clone().store,
+ profile_id,
+ &api_enums::TransactionType::Payment,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get merchant default fallback connectors config")?;
+
+ // 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 default fallback connectors configuration.
+ let mut ordered_connector_data_list = vec![decided_connector_data.clone()];
+ fallback_connetors_list
+ .iter()
+ .for_each(|fallback_connector| {
+ let connector_data = connector_data_list.iter().find(|connector_data| {
+ fallback_connector.merchant_connector_id == connector_data.merchant_connector_id
+ && fallback_connector.merchant_connector_id
+ != decided_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
};
|
2024-05-28T13:56:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently while fetching the apple pay retry connector list all the enabled merchant connector accounts for that specific merchant id is included. But we need to retry the connector with only the connectors in that specific profile id with which the payment attempt was created. Also range the apple pay retry connector in the default fallback configuration sequence.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create merchant connector accounts with apple pay simplified configured for some of them.
-> Use the below curl to set the default connectors
```
curl --location 'https://sandbox.hyperswitch.io/routing/default/profile/pro_SIWKUcl7KWmcoRroVz1r' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWJjZGIxYWItYmJiMS00YmY0LTgwYjQtNmQyYmM0NzIyZGUzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk5MzUwNTMzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwMDA1MjQwMCwib3JnX2lkIjoib3JnX0F3bmNqWFNUQW9ncUgwdUpVU2h2In0.WigP7IrTpBhP4LbWcimEJX0lJfnsjgEimOCOiBK1vxs' \
--data '[
{
"connector": "adyen",
"merchant_connector_id": "mca_NASIts6PGENwK4gd39mW"
},
{
"connector": "bluesnap",
"merchant_connector_id": "mca_E6t0JCvdefLSNoPUSGWh"
}
]'
```
<img width="1111" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/839b8e63-910d-4178-99b0-90017668dab3">
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_XoFL52XqqjWadvSrBkC4Kt91eIH5JUEgg9APgemwbWOnyxVYlT49S3kjDFRuoO65' \
--data-raw '{
"amount": 6500,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 6500,
"customer_id": "sai",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router"
}'
```
<img width="1142" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9f0baef3-2c35-474b-9741-4d5abe6219e9">
-> Do payment method list for the merchant
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_08tgyPCEZNQrMIvRBzzZ_secret_1MBVp3rgr2vqJfiH5Gyr' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_5d8a78ba4cf84af78765ff59ea249fc6'
```
<img width="1146" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/17c0e1b6-8e35-4509-bc9f-d06109bdd72b">
-> Confirm the payment with apple pay payment data
```
curl --location 'http://localhost:8080/payments/pay_08tgyPCEZNQrMIvRBzzZ/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_XoFL52XqqjWadvSrBkC4Kt91eIH5JUEgg9APgemwbWOnyxVYlT49S3kjDFRuoO65' \
--data '{
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0VtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433FCF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}'
```
<img width="1151" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/eea27285-d7dc-49f6-8a81-39a0c73dd8d6">
-> I had configured apple pay simplified flow for stripe, rapyd, adyen and manual flow for cybersource. And my default fallback list is stripe, rapyd, cybersource, adyen.
Below is the apple pay retry connector list
<img width="1030" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/225c4786-8175-4ce9-bf9b-9a377ef60f8e">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
865007717c5c7e617ca1b447ea5f9bb3d274cac3
|
-> Create merchant connector accounts with apple pay simplified configured for some of them.
-> Use the below curl to set the default connectors
```
curl --location 'https://sandbox.hyperswitch.io/routing/default/profile/pro_SIWKUcl7KWmcoRroVz1r' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWJjZGIxYWItYmJiMS00YmY0LTgwYjQtNmQyYmM0NzIyZGUzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk5MzUwNTMzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcwMDA1MjQwMCwib3JnX2lkIjoib3JnX0F3bmNqWFNUQW9ncUgwdUpVU2h2In0.WigP7IrTpBhP4LbWcimEJX0lJfnsjgEimOCOiBK1vxs' \
--data '[
{
"connector": "adyen",
"merchant_connector_id": "mca_NASIts6PGENwK4gd39mW"
},
{
"connector": "bluesnap",
"merchant_connector_id": "mca_E6t0JCvdefLSNoPUSGWh"
}
]'
```
<img width="1111" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/839b8e63-910d-4178-99b0-90017668dab3">
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_XoFL52XqqjWadvSrBkC4Kt91eIH5JUEgg9APgemwbWOnyxVYlT49S3kjDFRuoO65' \
--data-raw '{
"amount": 6500,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 6500,
"customer_id": "sai",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router"
}'
```
<img width="1142" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/9f0baef3-2c35-474b-9741-4d5abe6219e9">
-> Do payment method list for the merchant
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_08tgyPCEZNQrMIvRBzzZ_secret_1MBVp3rgr2vqJfiH5Gyr' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_5d8a78ba4cf84af78765ff59ea249fc6'
```
<img width="1146" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/17c0e1b6-8e35-4509-bc9f-d06109bdd72b">
-> Confirm the payment with apple pay payment data
```
curl --location 'http://localhost:8080/payments/pay_08tgyPCEZNQrMIvRBzzZ/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_XoFL52XqqjWadvSrBkC4Kt91eIH5JUEgg9APgemwbWOnyxVYlT49S3kjDFRuoO65' \
--data '{
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0VtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRmdzNldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433FCF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}'
```
<img width="1151" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/eea27285-d7dc-49f6-8a81-39a0c73dd8d6">
-> I had configured apple pay simplified flow for stripe, rapyd, adyen and manual flow for cybersource. And my default fallback list is stripe, rapyd, cybersource, adyen.
Below is the apple pay retry connector list
<img width="1030" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/225c4786-8175-4ce9-bf9b-9a377ef60f8e">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4805
|
Bug: Refactor Customers Payment Method List to support Client as well as S2S calls
### Feature Description
For Payment Methods v2, the customers payment method list will be supporting client based as well as S2S calls.
We are moving it under two distinct endpoints.
### Possible Implementation
The customers Payment method list will be moved under two distinct endpoints:
- For Client (with payment tokens) - `/payments/:id:/saved_payment_methods`
- For Server (without payment token) - `/customers/:cust_id:/saved_payment_methods`
Payment tokens for the listed payment methods would be generated only in case of client calls in a payments context.
|
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index f829d2e48fe..e2b9e2d3a55 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -24,6 +24,7 @@ customer_v2 = []
merchant_account_v2 = []
merchant_connector_account_v2 = []
payment_v2 = []
+payment_methods_v2 = []
routing_v2 = []
[dependencies]
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index ad2e2546f37..589dcd8d10b 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -1,12 +1,19 @@
use common_utils::events::{ApiEventMetric, ApiEventsType};
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
+use crate::payment_methods::CustomerPaymentMethodsListResponse;
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use crate::payment_methods::CustomerPaymentMethodsListResponse;
use crate::{
payment_methods::{
- CustomerDefaultPaymentMethodResponse, CustomerPaymentMethodsListResponse,
- DefaultPaymentMethod, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse,
- PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest,
- PaymentMethodCollectLinkResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest,
- PaymentMethodListResponse, PaymentMethodResponse, PaymentMethodUpdate,
+ CustomerDefaultPaymentMethodResponse, DefaultPaymentMethod, ListCountriesCurrenciesRequest,
+ ListCountriesCurrenciesResponse, PaymentMethodCollectLinkRenderRequest,
+ PaymentMethodCollectLinkRequest, PaymentMethodCollectLinkResponse,
+ PaymentMethodDeleteResponse, PaymentMethodListRequest, PaymentMethodListResponse,
+ PaymentMethodResponse, PaymentMethodUpdate,
},
payments::{
ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints,
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 3f1df4b8e96..c90031dc077 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -994,6 +994,19 @@ impl serde::Serialize for PaymentMethodList {
}
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct CustomerPaymentMethodsListResponse {
+ /// List of payment methods for customer
+ pub customer_payment_methods: Vec<CustomerPaymentMethod>,
+ /// Returns whether a customer id is not tied to a payment intent (only when the request is made against a client secret)
+ pub is_guest_customer: Option<bool>,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct CustomerPaymentMethodsListResponse {
/// List of payment methods for customer
@@ -1028,6 +1041,97 @@ pub struct CustomerDefaultPaymentMethodResponse {
pub payment_method_type: Option<api_enums::PaymentMethodType>,
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, Clone, serde::Serialize, ToSchema)]
+pub struct CustomerPaymentMethod {
+ /// Token for payment method in temporary card locker which gets refreshed often
+ #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")]
+ pub payment_token: Option<String>,
+ /// The unique identifier of the customer.
+ #[schema(example = "pm_iouuy468iyuowqs")]
+ pub payment_method_id: String,
+
+ /// The unique identifier of the customer.
+ #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
+ pub customer_id: id_type::CustomerId,
+
+ /// The type of payment method use for the payment.
+ #[schema(value_type = PaymentMethod,example = "card")]
+ pub payment_method: api_enums::PaymentMethod,
+
+ /// This is a sub-category of payment method.
+ #[schema(value_type = Option<PaymentMethodType>,example = "credit_card")]
+ pub payment_method_type: Option<api_enums::PaymentMethodType>,
+
+ /// The name of the bank/ provider issuing the payment method to the end user
+ #[schema(example = "Citibank")]
+ pub payment_method_issuer: Option<String>,
+
+ /// A standard code representing the issuer of payment method
+ #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")]
+ pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>,
+
+ /// Indicates whether the payment method is eligible for recurring payments
+ #[schema(example = true)]
+ pub recurring_enabled: bool,
+
+ /// Indicates whether the payment method is eligible for installment payments
+ #[schema(example = true)]
+ pub installment_payment_enabled: bool,
+
+ /// Type of payment experience enabled with the connector
+ #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))]
+ pub payment_experience: Option<Vec<api_enums::PaymentExperience>>,
+
+ /// PaymentMethod Data from locker
+ pub payment_method_data: Option<PaymentMethodListData>,
+
+ /// Masked bank details from PM auth services
+ #[schema(example = json!({"mask": "0000"}))]
+ pub bank: Option<MaskedBankDetails>,
+
+ /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
+ #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
+ pub metadata: Option<pii::SecretSerdeValue>,
+
+ /// A timestamp (ISO 8601 code) that determines when the customer was created
+ #[schema(value_type = Option<PrimitiveDateTime>,example = "2023-01-18T11:04:09.922Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub created: Option<time::PrimitiveDateTime>,
+
+ /// Surcharge details for this saved card
+ pub surcharge_details: Option<SurchargeDetailsResponse>,
+
+ /// Whether this payment method requires CVV to be collected
+ #[schema(example = true)]
+ pub requires_cvv: bool,
+
+ /// A timestamp (ISO 8601 code) that determines when the payment method was last used
+ #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")]
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub last_used_at: Option<time::PrimitiveDateTime>,
+ /// Indicates if the payment method has been set to default or not
+ #[schema(example = true)]
+ pub default_payment_method_set: bool,
+
+ /// The billing details of the payment method
+ #[schema(value_type = Option<Address>)]
+ pub billing: Option<payments::Address>,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+#[derive(Debug, Clone, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum PaymentMethodListData {
+ Card(CardDetailFromLocker),
+ #[cfg(feature = "payouts")]
+ Bank(payouts::Bank),
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct CustomerPaymentMethod {
/// Token for payment method in temporary card locker which gets refreshed often
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 3e6f470d80e..3492006261c 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -37,6 +37,7 @@ v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "stor
customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"]
merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant_account_v2", "hyperswitch_domain_models/merchant_account_v2"]
payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2"]
+payment_methods_v2 = ["api_models/payment_methods_v2"]
routing_v2 = ["api_models/routing_v2"]
merchant_connector_account_v2 = ["api_models/merchant_connector_account_v2", "kgraph_utils/merchant_connector_account_v2", "hyperswitch_domain_models/merchant_connector_account_v2", "diesel_models/merchant_connector_account_v2"]
diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs
index e2acc7b17b5..1dc43175342 100644
--- a/crates/router/src/compatibility/stripe/customers/types.rs
+++ b/crates/router/src/compatibility/stripe/customers/types.rs
@@ -193,7 +193,7 @@ pub struct CustomerPaymentMethodListResponse {
#[derive(Default, Serialize, PartialEq, Eq)]
pub struct PaymentMethodData {
- pub id: String,
+ pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
@@ -222,12 +222,29 @@ impl From<api::CustomerPaymentMethodsListResponse> for CustomerPaymentMethodList
}
}
+// Check this in review
impl From<api_types::CustomerPaymentMethod> for PaymentMethodData {
fn from(item: api_types::CustomerPaymentMethod) -> Self {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
+ let card = item.card.map(From::from);
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+ let card = match item.payment_method_data {
+ Some(api_types::PaymentMethodListData::Card(card)) => Some(CardDetails::from(card)),
+ _ => None,
+ };
Self {
+ #[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+ ))]
+ id: Some(item.payment_token),
+ #[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
id: item.payment_token,
object: "payment_method",
- card: item.card.map(From::from),
+ card,
created: item.created,
}
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 8cb64d1e0d8..f3bccf4d65f 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -48,6 +48,11 @@ use super::surcharge_decision_configs::{
perform_surcharge_decision_management_for_payment_method_list,
perform_surcharge_decision_management_for_saved_cards,
};
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
+use crate::routes::app::SessionStateInfo;
#[cfg(feature = "payouts")]
use crate::types::domain::types::AsyncLift;
use crate::{
@@ -67,7 +72,7 @@ use crate::{
},
db, logger,
pii::prelude::*,
- routes::{self, app::SessionStateInfo, metrics, payment_methods::ParentPaymentMethodToken},
+ routes::{self, metrics, payment_methods::ParentPaymentMethodToken},
services,
types::{
api::{self, routing as routing_types, PaymentMethodCreateExt},
@@ -3609,6 +3614,63 @@ fn filter_recurring_based(
recurring_enabled.map_or(true, |enabled| payment_method.recurring_enabled == enabled)
}
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn list_customer_payment_method_util(
+ state: routes::SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ req: Option<api::PaymentMethodListRequest>,
+ customer_id: Option<id_type::CustomerId>,
+ is_payment_associated: bool,
+) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
+ let limit = req.as_ref().and_then(|pml_req| pml_req.limit);
+
+ let (customer_id, payment_intent) = if is_payment_associated {
+ let cloned_secret = req.and_then(|r| r.client_secret.clone());
+ let payment_intent = helpers::verify_payment_intent_time_and_client_secret(
+ &state,
+ &merchant_account,
+ &key_store,
+ cloned_secret,
+ )
+ .await?;
+
+ (
+ payment_intent
+ .as_ref()
+ .and_then(|pi| pi.customer_id.clone()),
+ payment_intent,
+ )
+ } else {
+ (customer_id, None)
+ };
+
+ let resp = if let Some(cust) = customer_id {
+ Box::pin(list_customer_payment_method(
+ &state,
+ merchant_account,
+ key_store,
+ payment_intent,
+ &cust,
+ limit,
+ is_payment_associated,
+ ))
+ .await?
+ } else {
+ let response = api::CustomerPaymentMethodsListResponse {
+ customer_payment_methods: Vec::new(),
+ is_guest_customer: Some(true),
+ };
+ services::ApplicationResponse::Json(response)
+ };
+
+ Ok(resp)
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
state: routes::SessionState,
merchant_account: domain::MerchantAccount,
@@ -3680,6 +3742,10 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
}
}
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn list_customer_payment_method(
state: &routes::SessionState,
merchant_account: domain::MerchantAccount,
@@ -3767,88 +3833,21 @@ pub async fn list_customer_payment_method(
let payment_method = pm.payment_method.get_required_value("payment_method")?;
- let payment_method_retrieval_context = match payment_method {
- enums::PaymentMethod::Card => {
- let card_details =
- get_card_details_with_locker_fallback(&pm, state, &key_store).await?;
-
- if card_details.is_some() {
- PaymentMethodListContext {
- card_details,
- #[cfg(feature = "payouts")]
- bank_transfer_details: None,
- hyperswitch_token_data: PaymentTokenData::permanent_card(
- Some(pm.payment_method_id.clone()),
- pm.locker_id.clone().or(Some(pm.payment_method_id.clone())),
- pm.locker_id.clone().unwrap_or(pm.payment_method_id.clone()),
- ),
- }
- } else {
- continue;
- }
- }
-
- enums::PaymentMethod::BankDebit => {
- // Retrieve the pm_auth connector details so that it can be tokenized
- let bank_account_token_data =
- get_bank_account_connector_details(state, &pm, &key_store)
- .await
- .unwrap_or_else(|error| {
- logger::error!(?error);
- None
- });
- if let Some(data) = bank_account_token_data {
- let token_data = PaymentTokenData::AuthBankDebit(data);
-
- PaymentMethodListContext {
- card_details: None,
- #[cfg(feature = "payouts")]
- bank_transfer_details: None,
- hyperswitch_token_data: token_data,
- }
- } else {
- continue;
- }
- }
-
- enums::PaymentMethod::Wallet => PaymentMethodListContext {
- card_details: None,
- #[cfg(feature = "payouts")]
- bank_transfer_details: None,
- hyperswitch_token_data: PaymentTokenData::wallet_token(
- pm.payment_method_id.clone(),
- ),
- },
+ let pm_list_context = get_pm_list_context(
+ state,
+ &payment_method,
+ &key_store,
+ &pm,
+ Some(parent_payment_method_token.clone()),
+ true,
+ )
+ .await?;
- #[cfg(feature = "payouts")]
- enums::PaymentMethod::BankTransfer => PaymentMethodListContext {
- card_details: None,
- bank_transfer_details: Some(
- get_bank_from_hs_locker(
- state,
- &key_store,
- &parent_payment_method_token,
- &pm.customer_id,
- &pm.merchant_id,
- pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
- )
- .await?,
- ),
- hyperswitch_token_data: PaymentTokenData::temporary_generic(
- parent_payment_method_token.clone(),
- ),
- },
+ if pm_list_context.is_none() {
+ continue;
+ }
- _ => PaymentMethodListContext {
- card_details: None,
- #[cfg(feature = "payouts")]
- bank_transfer_details: None,
- hyperswitch_token_data: PaymentTokenData::temporary_generic(generate_id(
- consts::ID_LENGTH,
- "token",
- )),
- },
- };
+ let pm_list_context = pm_list_context.get_required_value("PaymentMethodListContext")?;
// Retrieve the masked bank details to be sent as a response
let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
@@ -3904,7 +3903,7 @@ pub async fn list_customer_payment_method(
payment_method,
payment_method_type: pm.payment_method_type,
payment_method_issuer: pm.payment_method_issuer,
- card: payment_method_retrieval_context.card_details,
+ card: pm_list_context.card_details,
metadata: pm.metadata,
payment_method_issuer_code: pm.payment_method_issuer_code,
recurring_enabled: mca_enabled,
@@ -3912,7 +3911,7 @@ pub async fn list_customer_payment_method(
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
created: Some(pm.created_at),
#[cfg(feature = "payouts")]
- bank_transfer: payment_method_retrieval_context.bank_transfer_details,
+ bank_transfer: pm_list_context.bank_transfer_details,
bank: bank_details,
surcharge_details: None,
requires_cvv,
@@ -3934,15 +3933,15 @@ pub async fn list_customer_payment_method(
.and_then(|b_profile| b_profile.intent_fulfillment_time)
.unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME);
+ let hyperswitch_token_data = pm_list_context
+ .hyperswitch_token_data
+ .get_required_value("PaymentTokenData")?;
+
ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
pma.payment_method,
))
- .insert(
- intent_fulfillment_time,
- payment_method_retrieval_context.hyperswitch_token_data,
- state,
- )
+ .insert(intent_fulfillment_time, hyperswitch_token_data, state)
.await?;
if let Some(metadata) = pma.metadata {
@@ -3973,6 +3972,115 @@ pub async fn list_customer_payment_method(
customer_payment_methods: customer_pms,
is_guest_customer: payment_intent.as_ref().map(|_| false), //to return this key only when the request is tied to a payment intent
};
+
+ Box::pin(perform_surcharge_ops(
+ payment_intent,
+ state,
+ merchant_account,
+ key_store,
+ business_profile,
+ &mut response,
+ ))
+ .await?;
+
+ Ok(services::ApplicationResponse::Json(response))
+}
+
+async fn get_pm_list_context(
+ state: &routes::SessionState,
+ payment_method: &enums::PaymentMethod,
+ key_store: &domain::MerchantKeyStore,
+ pm: &diesel_models::PaymentMethod,
+ #[cfg(feature = "payouts")] parent_payment_method_token: Option<String>,
+ #[cfg(not(feature = "payouts"))] _parent_payment_method_token: Option<String>,
+ is_payment_associated: bool,
+) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
+ let payment_method_retrieval_context = match payment_method {
+ enums::PaymentMethod::Card => {
+ let card_details = get_card_details_with_locker_fallback(pm, state, key_store).await?;
+
+ card_details.as_ref().map(|card| PaymentMethodListContext {
+ card_details: Some(card.clone()),
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated.then_some(
+ PaymentTokenData::permanent_card(
+ Some(pm.payment_method_id.clone()),
+ pm.locker_id.clone().or(Some(pm.payment_method_id.clone())),
+ pm.locker_id.clone().unwrap_or(pm.payment_method_id.clone()),
+ ),
+ ),
+ })
+ }
+
+ enums::PaymentMethod::BankDebit => {
+ // Retrieve the pm_auth connector details so that it can be tokenized
+ let bank_account_token_data = get_bank_account_connector_details(state, pm, key_store)
+ .await
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ });
+
+ bank_account_token_data.map(|data| {
+ let token_data = PaymentTokenData::AuthBankDebit(data);
+
+ PaymentMethodListContext {
+ card_details: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated.then_some(token_data),
+ }
+ })
+ }
+
+ enums::PaymentMethod::Wallet => Some(PaymentMethodListContext {
+ card_details: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated
+ .then_some(PaymentTokenData::wallet_token(pm.payment_method_id.clone())),
+ }),
+
+ #[cfg(feature = "payouts")]
+ enums::PaymentMethod::BankTransfer => Some(PaymentMethodListContext {
+ card_details: None,
+ bank_transfer_details: Some(
+ get_bank_from_hs_locker(
+ state,
+ key_store,
+ parent_payment_method_token.as_ref(),
+ &pm.customer_id,
+ &pm.merchant_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ )
+ .await?,
+ ),
+ hyperswitch_token_data: parent_payment_method_token
+ .map(|token| PaymentTokenData::temporary_generic(token.clone())),
+ }),
+
+ _ => Some(PaymentMethodListContext {
+ card_details: None,
+ #[cfg(feature = "payouts")]
+ bank_transfer_details: None,
+ hyperswitch_token_data: is_payment_associated.then_some(
+ PaymentTokenData::temporary_generic(generate_id(consts::ID_LENGTH, "token")),
+ ),
+ }),
+ };
+
+ Ok(payment_method_retrieval_context)
+}
+
+async fn perform_surcharge_ops(
+ payment_intent: Option<storage::PaymentIntent>,
+ state: &routes::SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ business_profile: Option<BusinessProfile>,
+ response: &mut api::CustomerPaymentMethodsListResponse,
+) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
let payment_attempt = payment_intent
.as_ref()
.async_map(|payment_intent| async {
@@ -3989,7 +4097,6 @@ pub async fn list_customer_payment_method(
})
.await
.transpose()?;
-
if let Some((payment_attempt, payment_intent, business_profile)) = payment_attempt
.zip(payment_intent)
.zip(business_profile)
@@ -4002,13 +4109,355 @@ pub async fn list_customer_payment_method(
&business_profile,
&payment_attempt,
payment_intent,
- &mut response,
+ response,
+ )
+ .await?;
+ }
+
+ Ok(())
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+struct SavedPMLPaymentsInfo {
+ pub payment_intent: storage::PaymentIntent,
+ pub business_profile: Option<BusinessProfile>,
+ pub requires_cvv: bool,
+ pub off_session_payment_flag: bool,
+ pub is_connector_agnostic_mit_enabled: bool,
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+impl SavedPMLPaymentsInfo {
+ pub async fn form_payments_info(
+ payment_intent: storage::PaymentIntent,
+ merchant_account: &domain::MerchantAccount,
+ db: &dyn db::StorageInterface,
+ ) -> errors::RouterResult<Self> {
+ let requires_cvv = db
+ .find_config_by_key_unwrap_or(
+ format!("{}_requires_cvv", merchant_account.get_id()).as_str(),
+ Some("true".to_string()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch requires_cvv config")?
+ .config
+ != "false";
+
+ let off_session_payment_flag = matches!(
+ payment_intent.setup_future_usage,
+ Some(common_enums::FutureUsage::OffSession)
+ );
+
+ let profile_id = core_utils::get_profile_id_from_business_details(
+ payment_intent.business_country,
+ payment_intent.business_label.as_ref(),
+ merchant_account,
+ payment_intent.profile_id.as_ref(),
+ db,
+ false,
+ )
+ .await
+ .attach_printable("Could not find profile id from business details")?;
+
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ Some(profile_id).as_ref(),
+ merchant_account.get_id(),
)
.await?;
+
+ let is_connector_agnostic_mit_enabled = business_profile
+ .as_ref()
+ .and_then(|business_profile| business_profile.is_connector_agnostic_mit_enabled)
+ .unwrap_or(false);
+
+ Ok(Self {
+ payment_intent,
+ business_profile,
+ requires_cvv,
+ off_session_payment_flag,
+ is_connector_agnostic_mit_enabled,
+ })
+ }
+
+ pub async fn perform_payment_ops(
+ &self,
+ state: &routes::SessionState,
+ parent_payment_method_token: Option<String>,
+ pma: &api::CustomerPaymentMethod,
+ pm_list_context: PaymentMethodListContext,
+ ) -> errors::RouterResult<()> {
+ let token = parent_payment_method_token
+ .as_ref()
+ .get_required_value("parent_payment_method_token")?;
+ let hyperswitch_token_data = pm_list_context
+ .hyperswitch_token_data
+ .get_required_value("PaymentTokenData")?;
+
+ let intent_fulfillment_time = self
+ .business_profile
+ .as_ref()
+ .and_then(|b_profile| b_profile.intent_fulfillment_time)
+ .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME);
+
+ ParentPaymentMethodToken::create_key_for_token((token, pma.payment_method))
+ .insert(intent_fulfillment_time, hyperswitch_token_data, state)
+ .await?;
+
+ if let Some(metadata) = pma.metadata.clone() {
+ let pm_metadata_vec: payment_methods::PaymentMethodMetadata = metadata
+ .parse_value("PaymentMethodMetadata")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to deserialize metadata to PaymentmethodMetadata struct",
+ )?;
+
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ for pm_metadata in pm_metadata_vec.payment_method_tokenization {
+ let key = format!(
+ "pm_token_{}_{}_{}",
+ token, pma.payment_method, pm_metadata.0
+ );
+
+ redis_conn
+ .set_key_with_expiry(&key, pm_metadata.1, intent_fulfillment_time)
+ .await
+ .change_context(errors::StorageError::KVError)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add data in redis")?;
+ }
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn list_customer_payment_method(
+ state: &routes::SessionState,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ payment_intent: Option<storage::PaymentIntent>,
+ customer_id: &id_type::CustomerId,
+ limit: Option<i64>,
+ is_payment_associated: bool,
+) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
+ let db = &*state.store;
+ let key_manager_state = &(state).into();
+ // let key = key_store.key.get_inner().peek();
+
+ let customer = db
+ .find_customer_by_customer_id_merchant_id(
+ key_manager_state,
+ customer_id,
+ merchant_account.get_id(),
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let payments_info = payment_intent
+ .async_map(|pi| SavedPMLPaymentsInfo::form_payments_info(pi, &merchant_account, db))
+ .await
+ .transpose()?;
+
+ let saved_payment_methods = db
+ .find_payment_method_by_customer_id_merchant_id_status(
+ customer_id,
+ merchant_account.get_id(),
+ common_enums::PaymentMethodStatus::Active,
+ limit,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ let mut filtered_saved_payment_methods_ctx = Vec::new();
+ for pm in saved_payment_methods.into_iter() {
+ let payment_method = pm.payment_method.get_required_value("payment_method")?;
+ let parent_payment_method_token =
+ is_payment_associated.then(|| generate_id(consts::ID_LENGTH, "token"));
+
+ let pm_list_context = get_pm_list_context(
+ state,
+ &payment_method,
+ &key_store,
+ &pm,
+ parent_payment_method_token.clone(),
+ is_payment_associated,
+ )
+ .await?;
+
+ if let Some(ctx) = pm_list_context {
+ filtered_saved_payment_methods_ctx.push((ctx, parent_payment_method_token, pm));
+ }
+ }
+
+ let pm_list_futures = filtered_saved_payment_methods_ctx
+ .into_iter()
+ .map(|ctx| {
+ generate_saved_pm_response(
+ state,
+ &key_store,
+ &merchant_account,
+ ctx,
+ &customer,
+ payments_info.as_ref(),
+ )
+ })
+ .collect::<Vec<_>>();
+
+ let final_result = futures::future::join_all(pm_list_futures).await;
+
+ let mut customer_pms = Vec::new();
+ for result in final_result.into_iter() {
+ let pma = result.attach_printable("saved pm list failed")?;
+ customer_pms.push(pma);
+ }
+
+ let mut response = api::CustomerPaymentMethodsListResponse {
+ customer_payment_methods: customer_pms,
+ is_guest_customer: is_payment_associated.then_some(false), //to return this key only when the request is tied to a payment intent
+ };
+
+ if is_payment_associated {
+ Box::pin(perform_surcharge_ops(
+ payments_info.as_ref().map(|pi| pi.payment_intent.clone()),
+ state,
+ merchant_account,
+ key_store,
+ payments_info.and_then(|pi| pi.business_profile),
+ &mut response,
+ ))
+ .await?;
}
Ok(services::ApplicationResponse::Json(response))
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+async fn generate_saved_pm_response(
+ state: &routes::SessionState,
+ key_store: &domain::MerchantKeyStore,
+ merchant_account: &domain::MerchantAccount,
+ pm_list_context: (
+ PaymentMethodListContext,
+ Option<String>,
+ diesel_models::PaymentMethod,
+ ),
+ customer: &domain::Customer,
+ payment_info: Option<&SavedPMLPaymentsInfo>,
+) -> Result<api::CustomerPaymentMethod, error_stack::Report<errors::ApiErrorResponse>> {
+ let (pm_list_context, parent_payment_method_token, pm) = pm_list_context;
+ let payment_method = pm.payment_method.get_required_value("payment_method")?;
+
+ let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
+ get_masked_bank_details(state, &pm, key_store)
+ .await
+ .unwrap_or_else(|err| {
+ logger::error!(error=?err);
+ None
+ })
+ } else {
+ None
+ };
+
+ let payment_method_billing = decrypt_generic_data::<api_models::payments::Address>(
+ state,
+ pm.payment_method_billing_address,
+ key_store,
+ )
+ .await
+ .attach_printable("unable to decrypt payment method billing address details")?;
+
+ let connector_mandate_details = pm
+ .connector_mandate_details
+ .clone()
+ .map(|val| val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference"))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
+
+ let (is_connector_agnostic_mit_enabled, requires_cvv, off_session_payment_flag) = payment_info
+ .map(|pi| {
+ (
+ pi.is_connector_agnostic_mit_enabled,
+ pi.requires_cvv,
+ pi.off_session_payment_flag,
+ )
+ })
+ .unwrap_or((false, false, false));
+
+ let mca_enabled = get_mca_status(
+ state,
+ key_store,
+ merchant_account.get_id(),
+ is_connector_agnostic_mit_enabled,
+ connector_mandate_details,
+ pm.network_transaction_id.as_ref(),
+ )
+ .await?;
+
+ let requires_cvv = if is_connector_agnostic_mit_enabled {
+ requires_cvv
+ && !(off_session_payment_flag
+ && (pm.connector_mandate_details.is_some() || pm.network_transaction_id.is_some()))
+ } else {
+ requires_cvv && !(off_session_payment_flag && pm.connector_mandate_details.is_some())
+ };
+
+ let pmd = if let Some(card) = pm_list_context.card_details.as_ref() {
+ Some(api::PaymentMethodListData::Card(card.clone()))
+ } else if cfg!(feature = "payouts") {
+ pm_list_context
+ .bank_transfer_details
+ .clone()
+ .map(api::PaymentMethodListData::Bank)
+ } else {
+ None
+ };
+
+ let pma = api::CustomerPaymentMethod {
+ payment_token: parent_payment_method_token.clone(),
+ payment_method_id: pm.payment_method_id.clone(),
+ customer_id: pm.customer_id,
+ payment_method,
+ payment_method_type: pm.payment_method_type,
+ payment_method_issuer: pm.payment_method_issuer,
+ payment_method_data: pmd,
+ metadata: pm.metadata,
+ payment_method_issuer_code: pm.payment_method_issuer_code,
+ recurring_enabled: mca_enabled,
+ installment_payment_enabled: false,
+ payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
+ created: Some(pm.created_at),
+ bank: bank_details,
+ surcharge_details: None,
+ requires_cvv: requires_cvv
+ && !(off_session_payment_flag && pm.connector_mandate_details.is_some()),
+ last_used_at: Some(pm.last_used_at),
+ default_payment_method_set: customer.default_payment_method_id.is_some()
+ && customer.default_payment_method_id == Some(pm.payment_method_id),
+ billing: payment_method_billing,
+ };
+
+ payment_info
+ .async_map(|pi| {
+ pi.perform_payment_ops(state, parent_payment_method_token, &pma, pm_list_context)
+ })
+ .await
+ .transpose()?;
+
+ Ok(pma)
+}
+
pub async fn get_mca_status(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
@@ -4396,7 +4845,7 @@ pub async fn update_last_used_at(
pub async fn get_bank_from_hs_locker(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
- temp_token: &str,
+ temp_token: Option<&String>,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
token_ref: &str,
@@ -4419,16 +4868,18 @@ pub async fn get_bank_from_hs_locker(
.change_context(errors::ApiErrorResponse::InternalServerError)?;
match &pm_parsed {
api::PayoutMethodData::Bank(bank) => {
- vault::Vault::store_payout_method_data_in_locker(
- state,
- Some(temp_token.to_string()),
- &pm_parsed,
- Some(customer_id.to_owned()),
- key_store,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error storing payout method data in temporary locker")?;
+ if let Some(token) = temp_token {
+ vault::Vault::store_payout_method_data_in_locker(
+ state,
+ Some(token.clone()),
+ &pm_parsed,
+ Some(customer_id.to_owned()),
+ key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error storing payout method data in temporary locker")?;
+ }
Ok(bank.to_owned())
}
api::PayoutMethodData::Card(_) => Err(errors::ApiErrorResponse::InvalidRequestData {
diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
index 6a3ceeada1c..23f79848dee 100644
--- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
+++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
@@ -3,7 +3,16 @@ use api_models::{
payments, routing,
surcharge_decision_configs::{self, SurchargeDecisionConfigs, SurchargeDecisionManagerRecord},
};
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
use common_utils::{ext_traits::StringExt, types as common_utils_types};
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+use common_utils::{
+ ext_traits::{OptionExt, StringExt},
+ types as common_utils_types,
+};
use error_stack::{self, ResultExt};
use euclid::{
backend,
@@ -267,6 +276,11 @@ where
}
Ok(surcharge_metadata)
}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "payment_methods_v2")
+))]
pub async fn perform_surcharge_decision_management_for_saved_cards(
state: &SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
@@ -303,10 +317,13 @@ pub async fn perform_surcharge_decision_management_for_saved_cards(
.change_context(ConfigError::InputConstructionError)?;
for customer_payment_method in customer_payment_method_list.iter_mut() {
+ let payment_token = customer_payment_method.payment_token.clone();
+
backend_input.payment_method.payment_method = Some(customer_payment_method.payment_method);
backend_input.payment_method.payment_method_type =
customer_payment_method.payment_method_type;
- backend_input.payment_method.card_network = customer_payment_method
+
+ let card_network = customer_payment_method
.card
.as_ref()
.and_then(|card| card.scheme.as_ref())
@@ -317,13 +334,98 @@ pub async fn perform_surcharge_decision_management_for_saved_cards(
.change_context(ConfigError::DslExecutionError)
})
.transpose()?;
+
+ backend_input.payment_method.card_network = card_network;
+
+ let surcharge_details = surcharge_source
+ .generate_surcharge_details_and_populate_surcharge_metadata(
+ &backend_input,
+ payment_attempt,
+ (
+ &mut surcharge_metadata,
+ types::SurchargeKey::Token(payment_token),
+ ),
+ )?;
+ customer_payment_method.surcharge_details = surcharge_details
+ .map(|surcharge_details| {
+ SurchargeDetailsResponse::foreign_try_from((&surcharge_details, payment_attempt))
+ .change_context(ConfigError::DslParsingError)
+ })
+ .transpose()?;
+ }
+ Ok(surcharge_metadata)
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub async fn perform_surcharge_decision_management_for_saved_cards(
+ state: &SessionState,
+ algorithm_ref: routing::RoutingAlgorithmRef,
+ payment_attempt: &storage::PaymentAttempt,
+ payment_intent: &storage::PaymentIntent,
+ customer_payment_method_list: &mut [api_models::payment_methods::CustomerPaymentMethod],
+) -> ConditionalConfigResult<types::SurchargeMetadata> {
+ let mut surcharge_metadata = types::SurchargeMetadata::new(payment_attempt.attempt_id.clone());
+ let surcharge_source = match (
+ payment_attempt.get_surcharge_details(),
+ algorithm_ref.surcharge_config_algo_id,
+ ) {
+ (Some(request_surcharge_details), _) => {
+ SurchargeSource::Predetermined(request_surcharge_details)
+ }
+ (None, Some(algorithm_id)) => {
+ let cached_algo = ensure_algorithm_cached(
+ &*state.store,
+ &payment_attempt.merchant_id,
+ algorithm_id.as_str(),
+ )
+ .await?;
+
+ SurchargeSource::Generate(cached_algo)
+ }
+ (None, None) => return Ok(surcharge_metadata),
+ };
+ let surcharge_source_log_message = match &surcharge_source {
+ SurchargeSource::Generate(_) => "Surcharge was calculated through surcharge rules",
+ SurchargeSource::Predetermined(_) => "Surcharge was sent in payment create request",
+ };
+ logger::debug!(customer_saved_card_list_surcharge_source = surcharge_source_log_message);
+ let mut backend_input = make_dsl_input_for_surcharge(payment_attempt, payment_intent, None)
+ .change_context(ConfigError::InputConstructionError)?;
+
+ for customer_payment_method in customer_payment_method_list.iter_mut() {
+ let payment_token = customer_payment_method
+ .payment_token
+ .clone()
+ .get_required_value("payment_token")
+ .change_context(ConfigError::InputConstructionError)?;
+
+ backend_input.payment_method.payment_method = Some(customer_payment_method.payment_method);
+ backend_input.payment_method.payment_method_type =
+ customer_payment_method.payment_method_type;
+
+ let card_network = match &customer_payment_method.payment_method_data {
+ Some(api_models::payment_methods::PaymentMethodListData::Card(card)) => card
+ .scheme
+ .as_ref()
+ .map(|scheme| {
+ scheme
+ .clone()
+ .parse_enum("CardNetwork")
+ .change_context(ConfigError::DslExecutionError)
+ })
+ .transpose()?,
+ _ => None,
+ };
+
+ backend_input.payment_method.card_network = card_network;
+
let surcharge_details = surcharge_source
.generate_surcharge_details_and_populate_surcharge_metadata(
&backend_input,
payment_attempt,
(
&mut surcharge_metadata,
- types::SurchargeKey::Token(customer_payment_method.payment_token.clone()),
+ types::SurchargeKey::Token(payment_token),
),
)?;
customer_payment_method.surcharge_details = surcharge_details
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 708fcbbf406..2286ee8265c 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -30,7 +30,7 @@ use super::blocklist;
use super::currency;
#[cfg(feature = "dummy_connector")]
use super::dummy_connector::*;
-#[cfg(all(any(feature = "olap", feature = "oltp"), not(feature = "customer_v2")))]
+#[cfg(any(feature = "olap", feature = "oltp"))]
use super::payment_methods::*;
#[cfg(feature = "payouts")]
use super::payout_link::*;
@@ -501,7 +501,30 @@ impl DummyConnector {
pub struct Payments;
-#[cfg(any(feature = "olap", feature = "oltp"))]
+#[cfg(all(
+ any(feature = "olap", feature = "oltp"),
+ feature = "v2",
+ feature = "payment_methods_v2",
+ feature = "payment_v2"
+))]
+impl Payments {
+ pub fn server(state: AppState) -> Scope {
+ let mut route = web::scope("/v2/payments").app_data(web::Data::new(state));
+ route = route.service(
+ web::resource("/{payment_id}/saved_payment_methods")
+ .route(web::get().to(list_customer_payment_method_for_payment)),
+ );
+
+ route
+ }
+}
+
+#[cfg(all(
+ any(feature = "olap", feature = "oltp"),
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2"),
+ not(feature = "payment_v2")
+))]
impl Payments {
pub fn server(state: AppState) -> Scope {
let mut route = web::scope("/payments").app_data(web::Data::new(state));
@@ -590,7 +613,7 @@ impl Payments {
)
.service(
web::resource("/{payment_id}/extended_card_info").route(web::get().to(retrieve_extended_card_info)),
- );
+ )
}
route
}
@@ -844,6 +867,7 @@ pub struct Customers;
#[cfg(all(
feature = "v2",
feature = "customer_v2",
+ feature = "payment_methods_v2",
any(feature = "olap", feature = "oltp")
))]
impl Customers {
@@ -853,6 +877,13 @@ impl Customers {
{
route = route.service(web::resource("").route(web::post().to(customers_create)))
}
+ #[cfg(all(feature = "oltp", feature = "v2", feature = "payment_methods_v2"))]
+ {
+ route = route.service(
+ web::resource("/{customer_id}/saved_payment_methods")
+ .route(web::get().to(list_customer_payment_method_api)),
+ );
+ }
route
}
}
@@ -860,6 +891,7 @@ impl Customers {
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "customer_v2"),
+ not(feature = "payment_methods_v2"),
any(feature = "olap", feature = "oltp")
))]
impl Customers {
@@ -897,13 +929,12 @@ impl Customers {
.route(web::get().to(customers_retrieve))
.route(web::post().to(customers_update))
.route(web::delete().to(customers_delete)),
- );
+ )
}
route
}
}
-
pub struct Refunds;
#[cfg(any(feature = "olap", feature = "oltp"))]
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index f55f6c80e7a..6d7b3526b79 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -229,6 +229,11 @@ pub async fn list_payment_method_api(
))
.await
}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
@@ -287,6 +292,134 @@ pub async fn list_customer_payment_method_api(
))
.await
}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+/// List payment methods for a Customer v2
+///
+/// To filter and list the applicable payment methods for a particular Customer ID, is to be associated with a payment
+#[utoipa::path(
+ get,
+ path = "v2/payments/{payment_id}/saved_payment_methods",
+ params (
+ ("client-secret" = String, Path, description = "A secret known only to your application and the authorization server"),
+ ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"),
+ ("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"),
+ ("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."),
+ ("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."),
+ ("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
+ ("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"),
+ ),
+ responses(
+ (status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
+ (status = 400, description = "Invalid Data"),
+ (status = 404, description = "Payment Methods does not exist in records")
+ ),
+ tag = "Payment Methods",
+ operation_id = "List all Payment Methods for a Customer",
+ security(("publishable_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
+pub async fn list_customer_payment_method_for_payment(
+ state: web::Data<AppState>,
+ payment_id: web::Path<(String,)>,
+ req: HttpRequest,
+ query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
+) -> HttpResponse {
+ let flow = Flow::CustomerPaymentMethodsList;
+ let payload = query_payload.into_inner();
+ let _payment_id = payment_id.into_inner().0.clone();
+
+ let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
+ Ok((auth, _auth_flow)) => (auth, _auth_flow),
+ Err(e) => return api::log_and_return_error_response(e),
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ cards::list_customer_payment_method_util(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ Some(req),
+ None,
+ true,
+ )
+ },
+ &*auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+/// List payment methods for a Customer v2
+///
+/// To filter and list the applicable payment methods for a particular Customer ID, to be used in a non-payments context
+#[utoipa::path(
+ get,
+ path = "v2/customers/{customer_id}/saved_payment_methods",
+ params (
+ ("accepted_country" = Vec<String>, Query, description = "The two-letter ISO currency code"),
+ ("accepted_currency" = Vec<Currency>, Path, description = "The three-letter ISO currency code"),
+ ("minimum_amount" = i64, Query, description = "The minimum amount accepted for processing by the particular payment method."),
+ ("maximum_amount" = i64, Query, description = "The maximum amount amount accepted for processing by the particular payment method."),
+ ("recurring_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
+ ("installment_payment_enabled" = bool, Query, description = "Indicates whether the payment method is eligible for installment payments"),
+ ),
+ responses(
+ (status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
+ (status = 400, description = "Invalid Data"),
+ (status = 404, description = "Payment Methods does not exist in records")
+ ),
+ tag = "Payment Methods",
+ operation_id = "List all Payment Methods for a Customer",
+ security(("api_key" = []))
+)]
+#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
+pub async fn list_customer_payment_method_api(
+ state: web::Data<AppState>,
+ customer_id: web::Path<(id_type::CustomerId,)>,
+ req: HttpRequest,
+ query_payload: web::Query<payment_methods::PaymentMethodListRequest>,
+) -> HttpResponse {
+ let flow = Flow::CustomerPaymentMethodsList;
+ let payload = query_payload.into_inner();
+ let customer_id = customer_id.into_inner().0.clone();
+
+ let ephemeral_or_api_auth = match auth::is_ephemeral_auth(req.headers()) {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ cards::list_customer_payment_method_util(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ Some(req),
+ Some(customer_id.clone()),
+ false,
+ )
+ },
+ &*ephemeral_or_api_auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
/// List payment methods for a Customer
///
/// To filter and list the applicable payment methods for a particular Customer ID
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index 77873503d6e..062a2fdf630 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -1,3 +1,19 @@
+#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
+pub use api_models::payment_methods::{
+ CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod,
+ CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
+ GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest,
+ PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCreate,
+ PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList,
+ PaymentMethodListData, PaymentMethodListRequest, PaymentMethodListResponse,
+ PaymentMethodMigrate, PaymentMethodResponse, PaymentMethodUpdate, PaymentMethodsData,
+ TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
+ TokenizedWalletValue1, TokenizedWalletValue2,
+};
+#[cfg(all(
+ any(feature = "v2", feature = "v1"),
+ not(feature = "payment_methods_v2")
+))]
pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod,
CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 8a8f89f9017..05e3e566c07 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -81,7 +81,7 @@ impl PaymentTokenData {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentMethodListContext {
pub card_details: Option<api::CardDetailFromLocker>,
- pub hyperswitch_token_data: PaymentTokenData,
+ pub hyperswitch_token_data: Option<PaymentTokenData>,
#[cfg(feature = "payouts")]
pub bank_transfer_details: Option<api::BankPayout>,
}
|
2024-06-03T13:32:14Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Refactored customer's pml for v2
The customers Payment method list will be moved under two distinct endpoints:
For Client (with payment tokens) - /payments/:id:/saved_payment_methods
For Server (without payment token) - /customers/:cust_id:/saved_payment_methods
Payment tokens for the listed payment methods would be generated only in case of client calls in a payments context.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Save a card
- Create another payment
```
curl --location --request POST 'http://localhost:8080/v2/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \
--data-raw '{
"amount": 200,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "Some_cust2",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response -
```
{
"payment_id": "pay_GNxoHRthb37nMZt6KLhv",
"merchant_id": "sarthak1",
"status": "requires_payment_method",
"amount": 200,
"net_amount": 200,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_GNxoHRthb37nMZt6KLhv_secret_G97qG0GJ85JeGks8NmnA",
"created": "2024-07-02T09:56:52.153Z",
"currency": "USD",
"customer_id": "Some_cust2",
"customer": {
"id": "Some_cust2",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "Some_cust2",
"created_at": 1719914212,
"expires": 1719917812,
"secret": "epk_7299286e8535424b957d32f6f5e44e99"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_1HgRzJgJf21X3s7FPrhP",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-02T10:11:52.153Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-02T09:56:52.226Z",
"charges": null,
"frm_metadata": null
}
```
- List saved payment method for v2
```
curl --location --request GET 'http://localhost:8080/v2/payments/pay_GNxoHRthb37nMZt6KLhv/saved_payment_methods?client_secret=pay_GNxoHRthb37nMZt6KLhv_secret_G97qG0GJ85JeGks8NmnA' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d'
```
Response -
```
{
"customer_payment_methods": [
{
"payment_token": "token_SBCX3r5nb9QaHNGtSbgK",
"payment_method_id": "pm_R8n4IKXyEpAGcKaEQl0g",
"customer_id": "Some_cust2",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"payment_method_data": {
"Card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2025",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
}
},
"bank": null,
"metadata": null,
"created": "2024-06-26T08:26:47.674Z",
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-06-26T10:39:30.552Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_nvHY8mkVcPYA94KQefdx",
"payment_method_id": "pm_xFF1OOhEMqVQhzEv3b06",
"customer_id": "Some_cust2",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"payment_method_data": {
"Card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2025",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
}
},
"bank": null,
"metadata": null,
"created": "2024-06-13T11:55:47.828Z",
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-06-13T11:55:47.828Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
}
],
"is_guest_customer": false
}
```
- Use Merchant API for saved payment methods -
```
curl --location --request GET 'http://localhost:8080/v2/customers/Some_cust2/saved_payment_methods' \
--header 'Accept: application/json' \
--header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR'
```
Response -
```
{
"customer_payment_methods": [
{
"payment_token": null,
"payment_method_id": "pm_R8n4IKXyEpAGcKaEQl0g",
"customer_id": "Some_cust2",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"payment_method_data": {
"Card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2025",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
}
},
"bank": null,
"metadata": null,
"created": "2024-06-26T08:26:47.674Z",
"surcharge_details": null,
"requires_cvv": false,
"last_used_at": "2024-06-26T10:39:30.552Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": null,
"payment_method_id": "pm_xFF1OOhEMqVQhzEv3b06",
"customer_id": "Some_cust2",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"payment_method_data": {
"Card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2025",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
}
},
"bank": null,
"metadata": null,
"created": "2024-06-13T11:55:47.828Z",
"surcharge_details": null,
"requires_cvv": false,
"last_used_at": "2024-06-13T11:55:47.828Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
537630f00482939d4c0b49c643dee3763fe0e046
|
- Save a card
- Create another payment
```
curl --location --request POST 'http://localhost:8080/v2/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \
--data-raw '{
"amount": 200,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "Some_cust2",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response -
```
{
"payment_id": "pay_GNxoHRthb37nMZt6KLhv",
"merchant_id": "sarthak1",
"status": "requires_payment_method",
"amount": 200,
"net_amount": 200,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_GNxoHRthb37nMZt6KLhv_secret_G97qG0GJ85JeGks8NmnA",
"created": "2024-07-02T09:56:52.153Z",
"currency": "USD",
"customer_id": "Some_cust2",
"customer": {
"id": "Some_cust2",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594430",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "Some_cust2",
"created_at": 1719914212,
"expires": 1719917812,
"secret": "epk_7299286e8535424b957d32f6f5e44e99"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_1HgRzJgJf21X3s7FPrhP",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-07-02T10:11:52.153Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-07-02T09:56:52.226Z",
"charges": null,
"frm_metadata": null
}
```
- List saved payment method for v2
```
curl --location --request GET 'http://localhost:8080/v2/payments/pay_GNxoHRthb37nMZt6KLhv/saved_payment_methods?client_secret=pay_GNxoHRthb37nMZt6KLhv_secret_G97qG0GJ85JeGks8NmnA' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d'
```
Response -
```
{
"customer_payment_methods": [
{
"payment_token": "token_SBCX3r5nb9QaHNGtSbgK",
"payment_method_id": "pm_R8n4IKXyEpAGcKaEQl0g",
"customer_id": "Some_cust2",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"payment_method_data": {
"Card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2025",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
}
},
"bank": null,
"metadata": null,
"created": "2024-06-26T08:26:47.674Z",
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-06-26T10:39:30.552Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_nvHY8mkVcPYA94KQefdx",
"payment_method_id": "pm_xFF1OOhEMqVQhzEv3b06",
"customer_id": "Some_cust2",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"payment_method_data": {
"Card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2025",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
}
},
"bank": null,
"metadata": null,
"created": "2024-06-13T11:55:47.828Z",
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-06-13T11:55:47.828Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
}
],
"is_guest_customer": false
}
```
- Use Merchant API for saved payment methods -
```
curl --location --request GET 'http://localhost:8080/v2/customers/Some_cust2/saved_payment_methods' \
--header 'Accept: application/json' \
--header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR'
```
Response -
```
{
"customer_payment_methods": [
{
"payment_token": null,
"payment_method_id": "pm_R8n4IKXyEpAGcKaEQl0g",
"customer_id": "Some_cust2",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"payment_method_data": {
"Card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2025",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
}
},
"bank": null,
"metadata": null,
"created": "2024-06-26T08:26:47.674Z",
"surcharge_details": null,
"requires_cvv": false,
"last_used_at": "2024-06-26T10:39:30.552Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": null,
"payment_method_id": "pm_xFF1OOhEMqVQhzEv3b06",
"customer_id": "Some_cust2",
"payment_method": "card",
"payment_method_type": null,
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"payment_method_data": {
"Card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2025",
"card_token": null,
"card_holder_name": "joseph Doe",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
}
},
"bank": null,
"metadata": null,
"created": "2024-06-13T11:55:47.828Z",
"surcharge_details": null,
"requires_cvv": false,
"last_used_at": "2024-06-13T11:55:47.828Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "john",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4783
|
Bug: [REFACTOR] retrieve extended card info config during business profile get call
During business profile get call, send the extended card info config of merchant in the response so that dashboard can make use of it
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 12d9832ada6..dc64947bf08 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1010,6 +1010,9 @@ pub struct BusinessProfileResponse {
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
+
+ /// Merchant's config to support extended card info feature
+ pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 8fc3ebb721f..20083afb1c9 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -8,7 +8,7 @@ pub use api_models::admin::{
};
use common_utils::ext_traits::{Encode, ValueExt};
use error_stack::ResultExt;
-use masking::Secret;
+use masking::{ExposeInterface, Secret};
use crate::{
core::errors,
@@ -81,6 +81,10 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf
})
.transpose()?,
use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
+ extended_card_info_config: item
+ .extended_card_info_config
+ .map(|config| config.expose().parse_value("ExtendedCardInfoConfig"))
+ .transpose()?,
})
}
}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index b87b516de28..18ec7577a98 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -6949,6 +6949,14 @@
"use_billing_as_payment_method_billing": {
"type": "boolean",
"nullable": true
+ },
+ "extended_card_info_config": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ExtendedCardInfoConfig"
+ }
+ ],
+ "nullable": true
}
}
},
|
2024-05-28T07:55:13Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
During business profile get call, send the extended card info config of merchant (public key and ttl) in the response so that dashboard can make use of it
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Create merchant account (get default profile_id)
2. Create api key
3. Use update endpoint of business profile to pass config.
```
curl --location 'http://localhost:8080/account/merchant_1716883344/business_profile/pro_5PdcjX4zYfC8X2PFjCel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"extended_card_info_config": {
"ttl_in_secs": 300,
"public_key": "pub_key"
}
}'
```

4. Retrieve the business profile and the config should be returned in the response
```
curl --location 'http://localhost:8080/account/merchant_1716883344/business_profile/pro_5PdcjX4zYfC8X2PFjCel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data ''
```

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
c9fa94febe7a1fcd24e8d723d14b78f8a73da0e3
|
1. Create merchant account (get default profile_id)
2. Create api key
3. Use update endpoint of business profile to pass config.
```
curl --location 'http://localhost:8080/account/merchant_1716883344/business_profile/pro_5PdcjX4zYfC8X2PFjCel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"extended_card_info_config": {
"ttl_in_secs": 300,
"public_key": "pub_key"
}
}'
```

4. Retrieve the business profile and the config should be returned in the response
```
curl --location 'http://localhost:8080/account/merchant_1716883344/business_profile/pro_5PdcjX4zYfC8X2PFjCel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data ''
```

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4778
|
Bug: [FEATURE] [CRYPTOPAY] Pass network details in payment request
### Feature Description
The customer should be able to choose the supported network in case of doing cryptocurrency payments via Cryptopay.
### Possible Implementation
The supported networks will be shown on SDK and the chosen network will be passed on to Cryptopay. If no network is chosen then Cryptopay will choose the default network for that transaction.
https://developers.cryptopay.me/guides/currencies/currencies
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index cd405e3ca98..fe46d342161 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2118,6 +2118,7 @@ pub struct SepaAndBacsBillingDetails {
#[serde(rename_all = "snake_case")]
pub struct CryptoData {
pub pay_currency: Option<String>,
+ pub network: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 7517918ed95..065290b6b2d 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -285,6 +285,7 @@ pub enum BankRedirectData {
#[serde(rename_all = "snake_case")]
pub struct CryptoData {
pub pay_currency: Option<String>,
+ pub network: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
@@ -693,8 +694,14 @@ impl From<api_models::payments::BankRedirectData> for BankRedirectData {
impl From<api_models::payments::CryptoData> for CryptoData {
fn from(value: api_models::payments::CryptoData) -> Self {
- let api_models::payments::CryptoData { pay_currency } = value;
- Self { pay_currency }
+ let api_models::payments::CryptoData {
+ pay_currency,
+ network,
+ } = value;
+ Self {
+ pay_currency,
+ network,
+ }
}
}
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 0405f318071..a582a00ee19 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -8195,7 +8195,6 @@ impl Default for super::settings::RequiredFields {
"TRX".to_string(),
"DOGE".to_string(),
"BNB".to_string(),
- "BUSD".to_string(),
"USDT".to_string(),
"USDC".to_string(),
"DAI".to_string(),
@@ -8204,6 +8203,15 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
+ (
+ "payment_method_data.crypto.network".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.crypto.network".to_string(),
+ display_name: "network".to_string(),
+ field_type: enums::FieldType::Text,
+ value: None,
+ }
+ ),
]),
common : HashMap::new(),
}
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index 1a1f23b93bf..bcbc9a043a1 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -42,6 +42,8 @@ pub struct CryptopayPaymentsRequest {
price_amount: String,
price_currency: enums::Currency,
pay_currency: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ network: Option<String>,
success_redirect_url: Option<String>,
unsuccess_redirect_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -63,6 +65,7 @@ impl TryFrom<&CryptopayRouterData<&types::PaymentsAuthorizeRouterData>>
price_amount: item.amount.to_owned(),
price_currency: item.router_data.request.currency,
pay_currency,
+ network: cryptodata.network.to_owned(),
success_redirect_url: item.router_data.request.router_return_url.clone(),
unsuccess_redirect_url: item.router_data.request.router_return_url.clone(),
//Cryptopay only accepts metadata as Object. If any other type, payment will fail with error.
diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs
index 85026c9c447..69c6bfac61d 100644
--- a/crates/router/tests/connectors/bitpay.rs
+++ b/crates/router/tests/connectors/bitpay.rs
@@ -70,6 +70,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
currency: enums::Currency::USD,
payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
+ network: None,
}),
confirm: true,
statement_descriptor_suffix: None,
diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs
index 306255c94c5..569b2222e8b 100644
--- a/crates/router/tests/connectors/coinbase.rs
+++ b/crates/router/tests/connectors/coinbase.rs
@@ -72,6 +72,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
currency: enums::Currency::USD,
payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
+ network: None,
}),
confirm: true,
statement_descriptor_suffix: None,
diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs
index 6d52a174b58..20c727756e7 100644
--- a/crates/router/tests/connectors/cryptopay.rs
+++ b/crates/router/tests/connectors/cryptopay.rs
@@ -71,6 +71,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
currency: enums::Currency::USD,
payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: Some("XRP".to_string()),
+ network: None,
}),
confirm: true,
statement_descriptor_suffix: None,
diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs
index 91162b829e2..df54f0caf85 100644
--- a/crates/router/tests/connectors/opennode.rs
+++ b/crates/router/tests/connectors/opennode.rs
@@ -71,6 +71,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
currency: enums::Currency::USD,
payment_method_data: domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
+ network: None,
}),
confirm: true,
statement_descriptor_suffix: None,
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 30bd356cd45..2fb02edb149 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -7907,6 +7907,10 @@
"pay_currency": {
"type": "string",
"nullable": true
+ },
+ "network": {
+ "type": "string",
+ "nullable": true
}
}
},
|
2024-05-27T11:46:13Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The customer will be able to choose the supported network in case of doing cryptocurrency payments via Cryptopay.
The supported networks will be shown on SDK and the chosen network will be passed on to Cryptopay. If no network is chosen then Cryptopay will choose the default network for that transaction.
Also the currency `BUSD` is no longer supported by Cryptopay, hence it is being removed from list of supported crypto currencies.
Reference: https://developers.cryptopay.me/guides/currencies/currencies
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4778
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Payments Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 120,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "bnb_smart_chain"
}
}
}'
```
Payments Response:
```
{
"payment_id": "pay_7v0mzPuohoNWvobOcUlV",
"merchant_id": "merchant_1713942708",
"status": "requires_customer_action",
"amount": 120,
"net_amount": 120,
"amount_capturable": 120,
"amount_received": 120,
"connector": "cryptopay",
"client_secret": "pay_7v0mzPuohoNWvobOcUlV_secret_QaYlaPPZ07arI9NStJNQ",
"created": "2024-05-27T11:36:42.124Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_7v0mzPuohoNWvobOcUlV/merchant_1713942708/pay_7v0mzPuohoNWvobOcUlV_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "25bf87e4-55bd-4dc7-a807-8998c95cb496",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_7v0mzPuohoNWvobOcUlV_1",
"payment_link": null,
"profile_id": "pro_HgGSGQyaRys8iaDsi7OX",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_z8isFAS0iNcgES4VN5Lm",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-27T11:51:42.124Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-27T11:36:42.715Z",
"charges": null,
"frm_metadata": null
}
```
List payment methods for a Merchant Request:
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_BUUFr1ZME4rkMHDeGapK_secret_WhDFJZOH4FBIU9p4Xbzp' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE'
```
List payment methods for a Merchant Response:
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "crypto",
"payment_method_types": [
{
"payment_method_type": "crypto_currency",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cryptopay"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.crypto.pay_currency": {
"required_field": "payment_method_data.crypto.pay_currency",
"display_name": "currency",
"field_type": {
"user_currency": {
"options": [
"BTC",
"LTC",
"ETH",
"XRP",
"XLM",
"BCH",
"ADA",
"SOL",
"SHIB",
"TRX",
"DOGE",
"BNB",
"USDT",
"USDC",
"DAI"
]
}
},
"value": null
},
"payment_method_data.crypto.network": {
"required_field": "payment_method_data.crypto.network",
"display_name": "network",
"field_type": "text",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7645edfa2e00500da3f8f117cc1a485fe1f41ab5
|
Payments Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 120,
"currency": "USD",
"confirm": true,
"email": "guest@example.com",
"return_url": "https://google.com",
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_experience": "redirect_to_url",
"payment_method_data": {
"crypto": {
"pay_currency": "LTC",
"network": "bnb_smart_chain"
}
}
}'
```
Payments Response:
```
{
"payment_id": "pay_7v0mzPuohoNWvobOcUlV",
"merchant_id": "merchant_1713942708",
"status": "requires_customer_action",
"amount": 120,
"net_amount": 120,
"amount_capturable": 120,
"amount_received": 120,
"connector": "cryptopay",
"client_secret": "pay_7v0mzPuohoNWvobOcUlV_secret_QaYlaPPZ07arI9NStJNQ",
"created": "2024-05-27T11:36:42.124Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "crypto",
"payment_method_data": {
"crypto": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_7v0mzPuohoNWvobOcUlV/merchant_1713942708/pay_7v0mzPuohoNWvobOcUlV_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": "redirect_to_url",
"payment_method_type": "crypto_currency",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "25bf87e4-55bd-4dc7-a807-8998c95cb496",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_7v0mzPuohoNWvobOcUlV_1",
"payment_link": null,
"profile_id": "pro_HgGSGQyaRys8iaDsi7OX",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_z8isFAS0iNcgES4VN5Lm",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-27T11:51:42.124Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-27T11:36:42.715Z",
"charges": null,
"frm_metadata": null
}
```
List payment methods for a Merchant Request:
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_BUUFr1ZME4rkMHDeGapK_secret_WhDFJZOH4FBIU9p4Xbzp' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE'
```
List payment methods for a Merchant Response:
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "crypto",
"payment_method_types": [
{
"payment_method_type": "crypto_currency",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"cryptopay"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.crypto.pay_currency": {
"required_field": "payment_method_data.crypto.pay_currency",
"display_name": "currency",
"field_type": {
"user_currency": {
"options": [
"BTC",
"LTC",
"ETH",
"XRP",
"XLM",
"BCH",
"ADA",
"SOL",
"SHIB",
"TRX",
"DOGE",
"BNB",
"USDT",
"USDC",
"DAI"
]
}
},
"value": null
},
"payment_method_data.crypto.network": {
"required_field": "payment_method_data.crypto.network",
"display_name": "network",
"field_type": "text",
"value": null
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
}
],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal"
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4775
|
Bug: fix: Ability to change TOTP issuer name depending on the env
As of now, the issuer name in TOTP is always "Hyperswitch" independent of env.
As TOTP will be present in multiple environments, we need to have different issuer names for all the environments, so that user can easily identify the TOTP.
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 8aa0ca9e52f..ac428298e73 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -351,8 +351,9 @@ email_role_arn = "" # The amazon resource name ( arn ) of the role which
sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session.
[user]
-password_validity_in_days = 90 # Number of days after which password should be updated
-two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside
+password_validity_in_days = 90 # Number of days after which password should be updated
+two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside
+totp_issuer_name = "Hyperswitch" # Name of the issuer for TOTP
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index f6ed3ca5ea5..8d76771f897 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -114,6 +114,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw
[user]
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
+totp_issuer_name = "Hyperswitch Integ"
[frm]
enabled = true
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 37b35eb47e7..65f8d87215a 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -121,6 +121,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw
[user]
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
+totp_issuer_name = "Hyperswitch Production"
[frm]
enabled = false
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index fc496e34fc3..94f6d4b3430 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -121,6 +121,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw
[user]
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
+totp_issuer_name = "Hyperswitch Sandbox"
[frm]
enabled = true
diff --git a/config/development.toml b/config/development.toml
index d12a667b631..25fe55e6057 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -270,6 +270,7 @@ sts_role_session_name = ""
[user]
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
+totp_issuer_name = "Hyperswitch Dev"
[bank_config.eps]
stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 3f6c9523e93..f43ceca893d 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -54,6 +54,7 @@ recon_admin_api_key = "recon_test_admin"
[user]
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
+totp_issuer_name = "Hyperswitch"
[locker]
host = ""
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index c71ed4496b0..9aa879a4387 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -436,6 +436,7 @@ pub struct Secrets {
pub struct UserSettings {
pub password_validity_in_days: u16,
pub two_factor_auth_expiry_in_secs: i64,
+ pub totp_issuer_name: String,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 3c6cd8b6ccd..c7615aa4be4 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -1,15 +1,17 @@
pub const MAX_NAME_LENGTH: usize = 70;
pub const MAX_COMPANY_NAME_LENGTH: usize = 70;
pub const BUSINESS_EMAIL: &str = "biz@hyperswitch.io";
+
pub const RECOVERY_CODES_COUNT: usize = 8;
pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between
-pub const TOTP_ISSUER_NAME: &str = "Hyperswitch";
+
/// The number of digits composing the auth code.
pub const TOTP_DIGITS: usize = 6;
/// Duration in seconds of a step.
pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30;
/// Number of totps allowed as network delay. 1 would mean one totp before current totp and one totp after are valids.
pub const TOTP_TOLERANCE: u8 = 1;
+
pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index c259e87c93d..f4751c3a55a 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1635,7 +1635,11 @@ pub async fn begin_totp(
}));
}
- let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), 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?;
@@ -1668,7 +1672,12 @@ pub async fn reset_totp(
return Err(UserErrors::TwoFactorAuthRequired.into());
}
- let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), 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?;
@@ -1701,7 +1710,11 @@ pub async fn verify_totp(
.await?
.ok_or(UserErrors::InternalServerError)?;
- let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?;
+ 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()
@@ -1732,7 +1745,11 @@ pub async fn update_totp(
.await?
.ok_or(UserErrors::TotpSecretNotFound)?;
- let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), Some(new_totp_secret))?;
+ 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()
diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs
index a0915f3ed86..f64eda4dc5a 100644
--- a/crates/router/src/utils/user/two_factor_auth.rs
+++ b/crates/router/src/utils/user/two_factor_auth.rs
@@ -12,6 +12,7 @@ use crate::{
pub fn generate_default_totp(
email: pii::Email,
secret: Option<masking::Secret<String>>,
+ issuer: String,
) -> UserResult<TOTP> {
let secret = secret
.map(|sec| totp_rs::Secret::Encoded(sec.expose()))
@@ -25,7 +26,7 @@ pub fn generate_default_totp(
consts::user::TOTP_TOLERANCE,
consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS,
secret,
- Some(consts::user::TOTP_ISSUER_NAME.to_string()),
+ Some(issuer),
email.expose().expose(),
)
.change_context(UserErrors::InternalServerError)
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 2abe90f6086..e46a710054e 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -31,6 +31,7 @@ jwt_secret = "secret"
[user]
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
+totp_issuer_name = "Hyperswitch"
[locker]
host = ""
|
2024-05-27T09:50:23Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR adds configs for TOTP Issuer (to easily change issuer name of TOTP)
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
3. `crates/router/src/configs`
4. `loadtest/config`
-->
1. `config/config.example.toml`
2. `config/deployments/integration_test.toml`
3. `config/deployments/production.toml`
4. `config/deployments/sandbox.toml`
5. `config/development.toml`
6. `config/docker_compose.toml`
7. `loadtest/config/development.toml`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #4775.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/2fa/totp/begin' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
```
```
{
"secret": {
"secret": "INY6LEAFGX3OWJFVBXBUM7OMH4KLNI76",
"totp_url": "otpauth://totp/Hyper:mani.dchandra%40juspay.in?secret=INY6LEAFGX3OWJFVBXBUM7OMH4KLNI76&issuer=Hyper"
}
}
```
The `totp_url` field in the above response contains issuer as `Hyper` and this is coming from config.
- In integ, issuer name will be: `Hyperswitch Integ`
- In sandbox, issuer name will be: `Hyperswitch Sandbox`
- In production, issuer name will be: `Hyperswitch Prod`
- In local, issuer name will be: `Hyperswitch Deb`
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
15d6c3e846a77dec6b6a5165d86044a9b9fd52f1
|
```
curl --location 'http://localhost:8080/user/2fa/totp/begin' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
```
```
{
"secret": {
"secret": "INY6LEAFGX3OWJFVBXBUM7OMH4KLNI76",
"totp_url": "otpauth://totp/Hyper:mani.dchandra%40juspay.in?secret=INY6LEAFGX3OWJFVBXBUM7OMH4KLNI76&issuer=Hyper"
}
}
```
The `totp_url` field in the above response contains issuer as `Hyper` and this is coming from config.
- In integ, issuer name will be: `Hyperswitch Integ`
- In sandbox, issuer name will be: `Hyperswitch Sandbox`
- In production, issuer name will be: `Hyperswitch Prod`
- In local, issuer name will be: `Hyperswitch Deb`
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4791
|
Bug: Add a column (connector_wallets_details) in merchant connector account and develop an api (migrate cert) to store the encrypted certificates in the added column.
Currently apple pay related details are being stored in the connector metadata, as in future we are going to add apple pay decrypted flow support for ios app we will be collecting the apple pay payment processing certificates as well. As this ppc and ppc key needs to be securely stored, we need to move the existing certificates to a new column which stores the encrypted certificates.
|
diff --git a/crates/api_models/src/apple_pay_certificates_migration.rs b/crates/api_models/src/apple_pay_certificates_migration.rs
new file mode 100644
index 00000000000..796734f53e4
--- /dev/null
+++ b/crates/api_models/src/apple_pay_certificates_migration.rs
@@ -0,0 +1,12 @@
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct ApplePayCertificatesMigrationResponse {
+ pub migration_successful: Vec<String>,
+ pub migration_failed: Vec<String>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
+pub struct ApplePayCertificatesMigrationRequest {
+ pub merchant_ids: Vec<String>,
+}
+
+impl common_utils::events::ApiEventMetric for ApplePayCertificatesMigrationRequest {}
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 9c26576e77b..078c27e6db9 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -1,3 +1,4 @@
+pub mod apple_pay_certificates_migration;
pub mod connector_onboarding;
pub mod customer;
pub mod dispute;
diff --git a/crates/api_models/src/events/apple_pay_certificates_migration.rs b/crates/api_models/src/events/apple_pay_certificates_migration.rs
new file mode 100644
index 00000000000..f194443bea0
--- /dev/null
+++ b/crates/api_models/src/events/apple_pay_certificates_migration.rs
@@ -0,0 +1,9 @@
+use common_utils::events::ApiEventMetric;
+
+use crate::apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse;
+
+impl ApiEventMetric for ApplePayCertificatesMigrationResponse {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::ApplePayCertificatesMigration)
+ }
+}
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs
index a0bc6f6362d..d6d6deaa235 100644
--- a/crates/api_models/src/lib.rs
+++ b/crates/api_models/src/lib.rs
@@ -2,6 +2,7 @@
pub mod admin;
pub mod analytics;
pub mod api_keys;
+pub mod apple_pay_certificates_migration;
pub mod blocklist;
pub mod cards_info;
pub mod conditional_configs;
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index cda13289aa5..8ccfa14eaf6 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4208,6 +4208,23 @@ pub struct SessionTokenInfo {
pub initiative_context: String,
#[schema(value_type = Option<CountryAlpha2>)]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
+ #[serde(flatten)]
+ pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(tag = "payment_processing_details_at")]
+pub enum PaymentProcessingDetailsAt {
+ Hyperswitch(PaymentProcessingDetails),
+ Connector,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)]
+pub struct PaymentProcessingDetails {
+ #[schema(value_type = String)]
+ pub payment_processing_certificate: Secret<String>,
+ #[schema(value_type = String)]
+ pub payment_processing_certificate_key: Secret<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 3df291d5681..f20d2b821dd 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2284,11 +2284,6 @@ pub enum ReconStatus {
Active,
Disabled,
}
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum ApplePayFlow {
- Simplified,
- Manual,
-}
#[derive(
Clone,
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index 8939e07a76c..1052840dbc8 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -50,6 +50,7 @@ pub enum ApiEventsType {
// TODO: This has to be removed once the corresponding apiEventTypes are created
Miscellaneous,
RustLocker,
+ ApplePayCertificatesMigration,
FraudCheck,
Recon,
Dispute {
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index d7c505f7942..b411b1a7acd 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -67,7 +67,7 @@ pub enum ConnectorAuthType {
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(untagged)]
pub enum ApplePayTomlConfig {
- Standard(payments::ApplePayMetadata),
+ Standard(Box<payments::ApplePayMetadata>),
Zen(ZenApplePay),
}
diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs
index e45ef002626..680e3dacc85 100644
--- a/crates/diesel_models/src/merchant_connector_account.rs
+++ b/crates/diesel_models/src/merchant_connector_account.rs
@@ -43,6 +43,7 @@ pub struct MerchantConnectorAccount {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: storage_enums::ConnectorStatus,
+ pub connector_wallets_details: Option<Encryption>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -72,6 +73,7 @@ pub struct MerchantConnectorAccountNew {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: storage_enums::ConnectorStatus,
+ pub connector_wallets_details: Option<Encryption>,
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
@@ -96,6 +98,7 @@ pub struct MerchantConnectorAccountUpdateInternal {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: Option<storage_enums::ConnectorStatus>,
+ pub connector_wallets_details: Option<Encryption>,
}
impl MerchantConnectorAccountUpdateInternal {
diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs
index 0527ff3a181..682766679fd 100644
--- a/crates/diesel_models/src/query/generics.rs
+++ b/crates/diesel_models/src/query/generics.rs
@@ -166,7 +166,8 @@ where
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
- _ => Err(report!(errors::DatabaseError::Others))
+ Err(error) => Err(error)
+ .change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
}
}
@@ -252,7 +253,8 @@ where
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
- _ => Err(report!(errors::DatabaseError::Others))
+ Err(error) => Err(error)
+ .change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 6074fdc10b7..7baaa337259 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -679,6 +679,7 @@ diesel::table! {
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
pm_auth_config -> Nullable<Jsonb>,
status -> ConnectorStatus,
+ connector_wallets_details -> Nullable<Bytea>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 065290b6b2d..8dca0c86a2a 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -22,6 +22,12 @@ pub enum PaymentMethodData {
CardToken(CardToken),
}
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ApplePayFlow {
+ Simplified(api_models::payments::PaymentProcessingDetails),
+ Manual,
+}
+
impl PaymentMethodData {
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
match self {
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index b5d96a5c53f..00e13f5fce9 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -3,7 +3,7 @@ use std::{collections::HashMap, marker::PhantomData};
use common_utils::id_type;
use masking::Secret;
-use crate::payment_address::PaymentAddress;
+use crate::{payment_address::PaymentAddress, payment_method_data};
#[derive(Debug, Clone)]
pub struct RouterData<Flow, Request, Response> {
@@ -22,6 +22,7 @@ pub struct RouterData<Flow, Request, Response> {
pub address: PaymentAddress,
pub auth_type: common_enums::enums::AuthenticationType,
pub connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
+ pub connector_wallets_details: Option<common_utils::pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
pub access_token: Option<AccessToken>,
pub session_token: Option<String>,
@@ -56,7 +57,7 @@ pub struct RouterData<Flow, Request, Response> {
pub connector_http_status_code: Option<u16>,
pub external_latency: Option<u128>,
/// Contains apple pay flow type simplified or manual
- pub apple_pay_flow: Option<common_enums::enums::ApplePayFlow>,
+ pub apple_pay_flow: Option<payment_method_data::ApplePayFlow>,
pub frm_metadata: Option<common_utils::pii::SecretSerdeValue>,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 237cddcf94e..f4fc5fc8473 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -309,6 +309,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::FeatureMetadata,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
+ api_models::payments::PaymentProcessingDetailsAt,
+ api_models::payments::PaymentProcessingDetails,
api_models::payments::SwishQrData,
api_models::payments::AirwallexData,
api_models::payments::NoonData,
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index 02a5873429f..53787fe04ab 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -1,6 +1,7 @@
pub mod admin;
pub mod api_keys;
pub mod api_locking;
+pub mod apple_pay_certificates_migration;
pub mod authentication;
pub mod blocklist;
pub mod cache;
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 6b582c2c957..0578945006f 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -937,7 +937,7 @@ pub async fn create_payment_connector(
payment_methods_enabled,
test_mode: req.test_mode,
disabled,
- metadata: req.metadata,
+ metadata: req.metadata.clone(),
frm_configs,
connector_label: Some(connector_label.clone()),
business_country: req.business_country,
@@ -961,6 +961,7 @@ pub async fn create_payment_connector(
applepay_verified_domains: None,
pm_auth_config: req.pm_auth_config.clone(),
status: connector_status,
+ connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(&key_store, &req.metadata).await?,
};
let transaction_type = match req.connector_type {
@@ -1200,6 +1201,7 @@ pub async fn update_payment_connector(
expected_format: "auth_type and api_key".to_string(),
})?;
let metadata = req.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 {
@@ -1275,6 +1277,10 @@ pub async fn update_payment_connector(
applepay_verified_domains: None,
pm_auth_config: req.pm_auth_config,
status: Some(connector_status),
+ connector_wallets_details: helpers::get_encrypted_apple_pay_connector_wallets_details(
+ &key_store, &metadata,
+ )
+ .await?,
};
// Profile id should always be present
diff --git a/crates/router/src/core/apple_pay_certificates_migration.rs b/crates/router/src/core/apple_pay_certificates_migration.rs
new file mode 100644
index 00000000000..327358bda50
--- /dev/null
+++ b/crates/router/src/core/apple_pay_certificates_migration.rs
@@ -0,0 +1,109 @@
+use api_models::apple_pay_certificates_migration;
+use common_utils::errors::CustomResult;
+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},
+};
+
+pub async fn apple_pay_certificates_migration(
+ state: SessionState,
+ req: &apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest,
+) -> CustomResult<
+ services::ApplicationResponse<
+ apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse,
+ >,
+ errors::ApiErrorResponse,
+> {
+ let db = state.store.as_ref();
+
+ let merchant_id_list = &req.merchant_ids;
+
+ let mut migration_successful_merchant_ids = vec![];
+ let mut migration_failed_merchant_ids = vec![];
+
+ for merchant_id in merchant_id_list {
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ merchant_id,
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ let merchant_connector_accounts = db
+ .find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ merchant_id,
+ true,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
+
+ let mut mca_to_update = vec![];
+
+ for connector_account in merchant_connector_accounts {
+ let connector_apple_pay_metadata =
+ helpers::get_applepay_metadata(connector_account.clone().metadata)
+ .map_err(|error| {
+ logger::error!(
+ "Apple pay metadata parsing failed for {:?} in certificates migrations api {:?}",
+ connector_account.clone().connector_name,
+ error
+ )
+ })
+ .ok();
+ if let Some(apple_pay_metadata) = connector_apple_pay_metadata {
+ let encrypted_apple_pay_metadata = domain_types::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")?,
+ ),
+ key_store.key.get_inner().peek(),
+ )
+ .await
+ .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.to_string());
+ }
+ Err(error) => {
+ logger::debug!(
+ "Merchant connector accounts update failed with error {error} for merchant id {merchant_id}");
+ migration_failed_merchant_ids.push(merchant_id.to_string());
+ }
+ };
+ }
+
+ Ok(services::api::ApplicationResponse::Json(
+ apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse {
+ migration_successful: migration_successful_merchant_ids,
+ migration_failed: migration_failed_merchant_ids,
+ },
+ ))
+}
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index 2255e1ff582..704784c485e 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -153,6 +153,7 @@ pub fn construct_router_data<F: Clone, Req, Res>(
address,
auth_type: common_enums::AuthenticationType::NoThreeDs,
connector_meta_data: merchant_connector_account.get_metadata(),
+ connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: None,
access_token: None,
session_token: None,
diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
index 74353e83b3d..679a5dad29a 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -67,6 +67,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: FraudCheckCheckoutData {
amount: self.payment_attempt.amount.get_amount_as_i64(),
diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
index f91d87c808c..855b87f3ffb 100644
--- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
@@ -72,6 +72,7 @@ pub async fn construct_fulfillment_router_data<'a>(
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()),
diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs
index b8f8810f09b..ac661231ecc 100644
--- a/crates/router/src/core/fraud_check/flows/record_return.rs
+++ b/crates/router/src/core/fraud_check/flows/record_return.rs
@@ -65,6 +65,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: FraudCheckRecordReturnData {
amount: self.payment_attempt.amount.get_amount_as_i64(),
diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs
index b605c540656..6dbde23e3d2 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -62,6 +62,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: FraudCheckSaleData {
amount: self.payment_attempt.amount.get_amount_as_i64(),
diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
index 8c496792a81..4f5d0b30aa9 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -72,6 +72,7 @@ impl
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: FraudCheckTransactionData {
amount: self.payment_attempt.amount.get_amount_as_i64(),
diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs
index ec438ee6d78..811b69e4562 100644
--- a/crates/router/src/core/mandate/utils.rs
+++ b/crates/router/src/core/mandate/utils.rs
@@ -44,6 +44,7 @@ pub async fn construct_mandate_revoke_router_data(
address: PaymentAddress::default(),
auth_type: diesel_models::enums::AuthenticationType::default(),
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index caaecdc8629..8ee8dce6393 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1475,44 +1475,47 @@ where
// Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay
// and the connector supports Apple Pay predecrypt
- if matches!(
- tokenization_action,
- TokenizationAction::DecryptApplePayToken
- | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt
- ) {
- let apple_pay_data = match payment_data.payment_method_data.clone() {
- Some(payment_data) => {
- let domain_data = domain::PaymentMethodData::from(payment_data);
- match domain_data {
- domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(
- wallet_data,
- )) => Some(
- ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data))
- .change_context(errors::ApiErrorResponse::InternalServerError)?
- .decrypt(state)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?,
- ),
- _ => None,
+ match &tokenization_action {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
+ | TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ ) => {
+ let apple_pay_data = match payment_data.payment_method_data.clone() {
+ Some(payment_method_data) => {
+ let domain_data = domain::PaymentMethodData::from(payment_method_data);
+ match domain_data {
+ domain::PaymentMethodData::Wallet(domain::WalletData::ApplePay(
+ wallet_data,
+ )) => Some(
+ ApplePayData::token_json(domain::WalletData::ApplePay(wallet_data))
+ .change_context(errors::ApiErrorResponse::InternalServerError)?
+ .decrypt(
+ &payment_processing_details.payment_processing_certificate,
+ &payment_processing_details.payment_processing_certificate_key,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ ),
+ _ => None,
+ }
}
- }
- _ => None,
- };
-
- let apple_pay_predecrypt = apple_pay_data
- .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>(
- "ApplePayPredecryptData",
- )
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ _ => None,
+ };
- logger::debug!(?apple_pay_predecrypt);
+ let apple_pay_predecrypt = apple_pay_data
+ .parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptData>(
+ "ApplePayPredecryptData",
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
- router_data.payment_method_token = Some(
- hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(Box::new(
- apple_pay_predecrypt,
- )),
- );
- }
+ router_data.payment_method_token = Some(
+ hyperswitch_domain_models::router_data::PaymentMethodToken::ApplePayDecrypt(
+ Box::new(apple_pay_predecrypt),
+ ),
+ );
+ }
+ _ => (),
+ };
let pm_token = router_data
.add_payment_method_token(state, &connector, &tokenization_action)
@@ -2053,7 +2056,7 @@ fn is_payment_method_tokenization_enabled_for_connector(
connector_name: &str,
payment_method: &storage::enums::PaymentMethod,
payment_method_type: &Option<storage::enums::PaymentMethodType>,
- apple_pay_flow: &Option<enums::ApplePayFlow>,
+ apple_pay_flow: &Option<domain::ApplePayFlow>,
) -> RouterResult<bool> {
let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name);
@@ -2078,13 +2081,13 @@ fn is_payment_method_tokenization_enabled_for_connector(
fn is_apple_pay_pre_decrypt_type_connector_tokenization(
payment_method_type: &Option<storage::enums::PaymentMethodType>,
- apple_pay_flow: &Option<enums::ApplePayFlow>,
+ apple_pay_flow: &Option<domain::ApplePayFlow>,
apple_pay_pre_decrypt_flow_filter: Option<ApplePayPreDecryptFlow>,
) -> bool {
match (payment_method_type, apple_pay_flow) {
(
Some(storage::enums::PaymentMethodType::ApplePay),
- Some(enums::ApplePayFlow::Simplified),
+ Some(domain::ApplePayFlow::Simplified(_)),
) => !matches!(
apple_pay_pre_decrypt_flow_filter,
Some(ApplePayPreDecryptFlow::NetworkTokenization)
@@ -2094,18 +2097,22 @@ fn is_apple_pay_pre_decrypt_type_connector_tokenization(
}
fn decide_apple_pay_flow(
+ state: &SessionState,
payment_method_type: &Option<enums::PaymentMethodType>,
merchant_connector_account: Option<&helpers::MerchantConnectorAccountType>,
-) -> Option<enums::ApplePayFlow> {
+) -> Option<domain::ApplePayFlow> {
payment_method_type.and_then(|pmt| match pmt {
- enums::PaymentMethodType::ApplePay => check_apple_pay_metadata(merchant_connector_account),
+ 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<enums::ApplePayFlow> {
+) -> Option<domain::ApplePayFlow> {
merchant_connector_account.and_then(|mca| {
let metadata = mca.get_metadata();
metadata.and_then(|apple_pay_metadata| {
@@ -2139,14 +2146,34 @@ fn check_apple_pay_metadata(
apple_pay_combined,
) => match apple_pay_combined {
api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => {
- enums::ApplePayFlow::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 { .. } => {
- enums::ApplePayFlow::Manual
+ 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(_) => {
- enums::ApplePayFlow::Manual
+ domain::ApplePayFlow::Manual
}
})
})
@@ -2173,23 +2200,21 @@ async fn decide_payment_method_tokenize_action(
payment_method: &storage::enums::PaymentMethod,
pm_parent_token: Option<&String>,
is_connector_tokenization_enabled: bool,
- apple_pay_flow: Option<enums::ApplePayFlow>,
+ apple_pay_flow: Option<domain::ApplePayFlow>,
) -> RouterResult<TokenizationAction> {
- let is_apple_pay_predecrypt_supported =
- matches!(apple_pay_flow, Some(enums::ApplePayFlow::Simplified));
-
match pm_parent_token {
- None => {
- if is_connector_tokenization_enabled && is_apple_pay_predecrypt_supported {
- Ok(TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt)
- } else if is_connector_tokenization_enabled {
- Ok(TokenizationAction::TokenizeInConnectorAndRouter)
- } else if is_apple_pay_predecrypt_supported {
- Ok(TokenizationAction::DecryptApplePayToken)
- } else {
- Ok(TokenizationAction::TokenizeInRouter)
+ None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {
+ (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ )
}
- }
+ (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,
+ (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
+ }
+ (false, _) => TokenizationAction::TokenizeInRouter,
+ }),
Some(token) => {
let redis_conn = state
.store
@@ -2212,17 +2237,18 @@ async fn decide_payment_method_tokenize_action(
match connector_token_option {
Some(connector_token) => Ok(TokenizationAction::ConnectorToken(connector_token)),
- None => {
- if is_connector_tokenization_enabled && is_apple_pay_predecrypt_supported {
- Ok(TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt)
- } else if is_connector_tokenization_enabled {
- Ok(TokenizationAction::TokenizeInConnectorAndRouter)
- } else if is_apple_pay_predecrypt_supported {
- Ok(TokenizationAction::DecryptApplePayToken)
- } else {
- Ok(TokenizationAction::TokenizeInRouter)
+ None => Ok(match (is_connector_tokenization_enabled, apple_pay_flow) {
+ (true, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ )
}
- }
+ (true, _) => TokenizationAction::TokenizeInConnectorAndRouter,
+ (false, Some(domain::ApplePayFlow::Simplified(payment_processing_details))) => {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
+ }
+ (false, _) => TokenizationAction::TokenizeInRouter,
+ }),
}
}
}
@@ -2235,8 +2261,8 @@ pub enum TokenizationAction {
TokenizeInConnectorAndRouter,
ConnectorToken(String),
SkipConnectorTokenization,
- DecryptApplePayToken,
- TokenizeInConnectorAndApplepayPreDecrypt,
+ DecryptApplePayToken(payments_api::PaymentProcessingDetails),
+ TokenizeInConnectorAndApplepayPreDecrypt(payments_api::PaymentProcessingDetails),
}
#[allow(clippy::too_many_arguments)]
@@ -2277,7 +2303,7 @@ where
let payment_method_type = &payment_data.payment_attempt.payment_method_type;
let apple_pay_flow =
- decide_apple_pay_flow(payment_method_type, Some(merchant_connector_account));
+ decide_apple_pay_flow(state, payment_method_type, Some(merchant_connector_account));
let is_connector_tokenization_enabled =
is_payment_method_tokenization_enabled_for_connector(
@@ -2346,12 +2372,14 @@ where
TokenizationAction::SkipConnectorTokenization => {
TokenizationAction::SkipConnectorTokenization
}
- TokenizationAction::DecryptApplePayToken => {
- TokenizationAction::DecryptApplePayToken
- }
- TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt => {
- TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt
+ TokenizationAction::DecryptApplePayToken(payment_processing_details) => {
+ TokenizationAction::DecryptApplePayToken(payment_processing_details)
}
+ TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ ) => TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(
+ payment_processing_details,
+ ),
};
(payment_data.to_owned(), connector_tokenization_action)
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 76441f40759..14a3b9327dc 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -166,8 +166,20 @@ async fn create_applepay_session_token(
)
} else {
// Get the apple pay metadata
- let apple_pay_metadata =
- helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?;
+ let connector_apple_pay_wallet_details =
+ helpers::get_applepay_metadata(router_data.connector_wallets_details.clone())
+ .map_err(|error| {
+ logger::debug!(
+ "Apple pay connector wallets details parsing failed in create_applepay_session_token {:?}",
+ error
+ )
+ })
+ .ok();
+
+ let apple_pay_metadata = match connector_apple_pay_wallet_details {
+ Some(apple_pay_wallet_details) => apple_pay_wallet_details,
+ None => helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?,
+ };
// Get payment request data , apple pay session request and merchant keys
let (
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index a58a6ae32b2..6610b048606 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -6,6 +6,7 @@ use api_models::{
};
use base64::Engine;
use common_utils::{
+ crypto::Encryptable,
ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt},
fp_utils, generate_id, id_type, pii,
types::MinorUnit,
@@ -3169,6 +3170,13 @@ impl MerchantConnectorAccountType {
}
}
+ pub fn get_connector_wallets_details(&self) -> Option<masking::Secret<serde_json::Value>> {
+ match self {
+ Self::DbVal(val) => val.connector_wallets_details.as_deref().cloned(),
+ Self::CacheVal(_) => None,
+ }
+ }
+
pub fn is_disabled(&self) -> bool {
match self {
Self::DbVal(ref inner) => inner.disabled.unwrap_or(false),
@@ -3368,6 +3376,7 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
refund_id: router_data.refund_id,
dispute_id: router_data.dispute_id,
connector_response: router_data.connector_response,
+ connector_wallets_details: router_data.connector_wallets_details,
}
}
@@ -3905,17 +3914,32 @@ pub fn validate_customer_access(
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
+ connector_wallets_details: 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 {:?}",
+ let connector_apple_pay_wallet_details =
+ get_applepay_metadata(connector_wallets_details)
+ .map_err(|error| {
+ logger::debug!(
+ "Apple pay connector wallets details parsing failed for {:?} in is_apple_pay_simplified_flow {:?}",
+ connector_name,
+ error
+ )
+ })
+ .ok();
+
+ let option_apple_pay_metadata = match connector_apple_pay_wallet_details {
+ Some(apple_pay_wallet_details) => Some(apple_pay_wallet_details),
+ None => get_applepay_metadata(connector_metadata)
+ .map_err(|error| {
+ logger::debug!(
+ "Apple pay metadata parsing failed for {:?} in is_apple_pay_simplified_flow {:?}",
connector_name,
error
)
- })
- .ok();
+ })
+ .ok(),
+ };
// return true only if the apple flow type is simplified
Ok(matches!(
@@ -3928,6 +3952,38 @@ pub fn is_apple_pay_simplified_flow(
))
}
+pub async fn get_encrypted_apple_pay_connector_wallets_details(
+ key_store: &domain::MerchantKeyStore,
+ connector_metadata: &Option<masking::Secret<tera::Value>>,
+) -> RouterResult<Option<Encryptable<masking::Secret<serde_json::Value>>>> {
+ let apple_pay_metadata = get_applepay_metadata(connector_metadata.clone())
+ .map_err(|error| {
+ logger::error!(
+ "Apple pay metadata parsing failed in get_encrypted_apple_pay_connector_wallets_details {:?}",
+ error
+ )
+ })
+ .ok();
+
+ let connector_apple_pay_details = apple_pay_metadata
+ .map(|metadata| {
+ serde_json::to_value(metadata)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize apple pay metadata as JSON")
+ })
+ .transpose()?
+ .map(masking::Secret::new);
+
+ let encrypted_connector_apple_pay_details = connector_apple_pay_details
+ .async_lift(|wallets_details| {
+ types::encrypt_optional(wallets_details, key_store.key.get_inner().peek())
+ })
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encrypting connector wallets details")?;
+ Ok(encrypted_connector_apple_pay_details)
+}
+
pub fn get_applepay_metadata(
connector_metadata: Option<pii::SecretSerdeValue>,
) -> RouterResult<api_models::payments::ApplepaySessionTokenMetadata> {
@@ -3991,6 +4047,7 @@ where
let connector_data_list = if is_apple_pay_simplified_flow(
merchant_connector_account_type.get_metadata(),
+ merchant_connector_account_type.get_connector_wallets_details(),
merchant_connector_account_type
.get_connector_name()
.as_ref(),
@@ -4010,6 +4067,10 @@ where
for merchant_connector_account in merchant_connector_account_list {
if is_apple_pay_simplified_flow(
merchant_connector_account.metadata,
+ merchant_connector_account
+ .connector_wallets_details
+ .as_deref()
+ .cloned(),
Some(&merchant_connector_account.connector_name),
)? {
let connector_data = api::ConnectorData::get_connector_by_name(
@@ -4064,10 +4125,11 @@ impl ApplePayData {
pub async fn decrypt(
&self,
- state: &SessionState,
+ 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(state).await?;
- let shared_secret = self.shared_secret(state).await?;
+ 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)
@@ -4075,17 +4137,11 @@ impl ApplePayData {
Ok(parsed_decrypted)
}
- pub async fn merchant_id(
+ pub fn merchant_id(
&self,
- state: &SessionState,
+ payment_processing_certificate: &masking::Secret<String>,
) -> CustomResult<String, errors::ApplePayDecryptionError> {
- let cert_data = state
- .conf
- .applepay_decrypt_keys
- .get_inner()
- .apple_pay_ppc
- .clone()
- .expose();
+ let cert_data = payment_processing_certificate.clone().expose();
let base64_decode_cert_data = BASE64_ENGINE
.decode(cert_data)
@@ -4120,9 +4176,9 @@ impl ApplePayData {
Ok(apple_pay_m_id)
}
- pub async fn shared_secret(
+ pub fn shared_secret(
&self,
- state: &SessionState,
+ 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())
@@ -4132,13 +4188,7 @@ impl ApplePayData {
.change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed)
.attach_printable("Failed to deserialize the public key")?;
- let decrypted_apple_pay_ppc_key = state
- .conf
- .applepay_decrypt_keys
- .get_inner()
- .apple_pay_ppc_key
- .clone()
- .expose();
+ 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())
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 48637a0d2b3..7016c7542be 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -727,7 +727,7 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>(
) -> RouterResult<Option<String>> {
match tokenization_action {
payments::TokenizationAction::TokenizeInConnector
- | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt => {
+ | payments::TokenizationAction::TokenizeInConnectorAndApplepayPreDecrypt(_) => {
let connector_integration: services::BoxedConnectorIntegration<
'_,
api::PaymentMethodToken,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 8eca589ca28..02115a529c3 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -125,6 +125,7 @@ where
};
let apple_pay_flow = payments::decide_apple_pay_flow(
+ state,
&payment_data.payment_attempt.payment_method_type,
Some(merchant_connector_account),
);
@@ -154,6 +155,7 @@ where
.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
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 679838a6dd5..8201a8480c0 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -164,6 +164,7 @@ pub async fn construct_payout_router_data<'a, F>(
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,
payment_method_status: None,
request: types::PayoutsData {
@@ -316,6 +317,7 @@ pub async fn construct_refund_router_data<'a, F>(
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()),
@@ -565,6 +567,7 @@ pub async fn construct_accept_dispute_router_data<'a>(
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()),
@@ -661,6 +664,7 @@ pub async fn construct_submit_evidence_router_data<'a>(
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()),
@@ -755,6 +759,7 @@ pub async fn construct_upload_file_router_data<'a>(
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()),
@@ -853,6 +858,7 @@ pub async fn construct_defend_dispute_router_data<'a>(
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()),
@@ -942,6 +948,7 @@ pub async fn construct_retrieve_file_router_data<'a>(
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,
payment_method_status: None,
request: types::RetrieveFileRequestData {
diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs
index 7518091ee87..bfbc1cb8b44 100644
--- a/crates/router/src/core/verification/utils.rs
+++ b/crates/router/src/core/verification/utils.rs
@@ -61,6 +61,7 @@ pub async fn check_existence_and_add_domain_to_db(
pm_auth_config: None,
connector_label: None,
status: None,
+ connector_wallets_details: None,
};
state
.store
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index ad1aafd3125..1394c68cfa8 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -86,6 +86,7 @@ pub async fn construct_webhook_router_data<'a>(
address: PaymentAddress::default(),
auth_type: diesel_models::enums::AuthenticationType::default(),
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
request: types::VerifyWebhookSourceRequestData {
webhook_headers: request_details.headers.clone(),
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 910ad085f63..19603f81486 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -942,6 +942,17 @@ impl FileMetadataInterface for KafkaStore {
#[async_trait::async_trait]
impl MerchantConnectorAccountInterface for KafkaStore {
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ merchant_connector_accounts: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), errors::StorageError> {
+ self.diesel_store
+ .update_multiple_merchant_connector_accounts(merchant_connector_accounts)
+ .await
+ }
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
merchant_id: &str,
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index aea37b517be..ab66b52c32d 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -1,4 +1,6 @@
+use async_bb8_diesel::AsyncConnection;
use common_utils::ext_traits::{AsyncExt, ByteSliceExt, Encode};
+use diesel_models::encryption::Encryption;
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
@@ -165,6 +167,14 @@ where
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ this: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), errors::StorageError>;
+
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
merchant_id: &str,
@@ -381,6 +391,104 @@ impl MerchantConnectorAccountInterface for Store {
.await
}
+ #[instrument(skip_all)]
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ merchant_connector_accounts: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+
+ async fn update_call(
+ connection: &diesel_models::PgPooledConn,
+ (merchant_connector_account, mca_update): (
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ ),
+ ) -> Result<(), error_stack::Report<storage_impl::errors::StorageError>> {
+ Conversion::convert(merchant_connector_account)
+ .await
+ .change_context(errors::StorageError::EncryptionError)?
+ .update(connection, mca_update)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?;
+ Ok(())
+ }
+
+ conn.transaction_async(|connection_pool| async move {
+ for (merchant_connector_account, update_merchant_connector_account) in
+ merchant_connector_accounts
+ {
+ let _connector_name = merchant_connector_account.connector_name.clone();
+ let _profile_id = merchant_connector_account.profile_id.clone().ok_or(
+ errors::StorageError::ValueNotFound("profile_id".to_string()),
+ )?;
+
+ let _merchant_id = merchant_connector_account.merchant_id.clone();
+ let _merchant_connector_id =
+ merchant_connector_account.merchant_connector_id.clone();
+
+ let update = update_call(
+ &connection_pool,
+ (
+ merchant_connector_account,
+ update_merchant_connector_account,
+ ),
+ );
+
+ #[cfg(feature = "accounts_cache")]
+ // Redact all caches as any of might be used because of backwards compatibility
+ cache::publish_and_redact_multiple(
+ self,
+ [
+ cache::CacheKind::Accounts(
+ format!("{}_{}", _profile_id, _connector_name).into(),
+ ),
+ cache::CacheKind::Accounts(
+ format!("{}_{}", _merchant_id, _merchant_connector_id).into(),
+ ),
+ cache::CacheKind::CGraph(
+ format!("cgraph_{}_{_profile_id}", _merchant_id).into(),
+ ),
+ ],
+ || update,
+ )
+ .await
+ .map_err(|error| {
+ // Returning `DatabaseConnectionError` after logging the actual error because
+ // -> it is not possible to get the underlying from `error_stack::Report<C>`
+ // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
+ // because of Rust's orphan rules
+ router_env::logger::error!(
+ ?error,
+ "DB transaction for updating multiple merchant connector account failed"
+ );
+ errors::StorageError::DatabaseConnectionError
+ })?;
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ update.await.map_err(|error| {
+ // Returning `DatabaseConnectionError` after logging the actual error because
+ // -> it is not possible to get the underlying from `error_stack::Report<C>`
+ // -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
+ // because of Rust's orphan rules
+ router_env::logger::error!(
+ ?error,
+ "DB transaction for updating multiple merchant connector account failed"
+ );
+ errors::StorageError::DatabaseConnectionError
+ })?;
+ }
+ }
+ Ok::<_, errors::StorageError>(())
+ })
+ .await?;
+ Ok(())
+ }
+
#[instrument(skip_all)]
async fn update_merchant_connector_account(
&self,
@@ -417,7 +525,7 @@ impl MerchantConnectorAccountInterface for Store {
#[cfg(feature = "accounts_cache")]
{
- // Redact both the caches as any one or both might be used because of backwards compatibility
+ // Redact all caches as any of might be used because of backwards compatibility
cache::publish_and_redact_multiple(
self,
[
@@ -502,6 +610,17 @@ impl MerchantConnectorAccountInterface for Store {
#[async_trait::async_trait]
impl MerchantConnectorAccountInterface for MockDb {
+ async fn update_multiple_merchant_connector_accounts(
+ &self,
+ _merchant_connector_accounts: Vec<(
+ domain::MerchantConnectorAccount,
+ storage::MerchantConnectorAccountUpdateInternal,
+ )>,
+ ) -> CustomResult<(), errors::StorageError> {
+ // No need to implement this function for `MockDb` as this function will be removed after the
+ // apple pay certificate migration
+ Err(errors::StorageError::MockDbError)?
+ }
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
merchant_id: &str,
@@ -658,6 +777,7 @@ impl MerchantConnectorAccountInterface for MockDb {
applepay_verified_domains: t.applepay_verified_domains,
pm_auth_config: t.pm_auth_config,
status: t.status,
+ connector_wallets_details: t.connector_wallets_details.map(Encryption::from),
};
accounts.push(account.clone());
account
@@ -857,6 +977,14 @@ mod merchant_connector_account_cache_tests {
applepay_verified_domains: None,
pm_auth_config: None,
status: common_enums::ConnectorStatus::Inactive,
+ connector_wallets_details: Some(
+ domain::types::encrypt(
+ serde_json::Value::default().into(),
+ merchant_key.key.get_inner().peek(),
+ )
+ .await
+ .unwrap(),
+ ),
};
db.insert_merchant_connector_account(mca.clone(), &merchant_key)
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 7344b85d150..73ec0f1635d 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -144,6 +144,7 @@ pub fn mk_app(
.service(routes::Routing::server(state.clone()))
.service(routes::Blocklist::server(state.clone()))
.service(routes::Gsm::server(state.clone()))
+ .service(routes::ApplePayCertificatesMigration::server(state.clone()))
.service(routes::PaymentLink::server(state.clone()))
.service(routes::User::server(state.clone()))
.service(routes::ConnectorOnboarding::server(state.clone()))
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 9f13635ca90..cb229b5c802 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -1,6 +1,7 @@
pub mod admin;
pub mod api_keys;
pub mod app;
+pub mod apple_pay_certificates_migration;
#[cfg(feature = "olap")]
pub mod blocklist;
pub mod cache;
@@ -58,10 +59,10 @@ pub use self::app::Payouts;
#[cfg(all(feature = "olap", feature = "recon"))]
pub use self::app::Recon;
pub use self::app::{
- ApiKeys, AppState, BusinessProfile, Cache, Cards, Configs, ConnectorOnboarding, Customers,
- Disputes, EphemeralKey, Files, Gsm, Health, Mandates, MerchantAccount,
- MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll, Refunds, SessionState,
- User, Webhooks,
+ ApiKeys, AppState, ApplePayCertificatesMigration, BusinessProfile, Cache, Cards, Configs,
+ ConnectorOnboarding, Customers, Disputes, EphemeralKey, Files, Gsm, Health, Mandates,
+ MerchantAccount, MerchantConnectorAccount, PaymentLink, PaymentMethods, Payments, Poll,
+ Refunds, SessionState, User, Webhooks,
};
#[cfg(feature = "olap")]
pub use self::app::{Blocklist, Routing, Verify, WebhookEvents};
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index 2d1b77460a5..cd392756505 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -413,7 +413,7 @@ pub async fn payment_connector_delete(
merchant_connector_id,
})
.into_inner();
- api::server_wrap(
+ Box::pin(api::server_wrap(
flow,
state,
&req,
@@ -430,7 +430,7 @@ pub async fn payment_connector_delete(
req.headers(),
),
api_locking::LockAction::NotApplicable,
- )
+ ))
.await
}
/// Merchant Account - Toggle KV
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 5af3a2bef25..5438535a15c 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -29,8 +29,8 @@ use super::routing as cloud_routing;
use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_verified_domains};
#[cfg(feature = "olap")]
use super::{
- admin::*, api_keys::*, connector_onboarding::*, disputes::*, files::*, gsm::*, payment_link::*,
- user::*, user_role::*, webhook_events::*,
+ admin::*, api_keys::*, apple_pay_certificates_migration, connector_onboarding::*, disputes::*,
+ files::*, gsm::*, payment_link::*, user::*, user_role::*, webhook_events::*,
};
use super::{cache::*, health::*};
#[cfg(any(feature = "olap", feature = "oltp"))]
@@ -1117,6 +1117,19 @@ impl Configs {
}
}
+pub struct ApplePayCertificatesMigration;
+
+#[cfg(feature = "olap")]
+impl ApplePayCertificatesMigration {
+ pub fn server(state: AppState) -> Scope {
+ web::scope("/apple_pay_certificates_migration")
+ .app_data(web::Data::new(state))
+ .service(web::resource("").route(
+ web::post().to(apple_pay_certificates_migration::apple_pay_certificates_migration),
+ ))
+ }
+}
+
pub struct Poll;
#[cfg(feature = "oltp")]
diff --git a/crates/router/src/routes/apple_pay_certificates_migration.rs b/crates/router/src/routes/apple_pay_certificates_migration.rs
new file mode 100644
index 00000000000..8c9d507ba41
--- /dev/null
+++ b/crates/router/src/routes/apple_pay_certificates_migration.rs
@@ -0,0 +1,30 @@
+use actix_web::{web, HttpRequest, HttpResponse};
+use router_env::Flow;
+
+use super::AppState;
+use crate::{
+ core::{api_locking, apple_pay_certificates_migration},
+ services::{api, authentication as auth},
+};
+
+pub async fn apple_pay_certificates_migration(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<
+ api_models::apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest,
+ >,
+) -> HttpResponse {
+ let flow = Flow::ApplePayCertificatesMigration;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ &json_payload.into_inner(),
+ |state, _, req, _| {
+ apple_pay_certificates_migration::apple_pay_certificates_migration(state, req)
+ },
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index b4b9658a7e0..a64343757b5 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -35,6 +35,7 @@ pub enum ApiIdentifier {
ConnectorOnboarding,
Recon,
Poll,
+ ApplePayCertificatesMigration,
}
impl From<Flow> for ApiIdentifier {
@@ -186,6 +187,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::GsmRuleUpdate
| Flow::GsmRuleDelete => Self::Gsm,
+ Flow::ApplePayCertificatesMigration => Self::ApplePayCertificatesMigration,
+
Flow::UserConnectAccount
| Flow::UserSignUp
| Flow::UserSignIn
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index e17ec791637..21aea14caf5 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -805,6 +805,7 @@ impl<F1, F2, T1, T2> ForeignFrom<(&RouterData<F1, T1, PaymentsResponseData>, T2)
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
+ connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
@@ -865,6 +866,7 @@ impl<F1, F2>
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
+ connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 0b932f9aeb1..7e296d0b4a8 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -85,6 +85,7 @@ impl VerifyConnectorData {
connector_customer: None,
connector_auth_type: self.connector_auth.clone(),
connector_meta_data: None,
+ connector_wallets_details: None,
payment_method_token: None,
connector_api_version: None,
recurring_mandate_payment_data: None,
diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs
index 0e7f5b081c3..6c2f6a06e1e 100644
--- a/crates/router/src/types/domain/merchant_connector_account.rs
+++ b/crates/router/src/types/domain/merchant_connector_account.rs
@@ -11,7 +11,10 @@ use diesel_models::{
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
-use super::{behaviour, types::TypeEncryption};
+use super::{
+ behaviour,
+ types::{self, AsyncLift, TypeEncryption},
+};
#[derive(Clone, Debug)]
pub struct MerchantConnectorAccount {
pub id: Option<i32>,
@@ -36,6 +39,7 @@ pub struct MerchantConnectorAccount {
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<serde_json::Value>,
pub status: enums::ConnectorStatus,
+ pub connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>,
}
#[derive(Debug)]
@@ -56,6 +60,10 @@ pub enum MerchantConnectorAccountUpdate {
pm_auth_config: Option<serde_json::Value>,
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
+ connector_wallets_details: Option<Encryptable<Secret<serde_json::Value>>>,
+ },
+ ConnectorWalletDetailsUpdate {
+ connector_wallets_details: Encryptable<Secret<serde_json::Value>>,
},
}
@@ -92,6 +100,7 @@ impl behaviour::Conversion for MerchantConnectorAccount {
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
+ connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
},
)
}
@@ -132,6 +141,13 @@ impl behaviour::Conversion for MerchantConnectorAccount {
applepay_verified_domains: other.applepay_verified_domains,
pm_auth_config: other.pm_auth_config,
status: other.status,
+ connector_wallets_details: other
+ .connector_wallets_details
+ .async_lift(|inner| types::decrypt(inner, key.peek()))
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting connector wallets details".to_string(),
+ })?,
})
}
@@ -160,6 +176,7 @@ impl behaviour::Conversion for MerchantConnectorAccount {
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
+ connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
})
}
}
@@ -183,6 +200,7 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
pm_auth_config,
connector_label,
status,
+ connector_wallets_details,
} => Self {
merchant_id,
connector_type,
@@ -201,6 +219,29 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
pm_auth_config,
connector_label,
status,
+ connector_wallets_details: connector_wallets_details.map(Encryption::from),
+ },
+ MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {
+ connector_wallets_details,
+ } => Self {
+ connector_wallets_details: Some(Encryption::from(connector_wallets_details)),
+ merchant_id: None,
+ connector_type: None,
+ connector_name: None,
+ connector_account_details: None,
+ connector_label: None,
+ test_mode: None,
+ disabled: None,
+ merchant_connector_id: None,
+ payment_methods_enabled: None,
+ frm_configs: None,
+ metadata: None,
+ modified_at: None,
+ connector_webhook_details: None,
+ frm_config: None,
+ applepay_verified_domains: None,
+ pm_auth_config: None,
+ status: None,
},
}
}
diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs
index 51d3210a70f..021505c644f 100644
--- a/crates/router/src/types/domain/payments.rs
+++ b/crates/router/src/types/domain/payments.rs
@@ -1,10 +1,10 @@
pub use hyperswitch_domain_models::payment_method_data::{
- AliPayQr, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod, BankDebitData,
- BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData, CardToken,
- CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails, GoPayRedirection,
- GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData,
- GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection,
- MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData,
+ AliPayQr, ApplePayFlow, ApplePayThirdPartySdkData, ApplePayWalletData, ApplepayPaymentMethod,
+ BankDebitData, BankRedirectData, BankTransferData, BoletoVoucherData, Card, CardRedirectData,
+ CardToken, CashappQr, CryptoData, GcashRedirection, GiftCardData, GiftCardDetails,
+ GoPayRedirection, GooglePayPaymentMethodInfo, GooglePayRedirectData,
+ GooglePayThirdPartySdkData, GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData,
+ KakaoPayRedirection, MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData,
SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, UpiCollectData, UpiData,
UpiIntentData, VoucherData, WalletData, WeChatPayQr,
};
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index b83d3138b7c..e71219b6a9e 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -707,13 +707,13 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
}
pub fn add_apple_pay_flow_metrics(
- apple_pay_flow: &Option<enums::ApplePayFlow>,
+ apple_pay_flow: &Option<domain::ApplePayFlow>,
connector: Option<String>,
merchant_id: String,
) {
if let Some(flow) = apple_pay_flow {
match flow {
- enums::ApplePayFlow::Simplified => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add(
+ domain::ApplePayFlow::Simplified(_) => metrics::APPLE_PAY_SIMPLIFIED_FLOW.add(
&metrics::CONTEXT,
1,
&[
@@ -724,7 +724,7 @@ pub fn add_apple_pay_flow_metrics(
metrics::request::add_attributes("merchant_id", merchant_id.to_owned()),
],
),
- enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add(
+ domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add(
&metrics::CONTEXT,
1,
&[
@@ -741,14 +741,14 @@ pub fn add_apple_pay_flow_metrics(
pub fn add_apple_pay_payment_status_metrics(
payment_attempt_status: enums::AttemptStatus,
- apple_pay_flow: Option<enums::ApplePayFlow>,
+ apple_pay_flow: Option<domain::ApplePayFlow>,
connector: Option<String>,
merchant_id: String,
) {
if payment_attempt_status == enums::AttemptStatus::Charged {
if let Some(flow) = apple_pay_flow {
match flow {
- enums::ApplePayFlow::Simplified => {
+ domain::ApplePayFlow::Simplified(_) => {
metrics::APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT.add(
&metrics::CONTEXT,
1,
@@ -761,7 +761,7 @@ pub fn add_apple_pay_payment_status_metrics(
],
)
}
- enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT
+ domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_SUCCESSFUL_PAYMENT
.add(
&metrics::CONTEXT,
1,
@@ -778,7 +778,7 @@ pub fn add_apple_pay_payment_status_metrics(
} else if payment_attempt_status == enums::AttemptStatus::Failure {
if let Some(flow) = apple_pay_flow {
match flow {
- enums::ApplePayFlow::Simplified => {
+ domain::ApplePayFlow::Simplified(_) => {
metrics::APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT.add(
&metrics::CONTEXT,
1,
@@ -791,7 +791,7 @@ pub fn add_apple_pay_payment_status_metrics(
],
)
}
- enums::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add(
+ domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT.add(
&metrics::CONTEXT,
1,
&[
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 10e8b366530..b01c5abb968 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -97,6 +97,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
None,
),
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
@@ -159,6 +160,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
response: Err(types::ErrorResponse::default()),
address: PaymentAddress::default(),
connector_meta_data: None,
+ connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 0de19f17b54..be86d377299 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -540,6 +540,7 @@ pub trait ConnectorActions: Connector {
connector_meta_data: info
.clone()
.and_then(|a| a.connector_meta_data.map(Secret::new)),
+ connector_wallets_details: None,
amount_captured: None,
access_token: info.clone().and_then(|a| a.access_token),
session_token: None,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 110532f524d..51f762e3713 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -298,6 +298,8 @@ pub enum Flow {
GsmRuleRetrieve,
/// Gsm Rule Update flow
GsmRuleUpdate,
+ /// Apple pay certificates migration
+ ApplePayCertificatesMigration,
/// Gsm Rule Delete flow
GsmRuleDelete,
/// User Sign Up
diff --git a/crates/storage_impl/src/errors.rs b/crates/storage_impl/src/errors.rs
index 4356b6b7997..b153c47b882 100644
--- a/crates/storage_impl/src/errors.rs
+++ b/crates/storage_impl/src/errors.rs
@@ -101,6 +101,12 @@ impl From<error_stack::Report<RedisError>> for StorageError {
}
}
+impl From<diesel::result::Error> for StorageError {
+ fn from(err: diesel::result::Error) -> Self {
+ Self::from(error_stack::report!(DatabaseError::from(err)))
+ }
+}
+
impl From<error_stack::Report<DatabaseError>> for StorageError {
fn from(err: error_stack::Report<DatabaseError>) -> Self {
Self::DatabaseError(err)
diff --git a/migrations/2024-05-28-054439_connector_wallets_details/down.sql b/migrations/2024-05-28-054439_connector_wallets_details/down.sql
new file mode 100644
index 00000000000..dea26bbd1eb
--- /dev/null
+++ b/migrations/2024-05-28-054439_connector_wallets_details/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE merchant_connector_account DROP COLUMN IF EXISTS connector_wallets_details;
\ No newline at end of file
diff --git a/migrations/2024-05-28-054439_connector_wallets_details/up.sql b/migrations/2024-05-28-054439_connector_wallets_details/up.sql
new file mode 100644
index 00000000000..c75de9204df
--- /dev/null
+++ b/migrations/2024-05-28-054439_connector_wallets_details/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE merchant_connector_account ADD COLUMN IF NOT EXISTS connector_wallets_details BYTEA DEFAULT NULL;
\ No newline at end of file
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index f42481798a4..ba0d8946192 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -13697,6 +13697,63 @@
},
"additionalProperties": false
},
+ "PaymentProcessingDetails": {
+ "type": "object",
+ "required": [
+ "payment_processing_certificate",
+ "payment_processing_certificate_key"
+ ],
+ "properties": {
+ "payment_processing_certificate": {
+ "type": "string"
+ },
+ "payment_processing_certificate_key": {
+ "type": "string"
+ }
+ }
+ },
+ "PaymentProcessingDetailsAt": {
+ "oneOf": [
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentProcessingDetails"
+ },
+ {
+ "type": "object",
+ "required": [
+ "payment_processing_details_at"
+ ],
+ "properties": {
+ "payment_processing_details_at": {
+ "type": "string",
+ "enum": [
+ "Hyperswitch"
+ ]
+ }
+ }
+ }
+ ]
+ },
+ {
+ "type": "object",
+ "required": [
+ "payment_processing_details_at"
+ ],
+ "properties": {
+ "payment_processing_details_at": {
+ "type": "string",
+ "enum": [
+ "Connector"
+ ]
+ }
+ }
+ }
+ ],
+ "discriminator": {
+ "propertyName": "payment_processing_details_at"
+ }
+ },
"PaymentRetrieveBody": {
"type": "object",
"properties": {
@@ -18394,43 +18451,55 @@
}
},
"SessionTokenInfo": {
- "type": "object",
- "required": [
- "certificate",
- "certificate_keys",
- "merchant_identifier",
- "display_name",
- "initiative",
- "initiative_context"
- ],
- "properties": {
- "certificate": {
- "type": "string"
- },
- "certificate_keys": {
- "type": "string"
- },
- "merchant_identifier": {
- "type": "string"
- },
- "display_name": {
- "type": "string"
- },
- "initiative": {
- "type": "string"
- },
- "initiative_context": {
- "type": "string"
- },
- "merchant_business_country": {
+ "allOf": [
+ {
"allOf": [
{
- "$ref": "#/components/schemas/CountryAlpha2"
+ "$ref": "#/components/schemas/PaymentProcessingDetailsAt"
}
],
"nullable": true
+ },
+ {
+ "type": "object",
+ "required": [
+ "certificate",
+ "certificate_keys",
+ "merchant_identifier",
+ "display_name",
+ "initiative",
+ "initiative_context"
+ ],
+ "properties": {
+ "certificate": {
+ "type": "string"
+ },
+ "certificate_keys": {
+ "type": "string"
+ },
+ "merchant_identifier": {
+ "type": "string"
+ },
+ "display_name": {
+ "type": "string"
+ },
+ "initiative": {
+ "type": "string"
+ },
+ "initiative_context": {
+ "type": "string"
+ },
+ "merchant_business_country": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/CountryAlpha2"
+ }
+ ],
+ "nullable": true
+ }
+ }
}
- }
+ ]
},
"StraightThroughAlgorithm": {
"oneOf": [
|
2024-05-28T13:19:09Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently apple pay related details are being stored in the connector metadata, as in future we are going to add apple pay decrypted flow support for ios app we will be collecting the apple pay payment processing certificates as well. As this ppc and ppc key needs to be securely stored, we need to move the existing certificates to a new column which stores the encrypted certificates.
This pr adds a api end point (`/apple_pay_certificates_migration`) to migrate the apple pay details form the merchant connector account `metadata` to the newly added column connector (`connector_wallets_details`). This api takes list of `merchant_ids` as input and then lists all the configured merchant connector accounts for that merchant id. After which it checks for the apple pay details in the metadata in the merchant connector account, if present it is encrypted by merchant's DEK (Data Encryption Key) and will be stored in the newly added column (`connector_wallets_details`) in the merchant connector account. Response contains the list of merchant_ids for migration succeeded (`migration_successful`) and failed (`migraiton_failed`).
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Apple pay certificate migration api
```
curl --location 'http://localhost:8080/apple_pay_certificates_migration' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_ids": ["merchant_1713176513", "merchant_1714122879"]
}'
```
<img width="719" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bb66cc2c-69f7-4c6e-bb3c-1e184944bbd2">
-> Check the db for connector_wallets_details of mca belonging to above merchants
<img width="862" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/24d5c9ed-f091-49cd-983b-839724024118">
-> Create MCA with apple pay `simplified` and manual `flow`
metadata for apple pay `simplified`
```
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
metadata for apple pay `manual` flow
```
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "",
"display_name": "applepay",
"certificate_keys": "",
"merchant_business_coountry": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Confirm an apple pay payment with above flows
<img width="1159" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a70ebc44-948a-421d-bcdf-3f9a2adb4361">
-> Create a apple pay payment with the below metadata
```
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "",
"display_name": "applepay",
"certificate_keys": "",
"payment_processing_details_at": "Hyperswitch",
"payment_processing_certificate": "",
"payment_processing_certificate_key": "",
"initiative_context": "sdk-test-app.netlify.app",
"merchant_identifier": "",
"merchant_business_coountry": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Confirm apple pay payment
<img width="1055" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4460d4e3-24e9-4348-ac1c-c05d6bef5e3e">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d242850b63173f314fb259451139464f09e0a9e9
|
-> Apple pay certificate migration api
```
curl --location 'http://localhost:8080/apple_pay_certificates_migration' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"merchant_ids": ["merchant_1713176513", "merchant_1714122879"]
}'
```
<img width="719" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bb66cc2c-69f7-4c6e-bb3c-1e184944bbd2">
-> Check the db for connector_wallets_details of mca belonging to above merchants
<img width="862" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/24d5c9ed-f091-49cd-983b-839724024118">
-> Create MCA with apple pay `simplified` and manual `flow`
metadata for apple pay `simplified`
```
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
metadata for apple pay `manual` flow
```
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "",
"display_name": "applepay",
"certificate_keys": "",
"merchant_business_coountry": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Confirm an apple pay payment with above flows
<img width="1159" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/a70ebc44-948a-421d-bcdf-3f9a2adb4361">
-> Create a apple pay payment with the below metadata
```
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "",
"display_name": "applepay",
"certificate_keys": "",
"payment_processing_details_at": "Hyperswitch",
"payment_processing_certificate": "",
"payment_processing_certificate_key": "",
"initiative_context": "sdk-test-app.netlify.app",
"merchant_identifier": "",
"merchant_business_coountry": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
}
```
-> Confirm apple pay payment
<img width="1055" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4460d4e3-24e9-4348-ac1c-c05d6bef5e3e">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4752
|
Bug: mask the email address being logged in the payment_method_list response logs
As of now the payment method list response logs contains the email address, this needs to be mased
<img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4c219a49-13d3-4fa1-804a-21c215aa5675">
|
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index dd7791ee2d2..5a19a225dee 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -531,7 +531,8 @@ pub struct RequiredFieldInfo {
#[schema(value_type = FieldType)]
pub field_type: api_enums::FieldType,
- pub value: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub value: Option<masking::Secret<String>>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index d3870a9e598..741a0e246b6 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2267,7 +2267,7 @@ pub async fn list_payment_methods(
.as_ref()
.and_then(|r| get_val(key.to_owned(), r));
if let Some(s) = temp {
- val.value = Some(s)
+ val.value = Some(s.into())
};
}
}
|
2024-05-23T14:07:07Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
https://github.com/juspay/hyperswitch/pull/4749
This pr is to mask the email address being logged in the payment method list response.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant account and mca
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_jviyQiUsX9uHI99VXUlF_secret_lHrA6q5GKvNvd5a0blUQ' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_df002da8beb74682ac3e8677a4b82217'
```
in the below log we can see the email address being logged (this is without the changes in this pr)
<img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0900eba7-09e0-4db7-95aa-bcd102cb49d6">
after the changes the email is being masked
<img width="1466" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67164e06-9953-4b17-83e1-3ccdad17d129">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f79c12d4f78ac622300e56f7159ca72d65a4ac0d
|
-> Create a merchant account and mca
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_jviyQiUsX9uHI99VXUlF_secret_lHrA6q5GKvNvd5a0blUQ' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_df002da8beb74682ac3e8677a4b82217'
```
in the below log we can see the email address being logged (this is without the changes in this pr)
<img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0900eba7-09e0-4db7-95aa-bcd102cb49d6">
after the changes the email is being masked
<img width="1466" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67164e06-9953-4b17-83e1-3ccdad17d129">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4773
|
Bug: [FEATURE] Process tracker flow for PaymentMethod Status update
### Feature Description
For vaulting flows, currently, the `PaymentMethodStatus` is kept as `awaiting_data` during the generation of client_secret, we want to implement a process tracker flow to update the status to `inactive` upon session expiry.
### Possible Implementation
Implementing a new flow for `PaymentMethodStatus` update.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/diesel_models/src/process_tracker.rs b/crates/diesel_models/src/process_tracker.rs
index 135c8e2b055..342ad8453af 100644
--- a/crates/diesel_models/src/process_tracker.rs
+++ b/crates/diesel_models/src/process_tracker.rs
@@ -208,6 +208,7 @@ pub enum ProcessTrackerRunner {
ApiKeyExpiryWorkflow,
OutgoingWebhookRetryWorkflow,
AttachPayoutAccountWorkflow,
+ PaymentMethodStatusUpdateWorkflow,
}
#[cfg(test)]
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 167e7a6b6ed..1afc09e5a6a 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -310,6 +310,9 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
)
}
}
+ storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow => Ok(Box::new(
+ workflows::payment_method_status_update::PaymentMethodStatusUpdateWorkflow,
+ )),
}
};
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index f0aa0480d09..a4d4f38bfaf 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -8,11 +8,18 @@ use api_models::payments::CardToken;
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
use diesel_models::enums;
+use error_stack::ResultExt;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use router_env::{instrument, tracing};
use crate::{
- core::{errors::RouterResult, payments::helpers, pm_auth as core_pm_auth},
+ consts,
+ core::{
+ errors::{self, RouterResult},
+ payments::helpers,
+ pm_auth as core_pm_auth,
+ },
+ db,
routes::SessionState,
types::{
api::{self, payments},
@@ -20,6 +27,9 @@ use crate::{
},
};
+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(
pm_data: &Option<payments::PaymentMethodData>,
@@ -94,6 +104,66 @@ pub async fn retrieve_payment_method(
}
}
+fn generate_task_id_for_payment_method_status_update_workflow(
+ key_id: &str,
+ runner: &storage::ProcessTrackerRunner,
+ task: &str,
+) -> String {
+ format!("{runner}_{task}_{key_id}")
+}
+
+pub async fn add_payment_method_status_update_task(
+ db: &dyn db::StorageInterface,
+ payment_method: &diesel_models::PaymentMethod,
+ prev_status: enums::PaymentMethodStatus,
+ curr_status: enums::PaymentMethodStatus,
+ merchant_id: &str,
+) -> Result<(), errors::ProcessTrackerError> {
+ let created_at = payment_method.created_at;
+ let schedule_time =
+ created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
+
+ let tracking_data = storage::PaymentMethodStatusTrackingData {
+ payment_method_id: payment_method.payment_method_id.clone(),
+ prev_status,
+ curr_status,
+ merchant_id: merchant_id.to_string(),
+ };
+
+ 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.payment_method_id.as_str(),
+ &runner,
+ task,
+ );
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ task,
+ runner,
+ tag,
+ tracking_data,
+ schedule_time,
+ )
+ .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.payment_method_id.clone()
+ )
+ })?;
+
+ Ok(())
+}
+
#[instrument(skip_all)]
pub async fn retrieve_payment_method_with_token(
state: &SessionState,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index fad3e6d918d..ff4517a17d9 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -45,7 +45,9 @@ use crate::{
configs::settings,
core::{
errors::{self, StorageErrorExt},
- payment_methods::{transformers as payment_methods, vault},
+ payment_methods::{
+ add_payment_method_status_update_task, transformers as payment_methods, vault,
+ },
payments::{
helpers,
routing::{self, SessionFlowRoutingInput},
@@ -297,6 +299,21 @@ pub async fn get_client_secret_or_add_payment_method(
)
.await?;
+ if res.status == enums::PaymentMethodStatus::AwaitingData {
+ add_payment_method_status_update_task(
+ db,
+ &res,
+ enums::PaymentMethodStatus::AwaitingData,
+ enums::PaymentMethodStatus::Inactive,
+ merchant_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to add payment method status update task in process tracker",
+ )?;
+ }
+
Ok(services::api::ApplicationResponse::Json(
api::PaymentMethodResponse::foreign_from(res),
))
@@ -357,7 +374,7 @@ pub async fn add_payment_method_data(
.attach_printable("Unable to find payment method")?;
if payment_method.status != enums::PaymentMethodStatus::AwaitingData {
- return Err((errors::ApiErrorResponse::DuplicatePaymentMethod).into());
+ return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
}
let customer_id = payment_method.customer_id.clone();
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index d9f96ef482c..308aa362562 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -110,3 +110,11 @@ impl DerefMut for PaymentsMandateReference {
&mut self.0
}
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub struct PaymentMethodStatusTrackingData {
+ pub payment_method_id: String,
+ pub prev_status: enums::PaymentMethodStatus,
+ pub curr_status: enums::PaymentMethodStatus,
+ pub merchant_id: String,
+}
diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs
index 7b29ded5185..2f858c59809 100644
--- a/crates/router/src/workflows.rs
+++ b/crates/router/src/workflows.rs
@@ -3,6 +3,7 @@ pub mod api_key_expiry;
#[cfg(feature = "payouts")]
pub mod attach_payout_account_workflow;
pub mod outgoing_webhook_retry;
+pub mod payment_method_status_update;
pub mod payment_sync;
pub mod refund_router;
pub mod tokenized_data;
diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs
new file mode 100644
index 00000000000..b8e57360d90
--- /dev/null
+++ b/crates/router/src/workflows/payment_method_status_update.rs
@@ -0,0 +1,107 @@
+use common_utils::ext_traits::ValueExt;
+use scheduler::{
+ consumer::types::process_data, utils as pt_utils, workflows::ProcessTrackerWorkflow,
+};
+
+use crate::{
+ errors,
+ logger::error,
+ routes::SessionState,
+ types::storage::{self, PaymentMethodStatusTrackingData},
+};
+
+pub struct PaymentMethodStatusUpdateWorkflow;
+
+#[async_trait::async_trait]
+impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow {
+ async fn execute_workflow<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ let db = &*state.store;
+ let tracking_data: PaymentMethodStatusTrackingData = process
+ .tracking_data
+ .clone()
+ .parse_value("PaymentMethodStatusTrackingData")?;
+
+ let retry_count = process.retry_count;
+ let pm_id = tracking_data.payment_method_id;
+ let prev_pm_status = tracking_data.prev_status;
+ let curr_pm_status = tracking_data.curr_status;
+ let merchant_id = tracking_data.merchant_id;
+
+ let key_store = state
+ .store
+ .get_merchant_key_store_by_merchant_id(
+ merchant_id.as_str(),
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await?;
+
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&merchant_id, &key_store)
+ .await?;
+
+ let payment_method = db
+ .find_payment_method(&pm_id, merchant_account.storage_scheme)
+ .await?;
+
+ if payment_method.status != prev_pm_status {
+ return db
+ .as_scheduler()
+ .finish_process_with_business_status(process, "PROCESS_ALREADY_COMPLETED")
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into);
+ }
+
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(curr_pm_status),
+ };
+
+ let res = db
+ .update_payment_method(payment_method, pm_update, merchant_account.storage_scheme)
+ .await
+ .map_err(errors::ProcessTrackerError::EStorageError);
+
+ if let Ok(_pm) = res {
+ db.as_scheduler()
+ .finish_process_with_business_status(process, "COMPLETED_BY_PT")
+ .await?;
+ } else {
+ let mapping = process_data::PaymentMethodsPTMapping::default();
+ let time_delta = if retry_count == 0 {
+ Some(mapping.default_mapping.start_after)
+ } else {
+ pt_utils::get_delay(retry_count + 1, &mapping.default_mapping.frequencies)
+ };
+
+ let schedule_time = pt_utils::get_time_from_delta(time_delta);
+
+ match schedule_time {
+ Some(s_time) => db
+ .as_scheduler()
+ .retry_process(process, s_time)
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?,
+ None => db
+ .as_scheduler()
+ .finish_process_with_business_status(process, "RETRIES_EXCEEDED")
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?,
+ };
+ };
+
+ Ok(())
+ }
+
+ async fn error_handler<'a>(
+ &'a self,
+ _state: &'a SessionState,
+ process: storage::ProcessTracker,
+ _error: errors::ProcessTrackerError,
+ ) -> errors::CustomResult<(), errors::ProcessTrackerError> {
+ error!(%process.id, "Failed while executing workflow");
+ Ok(())
+ }
+}
diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs
index 7f073a8e10b..f3253e0ad34 100644
--- a/crates/scheduler/src/utils.rs
+++ b/crates/scheduler/src/utils.rs
@@ -342,7 +342,7 @@ pub fn get_outgoing_webhook_retry_schedule_time(
}
/// Get the delay based on the retry count
-fn get_delay<'a>(
+pub fn get_delay<'a>(
retry_count: i32,
frequencies: impl IntoIterator<Item = &'a (i32, i32)>,
) -> Option<i32> {
|
2024-05-17T07:57:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR -
- Implemented a process tracker workflow for status update after pm client_secret expiry
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
When vaulting is done within session -
1. Create a Payment_method
```
curl --location --request POST 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \
--data-raw '{
"customer_id": "cus_LALaPcTuxxmCBORKevPC"
}'
```
Response -
```
{
"merchant_id": "sarthak1",
"customer_id": "cus_LALaPcTuxxmCBORKevPC",
"payment_method_id": "pm_gnnmqGeng12XWnsr3AWy",
"payment_method": null,
"payment_method_type": null,
"card": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": "2024-06-19T08:58:05.050Z",
"last_used_at": null,
"client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co"
}
```
2. Vault using `/save`
```
curl --location --request POST 'http://localhost:8080/payment_methods/pm_gnnmqGeng12XWnsr3AWy/save' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' \
--data-raw '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "visa",
"client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "08",
"card_exp_year": "2028",
"card_holder_name": "joseph"
}
}
}'
```
Response -
```
{
"merchant_id": "sarthak1",
"customer_id": null,
"payment_method_id": "pm_gnnmqGeng12XWnsr3AWy",
"payment_method": "card",
"payment_method_type": "credit",
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "08",
"expiry_year": "2028",
"card_token": null,
"card_holder_name": "joseph",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"metadata": null,
"created": "2024-06-19T08:58:19.752Z",
"last_used_at": "2024-06-19T08:58:19.752Z",
"client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co"
}
```
DB entry for PT -
<img width="1509" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/427e090a-79c0-4efe-ad6a-52968f71bdfb">
When vaulting is not done within session -
1. Create Payment method -
```
curl --location --request POST 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \
--data-raw '{
"customer_id": "cus_LALaPcTuxxmCBORKevPC"
}'
```
Response -
```
{
"merchant_id": "sarthak1",
"customer_id": "cus_LALaPcTuxxmCBORKevPC",
"payment_method_id": "pm_LlMdO3mS6HQ9EJLfDpL3",
"payment_method": null,
"payment_method_type": null,
"card": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": "2024-06-19T09:04:11.634Z",
"last_used_at": null,
"client_secret": "pm_LlMdO3mS6HQ9EJLfDpL3_secret_4565heI7J2bLsBgTLbJ5"
}
```
2. Vault using `/save` after session expiry -
```
curl --location --request POST 'http://localhost:8080/payment_methods/pm_LlMdO3mS6HQ9EJLfDpL3/save' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' \
--data-raw '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "visa",
"client_secret": "pm_LlMdO3mS6HQ9EJLfDpL3_secret_4565heI7J2bLsBgTLbJ5",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "08",
"card_exp_year": "2028",
"card_holder_name": "joseph"
}
}
}'
```
Response -
```
{
"error": {
"type": "invalid_request",
"message": "The payment method with the specified details already exists in our records",
"code": "HE_01"
}
}
```
DB entry after session expiry -
<img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/4c574e3d-48f7-4844-b493-a306c1ac3c5a">
<img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/60daa679-d78a-438d-bc3c-7ad769363014">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f84ed6a8a00cd5f28debfbc1bb1f8dba14eaa387
|
When vaulting is done within session -
1. Create a Payment_method
```
curl --location --request POST 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \
--data-raw '{
"customer_id": "cus_LALaPcTuxxmCBORKevPC"
}'
```
Response -
```
{
"merchant_id": "sarthak1",
"customer_id": "cus_LALaPcTuxxmCBORKevPC",
"payment_method_id": "pm_gnnmqGeng12XWnsr3AWy",
"payment_method": null,
"payment_method_type": null,
"card": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": "2024-06-19T08:58:05.050Z",
"last_used_at": null,
"client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co"
}
```
2. Vault using `/save`
```
curl --location --request POST 'http://localhost:8080/payment_methods/pm_gnnmqGeng12XWnsr3AWy/save' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' \
--data-raw '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "visa",
"client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "08",
"card_exp_year": "2028",
"card_holder_name": "joseph"
}
}
}'
```
Response -
```
{
"merchant_id": "sarthak1",
"customer_id": null,
"payment_method_id": "pm_gnnmqGeng12XWnsr3AWy",
"payment_method": "card",
"payment_method_type": "credit",
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "08",
"expiry_year": "2028",
"card_token": null,
"card_holder_name": "joseph",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"metadata": null,
"created": "2024-06-19T08:58:19.752Z",
"last_used_at": "2024-06-19T08:58:19.752Z",
"client_secret": "pm_gnnmqGeng12XWnsr3AWy_secret_ikc5JKsFFREjtR9hk5Co"
}
```
DB entry for PT -
<img width="1509" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/427e090a-79c0-4efe-ad6a-52968f71bdfb">
When vaulting is not done within session -
1. Create Payment method -
```
curl --location --request POST 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_cHN6hMdCFUUrNWjYSxnwhiuMsg83rXTX9jBmtHmCL6sq9a43PswY304MSt3a9blR' \
--data-raw '{
"customer_id": "cus_LALaPcTuxxmCBORKevPC"
}'
```
Response -
```
{
"merchant_id": "sarthak1",
"customer_id": "cus_LALaPcTuxxmCBORKevPC",
"payment_method_id": "pm_LlMdO3mS6HQ9EJLfDpL3",
"payment_method": null,
"payment_method_type": null,
"card": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": "2024-06-19T09:04:11.634Z",
"last_used_at": null,
"client_secret": "pm_LlMdO3mS6HQ9EJLfDpL3_secret_4565heI7J2bLsBgTLbJ5"
}
```
2. Vault using `/save` after session expiry -
```
curl --location --request POST 'http://localhost:8080/payment_methods/pm_LlMdO3mS6HQ9EJLfDpL3/save' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_16e38a16176e45298a70da6c56c5028d' \
--data-raw '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "visa",
"client_secret": "pm_LlMdO3mS6HQ9EJLfDpL3_secret_4565heI7J2bLsBgTLbJ5",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "08",
"card_exp_year": "2028",
"card_holder_name": "joseph"
}
}
}'
```
Response -
```
{
"error": {
"type": "invalid_request",
"message": "The payment method with the specified details already exists in our records",
"code": "HE_01"
}
}
```
DB entry after session expiry -
<img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/4c574e3d-48f7-4844-b493-a306c1ac3c5a">
<img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/60daa679-d78a-438d-bc3c-7ad769363014">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4757
|
Bug: [FIX] Fix the functionality to show both the disabled and enabled connectors while List Merchant Connector Account
### Feature Description
Fix the functionality to show both the disabled and enabled connectors while List Merchant Connector Account
### Possible Implementation
Fix the functionality to show both the disabled and enabled connectors while List Merchant Connector Account
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rs
index cc73bd7a532..bd24d12ec22 100644
--- a/crates/diesel_models/src/query/merchant_connector_account.rs
+++ b/crates/diesel_models/src/query/merchant_connector_account.rs
@@ -124,9 +124,7 @@ impl MerchantConnectorAccount {
if get_disabled {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
- dsl::merchant_id
- .eq(merchant_id.to_owned())
- .and(dsl::disabled.eq(true)),
+ dsl::merchant_id.eq(merchant_id.to_owned()),
None,
None,
Some(dsl::created_at.asc()),
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 5a12334c385..9fe8d899ea3 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3700,7 +3700,12 @@ pub async fn get_mca_status(
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: merchant_id.to_string(),
})?;
+
let mut mca_ids = HashSet::new();
+ let mcas = mcas
+ .into_iter()
+ .filter(|mca| mca.disabled == Some(true))
+ .collect::<Vec<_>>();
for mca in mcas {
mca_ids.insert(mca.merchant_connector_id);
|
2024-05-24T08:36:45Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
revert the filter for getting the mcas which are disabled, and explicitly get the Mca that are disabled
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- All the MCA's either disabled/enabled will show in the LIST MCAs
```
Response
[
{
"connector_type": "fiz_operations",
"connector_name": "cybersource",
"connector_label": "cybersource_US_default_2",
"merchant_connector_id": "mca_JfI8xFhxTnL5q2bFhpUW",
"profile_id": "pro_NMDohQHyrqzAkUjBjDmB",
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 0,
"maximum_amount": 10000,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": {
"merchant_secret": "samraat",
"additional_secret": null
},
"metadata": {
"google_pay": {
"merchant_info": {
"merchant_id": "vbewlji",
"merchant_name": "bluesnap"
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "bluesnap",
"gateway_merchant_id": "1087905"
}
}
}
]
},
"terminal_id": "10000001",
"account_name": "transaction_processing"
},
"test_mode": true,
"disabled": true,
"frm_configs": null,
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active"
},
{
"connector_type": "fiz_operations",
"connector_name": "stripe",
"connector_label": "stripe_US_default7",
"merchant_connector_id": "mca_mETGK4Fi1JQG7ggXzUnd",
"profile_id": "pro_NMDohQHyrqzAkUjBjDmB",
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 200000,
"recurring_enabled": false,
"installment_payment_enabled": false
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"JCB"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 200000,
"recurring_enabled": false,
"installment_payment_enabled": false
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 50000,
"recurring_enabled": false,
"installment_payment_enabled": false
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 600,
"maximum_amount": 800,
"recurring_enabled": false,
"installment_payment_enabled": false
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "affirm",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 50000,
"recurring_enabled": false,
"installment_payment_enabled": false
}
]
}
],
"connector_webhook_details": null,
"metadata": {
"city": "NY",
"unit": "245"
},
"test_mode": false,
"disabled": false,
"frm_configs": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active"
},
{
"connector_type": "fiz_operations",
"connector_name": "cybersource",
"connector_label": "cybersource_US_default_default",
"merchant_connector_id": "mca_Ec6WKYkD3tP5m4HwSmxd",
"profile_id": "pro_NMDohQHyrqzAkUjBjDmB",
ment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"DinersClub",
"Discover"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"DinersClub",
"Discover"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": {
"merchant_secret": "MyWebhookSecret",
"additional_secret": null
},
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
},
"test_mode": false,
"disabled": false,
"frm_configs": null,
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active"
}
]
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
55ccce61898083992afeab03ba1690954b1b45ef
|
- All the MCA's either disabled/enabled will show in the LIST MCAs
```
Response
[
{
"connector_type": "fiz_operations",
"connector_name": "cybersource",
"connector_label": "cybersource_US_default_2",
"merchant_connector_id": "mca_JfI8xFhxTnL5q2bFhpUW",
"profile_id": "pro_NMDohQHyrqzAkUjBjDmB",
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 0,
"maximum_amount": 10000,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": {
"merchant_secret": "samraat",
"additional_secret": null
},
"metadata": {
"google_pay": {
"merchant_info": {
"merchant_id": "vbewlji",
"merchant_name": "bluesnap"
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "bluesnap",
"gateway_merchant_id": "1087905"
}
}
}
]
},
"terminal_id": "10000001",
"account_name": "transaction_processing"
},
"test_mode": true,
"disabled": true,
"frm_configs": null,
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active"
},
{
"connector_type": "fiz_operations",
"connector_name": "stripe",
"connector_label": "stripe_US_default7",
"merchant_connector_id": "mca_mETGK4Fi1JQG7ggXzUnd",
"profile_id": "pro_NMDohQHyrqzAkUjBjDmB",
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 200000,
"recurring_enabled": false,
"installment_payment_enabled": false
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"JCB"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 200000,
"recurring_enabled": false,
"installment_payment_enabled": false
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 50000,
"recurring_enabled": false,
"installment_payment_enabled": false
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 600,
"maximum_amount": 800,
"recurring_enabled": false,
"installment_payment_enabled": false
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "affirm",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 50000,
"recurring_enabled": false,
"installment_payment_enabled": false
}
]
}
],
"connector_webhook_details": null,
"metadata": {
"city": "NY",
"unit": "245"
},
"test_mode": false,
"disabled": false,
"frm_configs": null,
"business_country": null,
"business_label": null,
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active"
},
{
"connector_type": "fiz_operations",
"connector_name": "cybersource",
"connector_label": "cybersource_US_default_default",
"merchant_connector_id": "mca_Ec6WKYkD3tP5m4HwSmxd",
"profile_id": "pro_NMDohQHyrqzAkUjBjDmB",
ment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"DinersClub",
"Discover"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard",
"DinersClub",
"Discover"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": -1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "redirect_to_url",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": {
"merchant_secret": "MyWebhookSecret",
"additional_secret": null
},
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
},
"test_mode": false,
"disabled": false,
"frm_configs": null,
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"applepay_verified_domains": null,
"pm_auth_config": null,
"status": "active"
}
]
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4780
|
Bug: Creating new email templates for Hyperswitch
- Create Email templates as per new figma designs
|
diff --git a/crates/router/src/services/email/assets/api_key_expiry_reminder.html b/crates/router/src/services/email/assets/api_key_expiry_reminder.html
index 772602d71e7..6ebb099ed74 100644
--- a/crates/router/src/services/email/assets/api_key_expiry_reminder.html
+++ b/crates/router/src/services/email/assets/api_key_expiry_reminder.html
@@ -1,149 +1,170 @@
-<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
-<title>API Key Expiry Notice</title>
-<body style="background-color: #ececec">
- <style>
- .apple-footer a {{
- text-decoration: none !important;
- color: #999 !important;
- border: none !important;
- }}
- .apple-email a {{
- text-decoration: none !important;
- color: #448bff !important;
- border: none !important;
- }}
- </style>
- <div
- id="wrapper"
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+ <title>API Key Expiry Notice</title>
+ </head>
+ <body
style="
- background-color: none;
- margin: 0 auto;
- text-align: center;
- width: 60%;
- -premailer-height: 200;
+ background-color: #f8f9fb;
+ height: 100%;
+ font-family: Arial, Helvetica, sans-serif;
"
>
- <table
- align="center"
- class="main-table"
+ <div
style="
- -premailer-cellpadding: 0;
- -premailer-cellspacing: 0;
- background-color: #fff;
- border: 0;
- border-top: 5px solid #0165ef;
- margin: 0 auto;
- mso-table-lspace: 0;
- mso-table-rspace: 0;
- padding: 0 40;
- text-align: center;
width: 100%;
+ margin: auto;
+ text-align: center;
+ background-color: #f8f9fb;
"
- bgcolor="#ffffff"
- cellpadding="0"
- cellspacing="0"
>
-
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="25"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="50"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="headline"
- style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 30px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: left;
- "
- align="center"
- >
- <p style="font-size: 18px">Dear Merchant,</p>
- <span style="font-size: 18px">
- It has come to our attention that your API key, <b>{api_key_name}</b> (<code>{prefix}*****</code>) </code> will expire in {expires_in} days. To ensure uninterrupted
- access to our platform and continued smooth operation of your services, we kindly request that you take the
- necessary actions as soon as possible.
- </span>
- </td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- height="20"
- width="100%"
- ></td>
- </tr>
-
- <tr>
- <td
- class="headline"
- style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 18px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: left;
- "
- align="center"
- >
- Thanks,<br />
- Team Hyperswitch
- </td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
-
- </table>
- </div>
-</body>
+ <table style="text-align: center; width: 100%">
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: center">
+ <table
+ style="
+ background-color: #ffffff;
+ text-align: center;
+ max-width: 50%;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ <tr>
+ <td>
+ <table style="width: 100%">
+ <tr>
+ <td style="text-align: center">
+ <img
+ src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png"
+ alt="Hyperswitch"
+ style="
+ text-align: center;
+ height: 1.3rem;
+ width: auto;
+ "
+ />
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 40px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ font-size: 1rem;
+ font-weight: 400;
+ line-height: 1.5rem;
+ min-width: 450px;
+ "
+ >
+ <table
+ style="
+ width: 90%;
+ min-width: 350px;
+ text-align: start;
+ margin: auto;
+ padding: 0 10px;
+ "
+ >
+ <tr>
+ <td style="text-align: start;">
+ <p>Dear Merchant,</p>
+ </td>
+ </tr>
+ <tr>
+ <td style="text-align: start;">
+ <p>
+ It has come to our attention that your API key, <b>{api_key_name}</b> (<code>{prefix}*****</code>) </code> will expire in {expires_in} days.
+ </p>
+ <p>
+ To ensure uninterrupted
+ access to our platform and continued smooth operation of your services, we request you to take the
+ necessary actions as soon as possible.
+ </p>
+
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 30px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: start;">
+ Thanks,<br />
+ Team Hyperswitch
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 50px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ font-size: 12px;
+ line-height: 1rem;
+ font-weight: 400;
+ color: #111326b2;
+ "
+ >
+ Follow us on
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="https://github.com/juspay/hyperswitch"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Github.png"
+ alt="Github"
+ height="15"
+ />
+ </a>
+ <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <img
+ src="https://app.hyperswitch.io/email-assets/Twitter.png"
+ alt="Twitter"
+ height="15"
+ />
+ </a>
+ <a
+ href="https://www.linkedin.com/company/hyperswitch/"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png"
+ alt="LinkedIn"
+ height="15"
+ />
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ </table>
+ </div>
+ </body>
+</html>
diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html
index c705608ec72..02f646c010d 100644
--- a/crates/router/src/services/email/assets/bizemailprod.html
+++ b/crates/router/src/services/email/assets/bizemailprod.html
@@ -1,138 +1,180 @@
-<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
-<title>Welcome to HyperSwitch!</title>
-<body style="background-color: #ececec">
- <div
- id="wrapper"
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+ <title>Welcome to Hyperswitch!</title>
+ </head>
+ <body
style="
- background-color: none;
- margin: 0 auto;
- text-align: center;
- width: 90%;
- -premailer-height: 200;
+ background-color: #f8f9fb;
+ height: 100%;
+ font-family: Arial, Helvetica, sans-serif;
"
>
- <table
- align="center"
- class="main-table"
+ <div
style="
- -premailer-cellpadding: 0;
- -premailer-cellspacing: 0;
- background-color: #fff;
- border: 0;
- border-top: 5px solid #0165ef;
- margin: 0 auto;
- mso-table-lspace: 0;
- mso-table-rspace: 0;
- padding: 0 40;
- text-align: center;
width: 100%;
+ margin: auto;
+ text-align: center;
+ background-color: #f8f9fb;
"
- bgcolor="#ffffff"
- cellpadding="0"
- cellspacing="0"
>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="copy"
- style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: left;
- line-height: 20px;
- margin-top: 20px;
- padding: 15px;
- "
- >
- <br />
- <p>Hi Team,</p>
- <p>
- A Production Account Intent has been initiated by {username} -
- please find more details below:
- </p>
- <ol>
- <li><strong>Name:</strong> {username}</li>
- <li><strong>Point of Contact Email (POC):</strong> {poc_email}</li>
- <li><strong>Legal Business Name:</strong> {legal_business_name}</li>
- <li><strong>Business Location:</strong> {business_location}</li>
- <li><strong>Business Website:</strong> {business_website}</li>
- </ol>
- <br />
- </td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- width="100%"
- ></td>
- </tr>
-
- <tr>
- <td
- class="headline"
- style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 18px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- "
- align="center"
- >
- Regards,<br />
- Hyperswitch Dashboard Team
- </td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- </table>
- </div>
-</body>
+ <table style="text-align: center; width: 100%">
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: center">
+ <table
+ style="
+ background-color: #ffffff;
+ text-align: center;
+ max-width: 60%;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td style="height: 15px"></td>
+ </tr>
+ <tr>
+ <td>
+ <table style="width: 100%">
+ <tr>
+ <td style="text-align: center">
+ <img
+ src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png"
+ alt="Hyperswitch"
+ style="
+ text-align: center;
+ height: 1.3rem;
+ width: auto;
+ "
+ />
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ font-size: 1rem;
+ font-weight: 400;
+ line-height: 1.5rem;
+ min-width: 450px;
+ "
+ >
+ <table
+ style="
+ width: 90%;
+ min-width: 350px;
+ text-align: start;
+ margin: auto;
+ padding: 0 10px;
+ "
+ >
+ <tr>
+ <td style="text-align: start">
+ <p>Hi Team,</p>
+ <p>
+ A Production Account Intent has been initiated by
+ {username} - please find more details below:
+ </p>
+ <ol>
+ <li><strong>Name:</strong> {username}</li>
+ <li>
+ <strong>Point of Contact Email (POC):</strong>
+ {poc_email}
+ </li>
+ <li>
+ <strong>Legal Business Name:</strong>
+ {legal_business_name}
+ </li>
+ <li>
+ <strong>Business Location:</strong>
+ {business_location}
+ </li>
+ <li>
+ <strong>Business Website:</strong>
+ {business_website}
+ </li>
+ </ol>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 15px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: start">
+ Regards,<br />
+ Hyperswitch Dashboard Team
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 50px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ font-size: 12px;
+ line-height: 1rem;
+ font-weight: 400;
+ color: #111326b2;
+ "
+ >
+ Follow us on
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="https://github.com/juspay/hyperswitch"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Github.png"
+ alt="Github"
+ height="15"
+ />
+ </a>
+ <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <img
+ src="https://app.hyperswitch.io/email-assets/Twitter.png"
+ alt="Twitter"
+ height="15"
+ />
+ </a>
+ <a
+ href="https://www.linkedin.com/company/hyperswitch/"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png"
+ alt="LinkedIn"
+ height="15"
+ />
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ </table>
+ </div>
+ </body>
+</html>
diff --git a/crates/router/src/services/email/assets/invite.html b/crates/router/src/services/email/assets/invite.html
index 307ec6cead8..7c7beb317fb 100644
--- a/crates/router/src/services/email/assets/invite.html
+++ b/crates/router/src/services/email/assets/invite.html
@@ -1,243 +1,225 @@
-<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
-<title>Welcome to HyperSwitch!</title>
-
-<body style="background-color: #ececec">
- <style>
- .apple-footer a {{
- text-decoration: none !important;
- color: #999 !important;
- border: none !important;
- }}
-
- .apple-email a {{
- text-decoration: none !important;
- color: #448bff !important;
- border: none !important;
- }}
- </style>
- <div id="wrapper" style="
- background-color: none;
- margin: 0 auto;
- text-align: center;
- width: 60%;
- -premailer-height: 200;
- ">
- <table align="center" class="main-table" style="
- -premailer-cellpadding: 0;
- -premailer-cellspacing: 0;
- background-color: #fff;
- border: 0;
- border-top: 5px solid #0165ef;
- margin: 0 auto;
- mso-table-lspace: 0;
- mso-table-rspace: 0;
- padding: 0 40;
- text-align: center;
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+ <title>Invite User</title>
+ </head>
+ <body
+ style="
+ background-color: #f8f9fb;
+ height: 100%;
+ font-family: Arial, Helvetica, sans-serif;
+ "
+ >
+ <div
+ style="
width: 100%;
- " bgcolor="#ffffff" cellpadding="0" cellspacing="0">
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="75" width="100%"></td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="25" width="100%"></td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="50" width="100%"></td>
- </tr>
- <tr>
- <td class="headline" style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 30px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- " align="center">
- Welcome to HyperSwitch!
+ margin: auto;
+ text-align: center;
+ background-color: #f8f9fb;
+ "
+ >
+ <table style="text-align: center; width: 100%">
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: center">
+ <table
+ style="
+ background-color: #ffffff;
+ text-align: center;
+ max-width: 55%;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ <tr>
+ <td>
+ <table style="width: 100%">
+ <tr>
+ <td style="text-align: center">
+ <img
+ src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png"
+ alt="Hyperswitch"
+ style="
+ text-align: center;
+ height: 1.3rem;
+ width: auto;
+ "
+ />
+ </td>
+ </tr>
+ </table>
</td>
- </tr>
- <tr>
- <td class="spacer-sm" style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- " width="100%"></td>
- </tr>
- <tr>
- <td class="copy" style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- " 20px!important; align="center">
- <br />
- Hi {username}<br />
- </td>
- </tr>
- <tr>
- <td class="spacer-sm" style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- " width="100%"></td>
- </tr>
- <tr>
- <td class="copy" style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- " 20px!important; align="center">
- <br />
- You have received this email because your administrator has invited you as a new user on
- Hyperswitch.
- <br />
+ </tr>
+ <tr>
+ <td style="height: 40px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ font-size: 2.02rem;
+ font-weight: 600;
+ line-height: 2.5rem;
+ color: #111326;
+ min-width: 550px;
+ "
+ >
+ Welcome to Hyperswitch!
</td>
- </tr>
- <tr>
- <td class="spacer-sm" style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- " width="100%"></td>
- </tr>
- <tr>
- <td class="copy" style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- " 20px!important; align="center">
- <br />
- <b>To get started, click on the button below. </b>
+ </tr>
+ <tr>
+ <td style="height: 10px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ width: 50%;
+ font-size: 1.02rem;
+ font-weight: 400;
+ line-height: 1.4rem;
+ min-width: 300px;
+ "
+ >
+ <table
+ style="
+ width: 50%;
+ min-width: 440px;
+ text-align: center;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td>
+ Hi {username}, you have received this email because your
+ administrator has invited you as a new user on
+ Hyperswitch.
+ </td>
+ </tr>
+ </table>
</td>
- </tr>
- <tr>
- <td class="spacer-sm" style="
- -premailer-height: 20;
- -premailer-width: 100%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- " height="20" width="100%"></td>
- </tr>
- <tr>
+ </tr>
+ <tr>
+ <td style="height: 30px"></td>
+ </tr>
+ <tr>
<td>
- <table align="center">
- <tr>
- <td align="center" width="160" height="40" class="button" style="
- background-color: #0165ef;
- border-radius: 2.5px;
- display: block;
- ">
- <a href="{link}" style="
- width: 100%;
- display: inline-block;
- text-decoration: none;
- font-weight: medium;
- color: #fff;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 40px;
- ">Click here to Join</a>
- </td>
- </tr>
- </table>
+ <a
+ href="{link}"
+ style="
+ text-decoration: none;
+ border: none;
+ border-radius: 64px;
+ font-size: 1.02rem;
+ color: #ffffff;
+ font-weight: 500;
+ line-height: 1.5rem;
+ width: 50%;
+ padding: 0.9rem 4rem;
+ background: #0070ff;
+ min-width: 18rem;
+ max-width: 25rem;
+ cursor: pointer;
+ "
+ >
+ Click here to join
+ </a>
</td>
- </tr>
- <tr>
- <td class="copy" style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- " 20px!important; align="center">
- <br />
- If the link has already expired, you can request a new link from your administrator or reach out to
- your internal support for more assistance.<br />
+ </tr>
+ <tr>
+ <td style="height: 30px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ width: 50%;
+ font-size: 1.02rem;
+ font-weight: 400;
+ line-height: 1.4rem;
+ min-width: 300px;
+ "
+ >
+ <table
+ style="
+ width: 50%;
+ min-width: 500px;
+ text-align: center;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td>
+ If the link has already expired, you can request a new
+ link from your administrator or reach out to your
+ internal support for more assistance.
+ </td>
+ </tr>
+ </table>
</td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="75" width="100%"></td>
- </tr>
- <tr>
- <td class="headline" style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 18px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- " align="center">
- Thanks,<br />
- Team Hyperswitch
+ </tr>
+ <tr>
+ <td style="height: 50px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ font-size: 12px;
+ line-height: 1rem;
+ font-weight: 400;
+ color: #111326b2;
+ "
+ >
+ Follow us on
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="https://github.com/juspay/hyperswitch"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Github.png"
+ alt="Github"
+ height="15"
+ />
+ </a>
+ <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <img
+ src="https://app.hyperswitch.io/email-assets/Twitter.png"
+ alt="Twitter"
+ height="15"
+ />
+ </a>
+ <a
+ href="https://www.linkedin.com/company/hyperswitch/"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png"
+ alt="LinkedIn"
+ height="15"
+ />
+ </a>
</td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="75" width="100%"></td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="75" width="100%"></td>
- </tr>
- </table>
+ </tr>
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ </table>
</div>
-</body>
+ </body>
+</html>
diff --git a/crates/router/src/services/email/assets/magic_link.html b/crates/router/src/services/email/assets/magic_link.html
index 643b6e23063..27f0b9816ef 100644
--- a/crates/router/src/services/email/assets/magic_link.html
+++ b/crates/router/src/services/email/assets/magic_link.html
@@ -1,256 +1,224 @@
-<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
-<title>Login to Hyperswitch</title>
-<body style="background-color: #ececec">
- <style>
- .apple-footer a {{
- text-decoration: none !important;
- color: #999 !important;
- border: none !important;
- }}
- .apple-email a {{
- text-decoration: none !important;
- color: #448bff !important;
- border: none !important;
- }}
- </style>
- <div
- id="wrapper"
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+ <title>Login to Hyperswitch</title>
+ </head>
+ <body
style="
- background-color: none;
- margin: 0 auto;
- text-align: center;
- width: 60%;
- -premailer-height: 200;
+ background-color: #f8f9fb;
+ height: 100%;
+ font-family: Arial, Helvetica, sans-serif;
"
>
- <table
- align="center"
- class="main-table"
+ <div
style="
- -premailer-cellpadding: 0;
- -premailer-cellspacing: 0;
- background-color: #fff;
- border: 0;
- border-top: 5px solid #0165ef;
- margin: 0 auto;
- mso-table-lspace: 0;
- mso-table-rspace: 0;
- padding: 0 40px;
- text-align: center;
width: 100%;
+ margin: auto;
+ text-align: center;
+ background-color: #f8f9fb;
"
- bgcolor="#ffffff"
- cellpadding="0"
- cellspacing="0"
>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="25"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="50"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="headline"
- style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 30px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- "
- align="center"
- >
- Welcome to Hyperswitch!
- <p style="font-size: 18px">Dear {user_name},</p>
- <span style="font-size: 18px">
- We are thrilled to welcome you into our community!
- </span>
- </td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="copy"
- style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- "
- 20px!important;
- align="center"
- >
- <br />
- Simply click on the link below, and you'll be granted instant access
- to your Hyperswitch account. Note that this link expires in 24 hours
- and can only be used once.<br />
- </td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 100%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- height="20"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td>
- <table align="center">
- <tr>
- <td
- align="center"
- width="160"
- height="40"
- class="button"
- style="
- background-color: #0165ef;
- border-radius: 2.5px;
- display: block;
- "
- >
- <a
- href="{link}"
+ <table style="text-align: center; width: 100%">
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: center">
+ <table
+ style="
+ background-color: #ffffff;
+ text-align: center;
+ max-width: 55%;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ <tr>
+ <td>
+ <table style="width: 100%">
+ <tr>
+ <td style="text-align: center">
+ <img
+ src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png"
+ alt="Hyperswitch"
+ style="
+ text-align: center;
+ height: 1.3rem;
+ width: auto;
+ "
+ />
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 40px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ font-size: 2.02rem;
+ font-weight: 600;
+ line-height: 2.5rem;
+ color: #111326;
+ min-width: 550px;
+ "
+ >
+ Welcome to Hyperswitch!
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 10px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ width: 50%;
+ font-size: 1.02rem;
+ font-weight: 400;
+ line-height: 1.4rem;
+ min-width: 300px;
+ "
+ >
+ <table
+ style="
+ width: 50%;
+ min-width: 350px;
+ text-align: center;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td>
+ Dear {username}, we are thrilled to welcome you into our
+ community!
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 30px"></td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="{link}"
+ style="
+ text-decoration: none;
+ border: none;
+ border-radius: 64px;
+ font-size: 1.02rem;
+ color: #ffffff;
+ font-weight: 500;
+ line-height: 1.5rem;
+ width: 50%;
+ padding: 0.9rem 3.5rem;
+ background: #0070ff;
+ min-width: 18rem;
+ max-width: 25rem;
+ cursor: pointer;
+ "
+ >
+ Unlock Hyperswitch
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 30px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ width: 50%;
+ font-size: 1.02rem;
+ font-weight: 400;
+ line-height: 1.4rem;
+ min-width: 300px;
+ "
+ >
+ <table
+ style="
+ width: 50%;
+ min-width: 500px;
+ text-align: center;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td>
+ This link provides instant access to Hyperswitch
+ account. It will expire in 24 hours and can only be used
+ once.
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 50px"></td>
+ </tr>
+ <tr>
+ <td
style="
- width: 100%;
- display: inline-block;
- text-decoration: none;
- font-weight: medium;
- color: #fff;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 40px;
+ font-size: 12px;
+ line-height: 1rem;
+ font-weight: 400;
+ color: #111326b2;
"
- >Unlock Hyperswitch</a
>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="headline"
- style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 18px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- "
- align="center"
- >
- Thanks,<br />
- Team Hyperswitch
- </td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- </table>
- </div>
-</body>
+ Follow us on
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="https://github.com/juspay/hyperswitch"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Github.png"
+ alt="Github"
+ height="15"
+ />
+ </a>
+ <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <img
+ src="https://app.hyperswitch.io/email-assets/Twitter.png"
+ alt="Twitter"
+ height="15"
+ />
+ </a>
+ <a
+ href="https://www.linkedin.com/company/hyperswitch/"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png"
+ alt="LinkedIn"
+ height="15"
+ />
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ </table>
+ </div>
+ </body>
+</html>
diff --git a/crates/router/src/services/email/assets/recon_activation.html b/crates/router/src/services/email/assets/recon_activation.html
index 7feffacb09d..53ee8386380 100644
--- a/crates/router/src/services/email/assets/recon_activation.html
+++ b/crates/router/src/services/email/assets/recon_activation.html
@@ -1,309 +1,197 @@
-<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
-<title>Access Granted to HyperSwitch Recon Dashboard!</title>
-
-<body style="background-color: #ececec">
- <style>
- <style>
- .apple-footer a {{
- text-decoration: none !important;
- color: #999 !important;
- border: none !important;
- }}
-
- .apple-email a {{
- text-decoration: none !important;
- color: #448bff !important;
- border: none !important;
- }}
- </style>
- </style>
- <div
- id="wrapper"
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+ <title>Access Granted to Hyperswitch Recon Dashboard!</title>
+ </head>
+ <body
style="
- background-color: none;
- margin: 0 auto;
- text-align: center;
- width: 60%;
- -premailer-height: 200;
+ background-color: #f8f9fb;
+ height: 100%;
+ font-family: Arial, Helvetica, sans-serif;
"
>
- <table
- align="center"
- class="main-table"
+ <div
style="
- -premailer-cellpadding: 0;
- -premailer-cellspacing: 0;
- background-color: #fff;
- border: 0;
- border-top: 5px solid #0165ef;
- margin: 0 auto;
- mso-table-lspace: 0;
- mso-table-rspace: 0;
- padding: 0 40;
- text-align: center;
width: 100%;
+ margin: auto;
+ text-align: center;
+ background-color: #f8f9fb;
"
- bgcolor="#ffffff"
- cellpadding="0"
- cellspacing="0"
>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="25"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="50"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="headline"
- style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 30px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- "
- align="center"
- >
- Access Granted to HyperSwitch Recon Dashboard!
- </td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="copy"
- style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: left;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- "
- 20px!important;
- align="left"
- >
- <br />
- Dear {username}<br />
- </td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="copy"
- style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: left;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- "
- 20px!important;
- align="left"
- >
- <br />
- We are pleased to inform you that your Reconciliation access request
- has been approved. As a result, you now have authorized access to the
- Recon dashboard, allowing you to test its functionality and experience
- its benefits firsthand.
- <br />
- </td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="copy"
- style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: left;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- "
- 20px!important;
- align="left"
- >
- <br />
- <b>To access the Recon dashboard, please follow these steps </b>
- </td>
- </tr>
- <tr>
- <td
- class="copy"
- style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: left;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- "
- 20px!important;
- align="left"
- >
- <br />
- <ol type="1">
- <li>
- Visit our website at
- <a href="https://app.hyperswitch.io/">Hyperswitch Dashboard</a>.
- </li>
- <li>Click on the "Login" button.</li>
- <li>Enter your login credentials to log in.</li>
- <li>
- Once logged in, you will have full access to the Recon dashboard,
- where you can explore its comprehensive features.
- </li>
- </ol>
- Should you have any inquiries or require any form of assistance,
- please do not hesitate to reach out to our team on
- <a href="https://hyperswitch-io.slack.com/ssb/redirect">Slack </a>,
- and we will be more than willing to assist you promptly. <br /><br />
- Wishing you a seamless and successful experience as you explore the
- capabilities of Hyperswitch.<br />
- </td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="headline"
- style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 18px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- "
- align="center"
- >
- Thanks,<br />
- Team Hyperswitch
- </td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- </table>
- </div>
-</body>
\ No newline at end of file
+ <table style="text-align: center; width: 100%">
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: center">
+ <table
+ style="
+ background-color: #ffffff;
+ text-align: center;
+ max-width: 55%;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td style="height: 15px"></td>
+ </tr>
+ <tr>
+ <td>
+ <table style="width: 100%">
+ <tr>
+ <td style="text-align: center">
+ <img
+ src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png"
+ alt="Hyperswitch"
+ style="
+ text-align: center;
+ height: 1.3rem;
+ width: auto;
+ "
+ />
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 40px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ font-size: 1rem;
+ font-weight: 400;
+ line-height: 1.5rem;
+ min-width: 450px;
+ "
+ >
+ <table
+ style="
+ width: 90%;
+ min-width: 350px;
+ text-align: start;
+ margin: auto;
+ padding: 0 10px;
+ "
+ >
+ <tr>
+ <td
+ style="
+ font-size: 2rem;
+ font-weight: 600;
+ line-height: 2.5rem;
+ color: #111326;
+ min-width: 500px;
+ text-align: center;
+ "
+ >
+ Access Granted to Hyperswitch Recon Dashboard!
+ </td>
+ </tr>
+ <tr>
+ <td style="text-align: start; font-size: 0.95rem; padding: 0 10px">
+ <p>Dear {username}</p>
+ <p>
+ We are pleased to inform you that your Reconciliation access request
+ has been approved. You now have authorized access to the
+ Recon dashboard, allowing you to test its functionality and experience
+ its benefits firsthand.
+ </p>
+ <p>
+ To access the Recon dashboard, please follow these steps:
+ </p>
+ <ol type="1">
+ <li>
+ Visit our website at
+ <a href="https://app.hyperswitch.io/">Hyperswitch Dashboard</a>.
+ </li>
+ <li>Click on the "Login" button.</li>
+ <li>Enter your login credentials.</li>
+ <li>
+ Once logged in, you will have full access to the Recon dashboard,
+ where you can explore its comprehensive features.
+ </li>
+ </ol>
+ <p>
+ For any inquiries or assistance,
+ please reach out to our team on
+ <a href="https://hyperswitch-io.slack.com/ssb/redirect">Slack </a>.
+ </p>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 15px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: start">
+ Thanks,</br>
+ Team Hyperswitch
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 50px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ font-size: 12px;
+ line-height: 1rem;
+ font-weight: 400;
+ color: #111326b2;
+ "
+ >
+ Follow us on
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="https://github.com/juspay/hyperswitch"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Github.png"
+ alt="Github"
+ height="15"
+ />
+ </a>
+ <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <img
+ src="https://app.hyperswitch.io/email-assets/Twitter.png"
+ alt="Twitter"
+ height="15"
+ />
+ </a>
+ <a
+ href="https://www.linkedin.com/company/hyperswitch/"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png"
+ alt="LinkedIn"
+ height="15"
+ />
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ </table>
+ </div>
+ </body>
+</html>
diff --git a/crates/router/src/services/email/assets/reset.html b/crates/router/src/services/email/assets/reset.html
index 98ddf8a7bd1..1aa6b1b50e9 100644
--- a/crates/router/src/services/email/assets/reset.html
+++ b/crates/router/src/services/email/assets/reset.html
@@ -1,229 +1,222 @@
-<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
-<title>Hyperswitch Merchant</title>
-
-<body style="background-color: #ececec">
- <style>
- .apple-footer a {{
- text-decoration: none !important;
- color: #999 !important;
- border: none !important;
- }}
-
- .apple-email a {{
- text-decoration: none !important;
- color: #448bff !important;
- border: none !important;
- }}
- </style>
- <div id="wrapper" style="
- background-color: none;
- margin: 0 auto;
- text-align: center;
- width: 60%;
- -premailer-height: 200;
- ">
- <table align="center" class="main-table" style="
- -premailer-cellpadding: 0;
- -premailer-cellspacing: 0;
- background-color: #fff;
- border: 0;
- border-top: 5px solid #0165ef;
- margin: 0 auto;
- mso-table-lspace: 0;
- mso-table-rspace: 0;
- padding: 0 40;
- text-align: center;
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+ <title>Reset Password</title>
+ </head>
+ <body
+ style="
+ background-color: #f8f9fb;
+ height: 100%;
+ font-family: Arial, Helvetica, sans-serif;
+ "
+ >
+ <div
+ style="
width: 100%;
- " bgcolor="#ffffff" cellpadding="0" cellspacing="0">
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="75" width="100%"></td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="25" width="100%"></td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="50" width="100%"></td>
- </tr>
- <tr>
- <td class="headline" style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 30px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- " align="center">
- Reset Your Password
- </td>
- </tr>
- <tr>
- <td class="spacer-sm" style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- " width="100%"></td>
- </tr>
- <tr>
- <td class="copy" style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- " 20px!important; align="center">
- <br />
- Hey {username}<br />
- </td>
- </tr>
- <tr>
- <td class="spacer-sm" style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- " width="100%"></td>
- </tr>
- <tr>
- <td class="copy" style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- " 20px!important; align="center">
- <br />
- We have received a request to reset your password associated with
- <br />
- <span style="font-weight: bold"> username : </span>
- {username}<br />
- </td>
- </tr>
- <tr>
- <td class="spacer-sm" style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- " width="100%"></td>
- </tr>
- <tr>
- <td class="copy" style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- " 20px!important; align="center">
- <br />
- Click on the below button to reset your password. <br />
- </td>
- </tr>
- <tr>
- <td class="spacer-sm" style="
- -premailer-height: 20;
- -premailer-width: 100%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- " height="20" width="100%"></td>
- </tr>
- <tr>
- <td>
- <table align="center">
- <tr>
- <td align="center" width="160" height="40" class="button" style="
- background-color: #0165ef;
- border-radius: 2.5px;
- display: block;
- ">
- <a href="{link}" style="
- width: 100%;
- display: inline-block;
- text-decoration: none;
- font-weight: medium;
- color: #fff;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 40px;
- ">Reset Password</a>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="75" width="100%"></td>
- </tr>
- <tr>
- <td class="headline" style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 18px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- " align="center">
- Thanks,<br />
- Team Hyperswitch
- </td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="75" width="100%"></td>
- </tr>
- <tr>
- <td class="spacer-lg" style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- " height="75" width="100%"></td>
- </tr>
- </table>
- </div>
-</body>
+ margin: auto;
+ text-align: center;
+ background-color: #f8f9fb;
+ "
+ >
+ <table style="text-align: center; width: 100%">
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: center">
+ <table
+ style="
+ background-color: #ffffff;
+ text-align: center;
+ max-width: 55%;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ <tr>
+ <td>
+ <table style="width: 100%">
+ <tr>
+ <td style="text-align: center">
+ <img
+ src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png"
+ alt="Hyperswitch"
+ style="
+ text-align: center;
+ height: 1.3rem;
+ width: auto;
+ "
+ />
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 40px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ font-size: 2.02rem;
+ font-weight: 600;
+ line-height: 2.5rem;
+ color: #111326;
+ min-width: 550px;
+ "
+ >
+ Reset password!
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 10px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ width: 50%;
+ font-size: 1.02rem;
+ font-weight: 400;
+ line-height: 1.4rem;
+ min-width: 300px;
+ "
+ >
+ <table
+ style="
+ width: 50%;
+ min-width: 450px;
+ text-align: center;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td>
+ We have received a request to reset your password
+ associated with
+ <span style="font-weight: bold"> username : </span>
+ {username}
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 10px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ width: 50%;
+ font-size: 1.02rem;
+ font-weight: 400;
+ line-height: 1.4rem;
+ min-width: 300px;
+ "
+ >
+ <table
+ style="
+ width: 50%;
+ min-width: 370px;
+ text-align: center;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td>Click on the below button to reset your password.</td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 30px"></td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="{link}"
+ style="
+ text-decoration: none;
+ border: none;
+ border-radius: 64px;
+ font-size: 1.03rem;
+ color: #ffffff;
+ font-weight: 500;
+ line-height: 1.5rem;
+ width: 50%;
+ padding: 0.9rem 4rem;
+ background: #0070ff;
+ min-width: 18rem;
+ max-width: 25rem;
+ cursor: pointer;
+ "
+ >
+ Reset Password
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 70px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ font-size: 12px;
+ line-height: 1rem;
+ font-weight: 400;
+ color: #111326b2;
+ "
+ >
+ Follow us on
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="https://github.com/juspay/hyperswitch"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Github.png"
+ alt="Github"
+ height="15"
+ />
+ </a>
+ <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <img
+ src="https://app.hyperswitch.io/email-assets/Twitter.png"
+ alt="Twitter"
+ height="15"
+ />
+ </a>
+ <a
+ href="https://www.linkedin.com/company/hyperswitch/"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png"
+ alt="LinkedIn"
+ height="15"
+ />
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ </table>
+ </div>
+ </body>
+</html>
diff --git a/crates/router/src/services/email/assets/verify.html b/crates/router/src/services/email/assets/verify.html
index 47d0e3b5c6d..7b56b79abdf 100644
--- a/crates/router/src/services/email/assets/verify.html
+++ b/crates/router/src/services/email/assets/verify.html
@@ -1,253 +1,190 @@
-<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
-<title>Hyperswitch Merchant</title>
-<body style="background-color: #ececec">
- <style>
- .apple-footer a {{
- text-decoration: none !important;
- color: #999 !important;
- border: none !important;
- }}
- .apple-email a {{
- text-decoration: none !important;
- color: #448bff !important;
- border: none !important;
- }}
- </style>
- <div
- id="wrapper"
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta http-equiv="X-UA-Compatible" content="ie=edge" />
+ <title>Verify Email</title>
+ </head>
+ <body
style="
- background-color: none;
- margin: 0 auto;
- text-align: center;
- width: 60%;
- -premailer-height: 200;
+ background-color: #f8f9fb;
+ height: 100%;
+ font-family: Arial, Helvetica, sans-serif;
"
>
- <table
- align="center"
- class="main-table"
+ <div
style="
- -premailer-cellpadding: 0;
- -premailer-cellspacing: 0;
- background-color: #fff;
- border: 0;
- border-top: 5px solid #0165ef;
- margin: 0 auto;
- mso-table-lspace: 0;
- mso-table-rspace: 0;
- padding: 0 40;
- text-align: center;
width: 100%;
+ margin: auto;
+ text-align: center;
+ background-color: #f8f9fb;
"
- bgcolor="#ffffff"
- cellpadding="0"
- cellspacing="0"
>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="25"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="50"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="headline"
- style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 30px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- "
- align="center"
- >
- Thanks for signing up!<br /><span style="font-size: 18px"
- >We need a confirmation of your email address to complete your
- registration.</span
- >
- </td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 80%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="copy"
- style="
- color: #666;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 20px;
- margin-top: 20px;
- padding: 0;
- "
- 20px!important;
- align="center"
- >
- <br />
- Click below to confirm your email address. <br />
- </td>
- </tr>
- <tr>
- <td
- class="spacer-sm"
- style="
- -premailer-height: 20;
- -premailer-width: 100%;
- line-height: 10px;
- margin: 0 auto;
- padding: 0;
- "
- height="20"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td>
- <table align="center">
- <tr>
- <td
- align="center"
- width="160"
- height="40"
- class="button"
- style="
- background-color: #0165ef;
- border-radius: 2.5px;
- display: block;
- "
- >
- <a
- href="{link}"
+ <table style="text-align: center; width: 100%">
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ <tr>
+ <td style="text-align: center">
+ <table
+ style="
+ background-color: #ffffff;
+ text-align: center;
+ min-width: 55%;
+ margin: auto;
+ padding: 0 13px;
+ "
+ >
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ <tr>
+ <td>
+ <table style="width: 100%">
+ <tr>
+ <td style="text-align: center">
+ <img
+ src="https://app.hyperswitch.io/email-assets/HyperswitchLogo.png"
+ alt="Hyperswitch"
+ style="
+ text-align: center;
+ height: 1.3rem;
+ width: auto;
+ "
+ />
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 40px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ font-size: 2.01rem;
+ font-weight: 600;
+ line-height: 2.5rem;
+ color: #111326;
+ min-width: 500px;
+ "
+ >
+ Thanks for signing up with Hyperswitch!
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 10px"></td>
+ </tr>
+ <tr>
+ <td
+ style="
+ color: #666666;
+ font-size: 1.02rem;
+ font-weight: 400;
+ line-height: 1.4rem;
+ min-width: 450px;
+ "
+ >
+ <table
+ style="
+ width: 50%;
+ min-width: 350px;
+ text-align: center;
+ margin: auto;
+ "
+ >
+ <tr>
+ <td>
+ Confirm your email address to complete your registration
+ by clicking the button below.
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 30px"></td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="{link}"
+ style="
+ text-decoration: none;
+ border: none;
+ border-radius: 64px;
+ font-size: 1.03rem;
+ color: #ffffff;
+ font-weight: 500;
+ line-height: 1.5rem;
+ width: 55%;
+ padding: 1rem 3rem;
+ background: #0070ff;
+ min-width: 18rem;
+ "
+ >
+ Confirm your email address
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 70px"></td>
+ </tr>
+ <tr>
+ <td
style="
- width: 100%;
- display: inline-block;
- text-decoration: none;
- font-weight: medium;
- color: #fff;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 14px;
- text-align: center;
- line-height: 40px;
+ font-size: 12px;
+ line-height: 1rem;
+ font-weight: 400;
+ color: #111326b2;
"
- >Verify Email Now</a
>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="headline"
- style="
- color: #444;
- font-family: Roboto, Helvetica, Arial, san-serif;
- font-size: 18px;
- font-weight: 100;
- line-height: 36px;
- margin: 0 auto;
- padding: 0;
- text-align: center;
- "
- align="center"
- >
- Thanks,<br />
- Team Hyperswitch
- </td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- <tr>
- <td
- class="spacer-lg"
- style="
- -premailer-height: 75;
- -premailer-width: 100%;
- line-height: 30px;
- margin: 0 auto;
- padding: 0;
- "
- height="75"
- width="100%"
- ></td>
- </tr>
- </table>
- </div>
-</body>
+ Follow us on
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <a
+ href="https://github.com/juspay/hyperswitch"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Github.png"
+ alt="Github"
+ height="15"
+ />
+ </a>
+ <a href="https://x.com/hyperswitchio?s=21" target="_blank">
+ <img
+ src="https://app.hyperswitch.io/email-assets/Twitter.png"
+ alt="Twitter"
+ height="15"
+ />
+ </a>
+ <a
+ href="https://www.linkedin.com/company/hyperswitch/"
+ target="_blank"
+ >
+ <img
+ src="https://app.hyperswitch.io/email-assets/Linkedin-Dark.png"
+ alt="LinkedIn"
+ height="15"
+ />
+ </a>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 20px"></td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td style="height: 6px"></td>
+ </tr>
+ </table>
+ </div>
+ </body>
+</html>
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index ee51d976b40..47da21aec98 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -76,7 +76,7 @@ pub mod html {
EmailBody::MagicLink { link, user_name } => {
format!(
include_str!("assets/magic_link.html"),
- user_name = user_name,
+ username = user_name,
link = link
)
}
|
2024-05-06T12:17:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Updated the HTML templates to new designs in backend
- Look at the below screenshots
- Old



- New











### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Currently used email templates were following Juspay old email structure, modified them to the new updated designs
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Tested using AWS SES email service & Postdrop, attached the screenshots
Please find below curls for same :
curl --location 'http://localhost:8080/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "gitanjli524@gmail.com"
}'
curl --location 'http://localhost:8080/user/user/invite_multiple?is_token_only=true' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGMyMjUyMTktZGVjNC00M2VlLTgyOTktMTBjMDRmYzkxYWYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA2ODY5OTYzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxNjk4MTMwNSwib3JnX2lkIjoib3JnX2dMbEJuQzgwVTgxNzlVTnozdm5sIn0.JsZr4aSFm_2C8si9byvS02kIAaYvpNNF_xidZSRm1sU' \
--header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGMyMjUyMTktZGVjNC00M2VlLTgyOTktMTBjMDRmYzkxYWYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA2ODY5OTYzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxNjk4MTMwNSwib3JnX2lkIjoib3JnX2dMbEJuQzgwVTgxNzlVTnozdm5sIn0.JsZr4aSFm_2C8si9byvS02kIAaYvpNNF_xidZSRm1sU' \
--data-raw '[
{
"email": "gitanjli524+098763@gmail.com",
"name": "25",
"role_id": "merchant_view_only"
}
]'
curl --location 'http://localhost:8080/user/forgot_password' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDM2NzMyMTUtYWU3NS00NGMzLWJiYzEtMGY3YmMxYmYwMjdmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzEyMjE0NDE5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxMjM4NzMyOSwib3JnX2lkIjoib3JnXzhLb2lWNmhrcG9KSGZNcllER1ZhIn0.H2G9oGp_JBoz3k5S7fMvaaJ9T0cG5VtUjM0hU3ltM3g' \
--data-raw '{
"email": "gitanjli524@gmail.com"
}'
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ccee1a9ce9e860bfa04e74329fb47fd73f010b23
|
- Tested using AWS SES email service & Postdrop, attached the screenshots
Please find below curls for same :
curl --location 'http://localhost:8080/user/connect_account' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "gitanjli524@gmail.com"
}'
curl --location 'http://localhost:8080/user/user/invite_multiple?is_token_only=true' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGMyMjUyMTktZGVjNC00M2VlLTgyOTktMTBjMDRmYzkxYWYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA2ODY5OTYzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxNjk4MTMwNSwib3JnX2lkIjoib3JnX2dMbEJuQzgwVTgxNzlVTnozdm5sIn0.JsZr4aSFm_2C8si9byvS02kIAaYvpNNF_xidZSRm1sU' \
--header 'Cookie: login_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGMyMjUyMTktZGVjNC00M2VlLTgyOTktMTBjMDRmYzkxYWYzIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA2ODY5OTYzIiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxNjk4MTMwNSwib3JnX2lkIjoib3JnX2dMbEJuQzgwVTgxNzlVTnozdm5sIn0.JsZr4aSFm_2C8si9byvS02kIAaYvpNNF_xidZSRm1sU' \
--data-raw '[
{
"email": "gitanjli524+098763@gmail.com",
"name": "25",
"role_id": "merchant_view_only"
}
]'
curl --location 'http://localhost:8080/user/forgot_password' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZDM2NzMyMTUtYWU3NS00NGMzLWJiYzEtMGY3YmMxYmYwMjdmIiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzEyMjE0NDE5Iiwicm9sZV9pZCI6Im9yZ19hZG1pbiIsImV4cCI6MTcxMjM4NzMyOSwib3JnX2lkIjoib3JnXzhLb2lWNmhrcG9KSGZNcllER1ZhIn0.H2G9oGp_JBoz3k5S7fMvaaJ9T0cG5VtUjM0hU3ltM3g' \
--data-raw '{
"email": "gitanjli524@gmail.com"
}'
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4751
|
Bug: mask the email address being logged in the payment_method_list response logs
As of now the payment method list response logs contains the email address, this needs to be mased
<img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/4c219a49-13d3-4fa1-804a-21c215aa5675">
|
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index d26a2deac18..d63d2b085b6 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -531,7 +531,8 @@ pub struct RequiredFieldInfo {
#[schema(value_type = FieldType)]
pub field_type: api_enums::FieldType,
- pub value: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub value: Option<masking::Secret<String>>,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 28121ecc801..5a12334c385 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2268,7 +2268,7 @@ pub async fn list_payment_methods(
.as_ref()
.and_then(|r| get_val(key.to_owned(), r));
if let Some(s) = temp {
- val.value = Some(s)
+ val.value = Some(s.into())
};
}
}
|
2024-05-23T13:36:58Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This pr is to mask the email address being logged in the payment method list response.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant account and mca
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_jviyQiUsX9uHI99VXUlF_secret_lHrA6q5GKvNvd5a0blUQ' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_df002da8beb74682ac3e8677a4b82217'
```
in the below log we can see the email address being logged (this is without the changes in this pr)
<img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0900eba7-09e0-4db7-95aa-bcd102cb49d6">
after the changes the email is being masked
<img width="1466" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67164e06-9953-4b17-83e1-3ccdad17d129">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
42e5ef155128f4df717e8fb101da6e6929659a0a
|
-> Create a merchant account and mca
-> Create a payment with confirm false
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_jviyQiUsX9uHI99VXUlF_secret_lHrA6q5GKvNvd5a0blUQ' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_df002da8beb74682ac3e8677a4b82217'
```
in the below log we can see the email address being logged (this is without the changes in this pr)
<img width="1448" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/0900eba7-09e0-4db7-95aa-bcd102cb49d6">
after the changes the email is being masked
<img width="1466" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67164e06-9953-4b17-83e1-3ccdad17d129">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4774
|
Bug: feat: Add config to force 2FA for users
Currently 2FA is skippable in all the environments.
We need to force 2FA in prod later at some point, so there should be config to which forces 2FA is enabled.
|
diff --git a/config/config.example.toml b/config/config.example.toml
index b0d3c743673..5aa45af85ac 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -395,6 +395,7 @@ password_validity_in_days = 90 # Number of days after which password shoul
two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside
totp_issuer_name = "Hyperswitch" # Name of the issuer for TOTP
base_url = "" # Base url used for user specific redirects and emails
+force_two_factor_auth = false # Whether to force two factor authentication for all users
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 780af87383f..b99577c7f06 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -138,6 +138,7 @@ password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch Integ"
base_url = "https://integ.hyperswitch.io"
+force_two_factor_auth = false
[frm]
enabled = true
@@ -394,4 +395,4 @@ connector_list = ""
card_networks = "Visa, AmericanExpress, Mastercard"
[network_tokenization_supported_connectors]
-connector_list = "cybersource"
\ No newline at end of file
+connector_list = "cybersource"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 430475b9e5c..5aaae800e32 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -145,6 +145,7 @@ password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch Production"
base_url = "https://live.hyperswitch.io"
+force_two_factor_auth = false
[frm]
enabled = false
@@ -408,4 +409,4 @@ connector_list = ""
card_networks = "Visa, AmericanExpress, Mastercard"
[network_tokenization_supported_connectors]
-connector_list = "cybersource"
\ No newline at end of file
+connector_list = "cybersource"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 99d4253aea3..d6868eb94b1 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -145,6 +145,7 @@ password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch Sandbox"
base_url = "https://app.hyperswitch.io"
+force_two_factor_auth = false
[frm]
enabled = true
diff --git a/config/development.toml b/config/development.toml
index cbc4573e555..18df92797bc 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -316,6 +316,7 @@ password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch Dev"
base_url = "http://localhost:8080"
+force_two_factor_auth = false
[bank_config.eps]
stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index cf07a1bf9be..760d6e370f7 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -56,6 +56,7 @@ password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch"
base_url = "http://localhost:8080"
+force_two_factor_auth = false
[locker]
host = ""
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 089089038b8..089426c68ba 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -211,6 +211,7 @@ pub struct TwoFactorAuthStatusResponseWithAttempts {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TwoFactorStatus {
pub status: Option<TwoFactorAuthStatusResponseWithAttempts>,
+ pub is_skippable: bool,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 61e026ae2c5..f675aad11a7 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -556,6 +556,7 @@ pub struct UserSettings {
pub two_factor_auth_expiry_in_secs: i64,
pub totp_issuer_name: String,
pub base_url: String,
+ pub force_two_factor_auth: bool,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 822c29b21d9..35b26926ed2 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1319,7 +1319,7 @@ pub async fn list_user_roles_details(
))
.await
.change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to construct proifle map")?
+ .attach_printable("Failed to construct profile map")?
.into_iter()
.map(|profile| (profile.get_id().to_owned(), profile.profile_name))
.collect::<HashMap<_, _>>();
@@ -1927,7 +1927,7 @@ pub async fn terminate_two_factor_auth(
.change_context(UserErrors::InternalServerError)?
.into();
- if !skip_two_factor_auth {
+ 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?
{
@@ -1997,9 +1997,12 @@ pub async fn check_two_factor_auth_status_with_attempts(
.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,
}));
};
@@ -2018,6 +2021,7 @@ pub async fn check_two_factor_auth_status_with_attempts(
totp,
recovery_code,
}),
+ is_skippable,
}))
}
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 11268e15e54..1e9f355a5e6 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -35,6 +35,7 @@ jwt_secret = "secret"
password_validity_in_days = 90
two_factor_auth_expiry_in_secs = 300
totp_issuer_name = "Hyperswitch"
+force_two_factor_auth = false
[locker]
host = ""
|
2024-10-30T08:44:07Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR will add force 2fa environment variable. When enabled it will force users to complete 2FA to access the control center.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
`config/config.example.toml`
`config/deployments/integration_test.toml`
`config/deployments/production.toml`
`config/deployments/sandbox.toml`
`config/development.toml`
`config/docker_compose.toml`
`loadtest/config/development.toml`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #4774.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. 2FA Status API
- `is_skippable` field is added in the response.
```
curl --location 'http://localhost:8080/user/2fa/v2' \
--header 'Authorization: JWT' \
```
```
{
"status": null,
"is_skippable": true
}
```
2. Terminate 2FA API
- This API will now not allow skip 2FA if the `force_two_factor_auth`
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \
--header 'Authorization: JWT' \
```
```
{
"error": {
"type": "invalid_request",
"message": "Two factor auth required",
"code": "UR_40"
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
19cf0f7437a8d16ee4da254d2a3e2659879be68c
|
1. 2FA Status API
- `is_skippable` field is added in the response.
```
curl --location 'http://localhost:8080/user/2fa/v2' \
--header 'Authorization: JWT' \
```
```
{
"status": null,
"is_skippable": true
}
```
2. Terminate 2FA API
- This API will now not allow skip 2FA if the `force_two_factor_auth`
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \
--header 'Authorization: JWT' \
```
```
{
"error": {
"type": "invalid_request",
"message": "Two factor auth required",
"code": "UR_40"
}
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4748
|
Bug: log and ignore the apple pay metadata parsing error while fetching apple pay retry connectors
For a merchant account there are be n number of connectors and its not mandatory that apple pay needs to be enabled for all of them. So while fetching apple pay retry connectors log the error if the apple pay metadata parsing fails. This is required as this will create unnecessary errors for the connectors that does not have the apple pay metadata enabled as for them apple pay metadata will be not there.
|
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index a6befa5269e..f760e907288 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3163,8 +3163,14 @@ where
routing_data.business_sub_label = choice.sub_label.clone();
}
+ #[cfg(feature = "retry")]
+ let should_do_retry =
+ retry::config_should_call_gsm(&*state.store, &merchant_account.merchant_id).await;
+
+ #[cfg(feature = "retry")]
if payment_data.payment_attempt.payment_method_type
== Some(storage_enums::PaymentMethodType::ApplePay)
+ && should_do_retry
{
let retryable_connector_data = helpers::get_apple_pay_retryable_connectors(
state,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 06c8c7f2c94..5611e536871 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3890,18 +3890,27 @@ pub fn validate_customer_access(
pub fn is_apple_pay_simplified_flow(
connector_metadata: Option<pii::SecretSerdeValue>,
+ connector_name: Option<&String>,
) -> CustomResult<bool, errors::ApiErrorResponse> {
- let apple_pay_metadata = get_applepay_metadata(connector_metadata)?;
-
- Ok(match apple_pay_metadata {
- api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
- apple_pay_combined_metadata,
- ) => match apple_pay_combined_metadata {
- api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => true,
- api_models::payments::ApplePayCombinedMetadata::Manual { .. } => false,
- },
- api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => false,
- })
+ 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 { .. }
+ )
+ )
+ ))
}
pub fn get_applepay_metadata(
@@ -3954,7 +3963,7 @@ where
field_name: "profile_id",
})?;
- let merchant_connector_account = get_merchant_connector_account(
+ let merchant_connector_account_type = get_merchant_connector_account(
&state,
merchant_account.merchant_id.as_str(),
payment_data.creds_identifier.to_owned(),
@@ -3963,15 +3972,19 @@ where
&decided_connector_data.connector_name.to_string(),
merchant_connector_id,
)
- .await?
- .get_metadata();
+ .await?;
- let connector_data_list = if is_apple_pay_simplified_flow(merchant_connector_account)? {
+ 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(
merchant_account.merchant_id.as_str(),
- true,
+ false,
key_store,
)
.await
@@ -3980,7 +3993,10 @@ where
let mut connector_data_list = vec![decided_connector_data.clone()];
for merchant_connector_account in merchant_connector_account_list {
- if is_apple_pay_simplified_flow(merchant_connector_account.metadata)? {
+ if is_apple_pay_simplified_flow(
+ merchant_connector_account.metadata,
+ Some(&merchant_connector_account.connector_name),
+ )? {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&merchant_connector_account.connector_name.to_string(),
|
2024-05-23T11:15:20Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
For a merchant account there are be n number of connectors and its not mandatory that apple pay needs to be enabled for all of them. So while fetching apple pay retry connectors log the error if the apple pay metadata parsing fails. This is required as this will create unnecessary errors for the connectors that does not have the apple pay metadata enabled as for them apple pay metadata will be not there.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant account
-> Enable gcm for the `merchant_id`
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "should_call_gsm_{merchant_id}",
"value": "true"
}'
```
-> Set the maximum retries count
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "max_auto_retries_enabled_{merchant_id}",
"value": "1"
}'
```
-> Create MCA for stripe and cybersource with apple pay simplified flow
metadata for simplified flow
```
"metadata": {
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
},
"google_pay": {
"merchant_info": {
"merchant_name": "Stripe"
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
]
}
}
}
```
-> Do a apple pay payment create with confirm false
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}
```
<img width="1007" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67deb74e-e0dd-4af3-b5d9-7298d65c3e01">
-> Do payment method list for merchant
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_V1VBfr3VW6MVXaFw01sT_secret_6bByPi9DrnPk0uv6vYJj' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_cc7a8a8132a840338323ac8f7f6860d0'
```
<img width="1059" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/38f97f9d-ff51-41dc-9a06-20137f2ead1a">
-> Confirm the above create payment with `payment_id` and payment_data
```
curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: api_key' \
--data '{
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}'
```
<img width="1045" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1b5c8cb4-43bf-42ea-a82f-9c6db940950b">
-> Apple pay retry connectors. In here I had configured apple pay simplified flow for stripe and rapyd. And apple pay manual flow for cybersource and adyen mca without apple pay enabled
<img width="1158" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/59e3a5ba-31f6-42f9-bb81-d388ced47e0e">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ae77373b4cac63979673fdac37c55986d954358e
|
-> Create a merchant account
-> Enable gcm for the `merchant_id`
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "should_call_gsm_{merchant_id}",
"value": "true"
}'
```
-> Set the maximum retries count
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "max_auto_retries_enabled_{merchant_id}",
"value": "1"
}'
```
-> Create MCA for stripe and cybersource with apple pay simplified flow
metadata for simplified flow
```
"metadata": {
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
},
"google_pay": {
"merchant_info": {
"merchant_name": "Stripe"
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
]
}
}
}
```
-> Do a apple pay payment create with confirm false
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}
```
<img width="1007" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67deb74e-e0dd-4af3-b5d9-7298d65c3e01">
-> Do payment method list for merchant
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_V1VBfr3VW6MVXaFw01sT_secret_6bByPi9DrnPk0uv6vYJj' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_cc7a8a8132a840338323ac8f7f6860d0'
```
<img width="1059" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/38f97f9d-ff51-41dc-9a06-20137f2ead1a">
-> Confirm the above create payment with `payment_id` and payment_data
```
curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: api_key' \
--data '{
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}'
```
<img width="1045" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1b5c8cb4-43bf-42ea-a82f-9c6db940950b">
-> Apple pay retry connectors. In here I had configured apple pay simplified flow for stripe and rapyd. And apple pay manual flow for cybersource and adyen mca without apple pay enabled
<img width="1158" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/59e3a5ba-31f6-42f9-bb81-d388ced47e0e">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4742
|
Bug: [BUG] Failing unit tests for routing and constraint graph
### Bug Description
Certain unit tests in the `euclid` and `kgraph_utils` crates are failing.
**euclid**
```
FAIL [ 0.032s] euclid frontend::dir::test::test_consistent_dir_key_naming
```
**kgraph_utils**
```
FAIL [ 0.037s] kgraph_utils mca::tests::test_debit_card_success_case
```
### Expected Behavior
All unit tests should pass.
### Actual Behavior
Some tests fail owing to being outdated or due to a code discrepancy.
### Steps To Reproduce
1. Clone the main branch
2. Run the unit tests for the `euclid` and `kgraph_utils` crates
### Context For The Bug
_No response_
### Environment
Local
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs
index bc16057fbb5..f2b9ab99049 100644
--- a/crates/euclid/src/frontend/dir.rs
+++ b/crates/euclid/src/frontend/dir.rs
@@ -809,6 +809,10 @@ mod test {
let mut key_names: FxHashMap<DirKeyKind, String> = FxHashMap::default();
for key in DirKeyKind::iter() {
+ if matches!(key, DirKeyKind::Connector) {
+ continue;
+ }
+
let json_str = if let DirKeyKind::MetaData = key {
r#""metadata""#.to_string()
} else {
diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs
index ed96cd9b545..b32c8c23bd9 100644
--- a/crates/kgraph_utils/src/mca.rs
+++ b/crates/kgraph_utils/src/mca.rs
@@ -716,7 +716,6 @@ mod tests {
api_enums::CardNetwork::Mastercard,
]),
accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
- api_enums::Currency::USD,
api_enums::Currency::INR,
])),
accepted_countries: None,
@@ -734,7 +733,6 @@ mod tests {
]),
accepted_currencies: Some(AcceptedCurrencies::EnableOnly(vec![
api_enums::Currency::GBP,
- api_enums::Currency::PHP,
])),
accepted_countries: None,
minimum_amount: Some(10),
@@ -752,14 +750,6 @@ mod tests {
status: api_enums::ConnectorStatus::Inactive,
};
- let currency_country_flow_filter = kgraph_types::CurrencyCountryFlowFilter {
- currency: Some(HashSet::from([api_enums::Currency::INR])),
- country: Some(HashSet::from([api_enums::CountryAlpha2::IN])),
- not_available_flows: Some(kgraph_types::NotAvailableFlows {
- capture_method: Some(api_enums::CaptureMethod::Manual),
- }),
- };
-
let config_map = kgraph_types::CountryCurrencyFilter {
connector_configs: HashMap::from([(
api_enums::RoutableConnectors::Stripe,
@@ -768,13 +758,31 @@ mod tests {
kgraph_types::PaymentMethodFilterKey::PaymentMethodType(
api_enums::PaymentMethodType::Credit,
),
- currency_country_flow_filter.clone(),
+ kgraph_types::CurrencyCountryFlowFilter {
+ currency: Some(HashSet::from([
+ api_enums::Currency::INR,
+ api_enums::Currency::USD,
+ ])),
+ country: Some(HashSet::from([api_enums::CountryAlpha2::IN])),
+ not_available_flows: Some(kgraph_types::NotAvailableFlows {
+ capture_method: Some(api_enums::CaptureMethod::Manual),
+ }),
+ },
),
(
kgraph_types::PaymentMethodFilterKey::PaymentMethodType(
api_enums::PaymentMethodType::Debit,
),
- currency_country_flow_filter,
+ kgraph_types::CurrencyCountryFlowFilter {
+ currency: Some(HashSet::from([
+ api_enums::Currency::GBP,
+ api_enums::Currency::PHP,
+ ])),
+ country: Some(HashSet::from([api_enums::CountryAlpha2::IN])),
+ not_available_flows: Some(kgraph_types::NotAvailableFlows {
+ capture_method: Some(api_enums::CaptureMethod::Manual),
+ }),
+ },
),
])),
)]),
@@ -838,8 +846,8 @@ mod tests {
dirval!(Connector = Stripe),
dirval!(PaymentMethod = Card),
dirval!(CardType = Debit),
- dirval!(CardNetwork = DinersClub),
- dirval!(PaymentCurrency = GBP),
+ dirval!(CardNetwork = Maestro),
+ dirval!(PaymentCurrency = PHP),
dirval!(PaymentAmount = 100),
]),
&mut Memoization::new(),
|
2024-05-23T08:01:10Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR fixes a couple of failing unit tests in the `euclid` and `kgraph_utils` crates.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Running unit tests locally. API Tests not required
<img width="674" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/babeb68b-2e8c-4b9e-925c-08c6ff55a9a9">
<img width="762" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/a99b2bc7-57e2-45d6-a8af-754f0da52cbb">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ba624d049840f65fc21a5e578f8d4ba8543e1420
|
Running unit tests locally. API Tests not required
<img width="674" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/babeb68b-2e8c-4b9e-925c-08c6ff55a9a9">
<img width="762" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/a99b2bc7-57e2-45d6-a8af-754f0da52cbb">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4734
|
Bug: [BUG] Decrypt the card without having locker as a fallback
### Feature Description
Decrypt the card without having locker as a fallback
### Possible Implementation
Decrypt the card without having locker as a fallback
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 8dbef81b906..a3ed16def0c 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -3,7 +3,8 @@ use std::marker::PhantomData;
use api_models::{
admin::ExtendedCardInfoConfig,
enums::FrmSuggestion,
- payments::{AdditionalCardInfo, AdditionalPaymentData, ExtendedCardInfo},
+ payment_methods::PaymentMethodsData,
+ payments::{AdditionalPaymentData, ExtendedCardInfo},
};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt};
@@ -21,7 +22,6 @@ use crate::{
blocklist::utils as blocklist_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
- payment_methods::cards,
payments::{
self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress,
PaymentData,
@@ -34,7 +34,7 @@ use crate::{
types::{
self,
api::{self, ConnectorCallType, PaymentIdTypeExt},
- domain,
+ domain::{self, types::decrypt},
storage::{self, enums as storage_enums},
},
utils::{self, OptionExt},
@@ -1040,26 +1040,39 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
- let key = key_store.key.get_inner().peek();
+ let encode_additional_pm_to_value = if let Some(ref pm) = payment_data.payment_method_info {
+ let key = key_store.key.get_inner().peek();
- let card_detail_from_locker = payment_data
- .payment_method_info
- .as_ref()
- .async_map(|pm| async move {
- cards::get_card_details_without_locker_fallback(pm, key, state).await
+ let card_detail_from_locker: Option<api::CardDetailFromLocker> =
+ decrypt::<serde_json::Value, masking::WithType>(
+ pm.payment_method_data.clone(),
+ key,
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ .attach_printable("unable to decrypt card details")
+ .ok()
+ .flatten()
+ .map(|x| x.into_inner().expose())
+ .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok())
+ .and_then(|pmd| match pmd {
+ PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)),
+ _ => None,
+ });
+
+ card_detail_from_locker.and_then(|card_details| {
+ let additional_data = card_details.into();
+ let additional_data_payment =
+ AdditionalPaymentData::Card(Box::new(additional_data));
+ additional_data_payment
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode additional pm data")
+ .ok()
})
- .await
- .transpose()?;
-
- let additional_data: Option<AdditionalCardInfo> = card_detail_from_locker.map(From::from);
-
- let encode_additional_pm_to_value = additional_data
- .map(|additional_data| AdditionalPaymentData::Card(Box::new(additional_data)))
- .as_ref()
- .map(Encode::encode_to_value)
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to encode additional pm data")?;
+ } else {
+ None
+ };
let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();
let authentication_type = payment_data.payment_attempt.authentication_type;
|
2024-05-22T16:43:57Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
The token based MIT payments were throwing a 5xx , as this [PR](https://github.com/juspay/hyperswitch/pull/4711) called locker every time as a fallback while trying to decrypt the card . This PR fixes the failing token based MIT payments
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
-Create a MA and a MCA
- Create a off_session payment , with google pay token
- Create another recurring payment via google pay
>
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_QEGuyQGnDNOXysqCH4yETBv5kLrF9Nk0cktqhVcnxEutsoJQZkAlmeQ4rITJHTI5' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>
```
Confirm
curl --location 'http://localhost:8080/payments/pay_MmhKI2g6MjI22FZbi1jh/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_QEGuyQGnDNOXysqCH4yETBv5kLrF9Nk0cktqhVcnxEutsoJQZkAlmeQ4rITJHTI5' \
--data '{
"confirm": true,
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_token": "token_5rtAjgUaL0bLDjfj185V"
}'
```
> Response
```
{
"payment_id": "pay_MmhKI2g6MjI22FZbi1jh",
"merchant_id": "merchant_1716403278",
"status": "succeeded",
"amount": 6777,
"net_amount": 6777,
"amount_capturable": 0,
"amount_received": 6777,
"connector": "bankofamerica",
"client_secret": "pay_MmhKI2g6MjI22FZbi1jh_secret_GbiTtFazN61AKDLwJMMu",
"created": "2024-05-22T18:41:47.798Z",
"currency": "USD",
"customer_id": "new-c777",
"customer": {
"id": "new-c777",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": null,
"payment_token": "token_5rtAjgUaL0bLDjfj185V",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "google_pay",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7164033224736237803955",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_MmhKI2g6MjI22FZbi1jh_1",
"payment_link": null,
"profile_id": "pro_iBJ1GnZMmCPPTzJ0izXc",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_WTIH9V0jHkOxRG9L01ux",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T18:56:47.798Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_hrBVSNziVDNOzeGqvMCB",
"payment_method_status": "active",
"updated": "2024-05-22T18:42:03.520Z",
"frm_metadata": null
}
```
- For Cards
> Do a token based MIT will see the card_details in the response
```
Resposne
{
"payment_id": "pay_4ZRUltEq1k4Swzm1NX3V",
"merchant_id": "merchant_1716400925",
"status": "succeeded",
"amount": 6777,
"net_amount": 6777,
"amount_capturable": 0,
"amount_received": 6777,
"connector": "cybersource",
"client_secret": "pay_4ZRUltEq1k4Swzm1NX3V_secret_Xy2mkCxiynpb4QVvJ87P",
"created": "2024-05-22T18:05:27.351Z",
"currency": "USD",
"customer_id": "new-c777",
"customer": {
"id": "new-c777",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "11",
"card_exp_year": "2040",
"card_holder_name": "AKA",
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_7wYGRb2yHaxmRHew4Nwb",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7164013142446089903955",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_4ZRUltEq1k4Swzm1NX3V_1",
"payment_link": null,
"profile_id": "pro_YaIF6M1jA9UH6xnB0Att",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_JWZiq29SfXxoNTiFGlG8",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T18:20:27.351Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_ByLjjOGIQdbHriocx497",
"payment_method_status": "active",
"updated": "2024-05-22T18:08:35.227Z",
"frm_metadata": null
}
```
- For Cybersource wallts recurring payments
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>
```
Confirm
curl --location 'http://localhost:8080/payments/pay_6nyM2u8hRoS9YWDzSgqj/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \
--data '{
"confirm": true,
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_token": "token_qK3qo9EVuk5TE4sBb1v8"
}'
```
>
```
Response
{
"payment_id": "pay_6nyM2u8hRoS9YWDzSgqj",
"merchant_id": "merchant_1716404501",
"status": "succeeded",
"amount": 6777,
"net_amount": 6777,
"amount_capturable": 0,
"amount_received": 6777,
"connector": "cybersource",
"client_secret": "pay_6nyM2u8hRoS9YWDzSgqj_secret_DEYEPOXvjoWgvzVvCDKK",
"created": "2024-05-22T19:03:02.415Z",
"currency": "USD",
"customer_id": "new-c777",
"customer": {
"id": "new-c777",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": null,
"payment_token": "token_qK3qo9EVuk5TE4sBb1v8",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "google_pay",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7164045889206818003954",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_6nyM2u8hRoS9YWDzSgqj_1",
"payment_link": null,
"profile_id": "pro_NMDohQHyrqzAkUjBjDmB",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_JfI8xFhxTnL5q2bFhpUW",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T19:18:02.415Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka",
"payment_method_status": "active",
"updated": "2024-05-22T19:03:10.117Z",
"frm_metadata": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d942a31d60595d366977746be7215620da0ababd
|
-Create a MA and a MCA
- Create a off_session payment , with google pay token
- Create another recurring payment via google pay
>
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_QEGuyQGnDNOXysqCH4yETBv5kLrF9Nk0cktqhVcnxEutsoJQZkAlmeQ4rITJHTI5' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>
```
Confirm
curl --location 'http://localhost:8080/payments/pay_MmhKI2g6MjI22FZbi1jh/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_QEGuyQGnDNOXysqCH4yETBv5kLrF9Nk0cktqhVcnxEutsoJQZkAlmeQ4rITJHTI5' \
--data '{
"confirm": true,
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_token": "token_5rtAjgUaL0bLDjfj185V"
}'
```
> Response
```
{
"payment_id": "pay_MmhKI2g6MjI22FZbi1jh",
"merchant_id": "merchant_1716403278",
"status": "succeeded",
"amount": 6777,
"net_amount": 6777,
"amount_capturable": 0,
"amount_received": 6777,
"connector": "bankofamerica",
"client_secret": "pay_MmhKI2g6MjI22FZbi1jh_secret_GbiTtFazN61AKDLwJMMu",
"created": "2024-05-22T18:41:47.798Z",
"currency": "USD",
"customer_id": "new-c777",
"customer": {
"id": "new-c777",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": null,
"payment_token": "token_5rtAjgUaL0bLDjfj185V",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "google_pay",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7164033224736237803955",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_MmhKI2g6MjI22FZbi1jh_1",
"payment_link": null,
"profile_id": "pro_iBJ1GnZMmCPPTzJ0izXc",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_WTIH9V0jHkOxRG9L01ux",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T18:56:47.798Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_hrBVSNziVDNOzeGqvMCB",
"payment_method_status": "active",
"updated": "2024-05-22T18:42:03.520Z",
"frm_metadata": null
}
```
- For Cards
> Do a token based MIT will see the card_details in the response
```
Resposne
{
"payment_id": "pay_4ZRUltEq1k4Swzm1NX3V",
"merchant_id": "merchant_1716400925",
"status": "succeeded",
"amount": 6777,
"net_amount": 6777,
"amount_capturable": 0,
"amount_received": 6777,
"connector": "cybersource",
"client_secret": "pay_4ZRUltEq1k4Swzm1NX3V_secret_Xy2mkCxiynpb4QVvJ87P",
"created": "2024-05-22T18:05:27.351Z",
"currency": "USD",
"customer_id": "new-c777",
"customer": {
"id": "new-c777",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "11",
"card_exp_year": "2040",
"card_holder_name": "AKA",
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_7wYGRb2yHaxmRHew4Nwb",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7164013142446089903955",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_4ZRUltEq1k4Swzm1NX3V_1",
"payment_link": null,
"profile_id": "pro_YaIF6M1jA9UH6xnB0Att",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_JWZiq29SfXxoNTiFGlG8",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T18:20:27.351Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_ByLjjOGIQdbHriocx497",
"payment_method_status": "active",
"updated": "2024-05-22T18:08:35.227Z",
"frm_metadata": null
}
```
- For Cybersource wallts recurring payments
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>
```
Confirm
curl --location 'http://localhost:8080/payments/pay_6nyM2u8hRoS9YWDzSgqj/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \
--data '{
"confirm": true,
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_token": "token_qK3qo9EVuk5TE4sBb1v8"
}'
```
>
```
Response
{
"payment_id": "pay_6nyM2u8hRoS9YWDzSgqj",
"merchant_id": "merchant_1716404501",
"status": "succeeded",
"amount": 6777,
"net_amount": 6777,
"amount_capturable": 0,
"amount_received": 6777,
"connector": "cybersource",
"client_secret": "pay_6nyM2u8hRoS9YWDzSgqj_secret_DEYEPOXvjoWgvzVvCDKK",
"created": "2024-05-22T19:03:02.415Z",
"currency": "USD",
"customer_id": "new-c777",
"customer": {
"id": "new-c777",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": null,
"payment_token": "token_qK3qo9EVuk5TE4sBb1v8",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "google_pay",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7164045889206818003954",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_6nyM2u8hRoS9YWDzSgqj_1",
"payment_link": null,
"profile_id": "pro_NMDohQHyrqzAkUjBjDmB",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_JfI8xFhxTnL5q2bFhpUW",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T19:18:02.415Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka",
"payment_method_status": "active",
"updated": "2024-05-22T19:03:10.117Z",
"frm_metadata": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4733
|
Bug: [Refactor] Use recurring enabled flag to decide which payment method supports MIT
### Feature Description
Use recurring enabled flag to decide which payment method supports MIT
### Possible Implementation
Use recurring enabled flag to decide which payment method supports MIT
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rs
index bd24d12ec22..cc73bd7a532 100644
--- a/crates/diesel_models/src/query/merchant_connector_account.rs
+++ b/crates/diesel_models/src/query/merchant_connector_account.rs
@@ -124,7 +124,9 @@ impl MerchantConnectorAccount {
if get_disabled {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
- dsl::merchant_id.eq(merchant_id.to_owned()),
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::disabled.eq(true)),
None,
None,
Some(dsl::created_at.asc()),
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 657ad625045..28121ecc801 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3525,7 +3525,22 @@ pub async fn list_customer_payment_method(
)
.await
.attach_printable("unable to decrypt payment method billing address details")?;
-
+ let connector_mandate_details = pm
+ .connector_mandate_details
+ .clone()
+ .map(|val| {
+ val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference")
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
+ let mca_enabled = get_mca_status(
+ state,
+ &key_store,
+ &merchant_account.merchant_id,
+ connector_mandate_details,
+ )
+ .await?;
// Need validation for enabled payment method ,querying MCA
let pma = api::CustomerPaymentMethod {
payment_token: parent_payment_method_token.to_owned(),
@@ -3537,7 +3552,7 @@ pub async fn list_customer_payment_method(
card: payment_method_retrieval_context.card_details,
metadata: pm.metadata,
payment_method_issuer_code: pm.payment_method_issuer_code,
- recurring_enabled: false,
+ recurring_enabled: mca_enabled,
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
created: Some(pm.created_at),
@@ -3667,7 +3682,38 @@ pub async fn list_customer_payment_method(
Ok(services::ApplicationResponse::Json(response))
}
+pub async fn get_mca_status(
+ state: &routes::AppState,
+ key_store: &domain::MerchantKeyStore,
+ merchant_id: &str,
+ connector_mandate_details: Option<storage::PaymentsMandateReference>,
+) -> errors::RouterResult<bool> {
+ if let Some(connector_mandate_details) = connector_mandate_details {
+ let mcas = state
+ .store
+ .find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ merchant_id,
+ true,
+ key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: merchant_id.to_string(),
+ })?;
+ let mut mca_ids = HashSet::new();
+ for mca in mcas {
+ mca_ids.insert(mca.merchant_connector_id);
+ }
+
+ for mca_id in connector_mandate_details.keys() {
+ if !mca_ids.contains(mca_id) {
+ return Ok(true);
+ }
+ }
+ }
+ Ok(false)
+}
pub async fn decrypt_generic_data<T>(
data: Option<Encryption>,
key: &[u8],
|
2024-05-22T14:10:18Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
use recurring enabled flag in the lIst Customer Payment Method to decide which payment method supports MIT.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create a MA and a MCA with 2 connectors , cybersource and stripe
- Create a mandate payment with one card , lets say using stripe
- create a mandate payment with some pm, let's say wallet with the connector cybersource
- list the payment methods for the customer, the card which has mandate enabled will have the recurring field as true else false
> So in the below case have not disabled any mca and then you do a list the recurring enabled field will come as true
```
Response
{
"customer_payment_methods": [
{
"payment_token": "token_HeBYwsQiiuwKosGloeAF",
"payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "11",
"expiry_year": "2040",
"card_token": null,
"card_holder_name": "AKA",
"card_fingerprint": null,
"nick_name": "HELO",
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-05-23T07:11:00.434Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-23T07:11:00.434Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_lMFXXJEri6mOFZOc0q1Y",
"payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka",
"customer_id": "CustomerX",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": null,
"metadata": null,
"created": "2024-05-22T19:01:56.041Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-22T19:01:56.041Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "AE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "Dubai",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
> Now if you disable cybersource then the list pm will show the recurring enabled field for wallets as false
<img width="1680" alt="Screenshot 2024-05-23 at 12 46 15 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/11902155-dff0-4cf9-a4a0-7413810ea013">
```
Response
{
"customer_payment_methods": [
{
"payment_token": "token_P93Wev0NlWNzCqr0nHzz",
"payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "11",
"expiry_year": "2040",
"card_token": null,
"card_holder_name": "AKA",
"card_fingerprint": null,
"nick_name": "HELO",
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-05-23T07:11:00.434Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-23T07:11:00.434Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_MaQ7pdm33YgwUHQtOSFe",
"payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka",
"customer_id": "CustomerX",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": null,
"metadata": null,
"created": "2024-05-22T19:01:56.041Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-22T19:01:56.041Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "AE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "Dubai",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
> Make a on_session payment with some other card, lets say `4111`, the recurring enabled will be false as there was no mandate setup with the connector
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \
--data-raw ' {"amount": 7000,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "CustomerX",
"email": "something@gmail.com",
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1
}
},
"setup_future_usage": "on_session"
}'
```
```
Confirm
curl --location 'http://localhost:8080/payments/pay_Ig6fQkfaXJfMYNWFYRp2/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "12",
"card_exp_year": "2043",
"card_holder_name": "Cy1",
"card_cvc": "123"
}
},
"routing": {
"type": "single",
"data": {"connector":"cybersource","merchant_connector_id":"mca_JfI8xFhxTnL5q2bFhpUW"}
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}}
}'
```
```
Response
{
"customer_payment_methods": [
{
"payment_token": "token_bz048kmTQUOIn9ZVXt6P",
"payment_method_id": "pm_SkeqCzMYhN4ztURPxxw9",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "1111",
"expiry_month": "12",
"expiry_year": "2043",
"card_token": null,
"card_holder_name": "Cy1",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "411111",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-05-23T07:19:38.071Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-23T07:19:38.071Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_XwND8wiXdMykgcfZQprc",
"payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "11",
"expiry_year": "2040",
"card_token": null,
"card_holder_name": "AKA",
"card_fingerprint": null,
"nick_name": "HELO",
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-05-23T07:11:00.434Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-23T07:11:00.434Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_RDoIFRCyyWgRcaB2JPGa",
"payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka",
"customer_id": "CustomerX",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": null,
"metadata": null,
"created": "2024-05-22T19:01:56.041Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-22T19:01:56.041Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "AE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "Dubai",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8afeda54fc5e3f3d510c48c81c222387e9cacc0e
|
- Create a MA and a MCA with 2 connectors , cybersource and stripe
- Create a mandate payment with one card , lets say using stripe
- create a mandate payment with some pm, let's say wallet with the connector cybersource
- list the payment methods for the customer, the card which has mandate enabled will have the recurring field as true else false
> So in the below case have not disabled any mca and then you do a list the recurring enabled field will come as true
```
Response
{
"customer_payment_methods": [
{
"payment_token": "token_HeBYwsQiiuwKosGloeAF",
"payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "11",
"expiry_year": "2040",
"card_token": null,
"card_holder_name": "AKA",
"card_fingerprint": null,
"nick_name": "HELO",
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-05-23T07:11:00.434Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-23T07:11:00.434Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_lMFXXJEri6mOFZOc0q1Y",
"payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka",
"customer_id": "CustomerX",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": null,
"metadata": null,
"created": "2024-05-22T19:01:56.041Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-22T19:01:56.041Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "AE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "Dubai",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
> Now if you disable cybersource then the list pm will show the recurring enabled field for wallets as false
<img width="1680" alt="Screenshot 2024-05-23 at 12 46 15 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/11902155-dff0-4cf9-a4a0-7413810ea013">
```
Response
{
"customer_payment_methods": [
{
"payment_token": "token_P93Wev0NlWNzCqr0nHzz",
"payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "11",
"expiry_year": "2040",
"card_token": null,
"card_holder_name": "AKA",
"card_fingerprint": null,
"nick_name": "HELO",
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-05-23T07:11:00.434Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-23T07:11:00.434Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_MaQ7pdm33YgwUHQtOSFe",
"payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka",
"customer_id": "CustomerX",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": null,
"metadata": null,
"created": "2024-05-22T19:01:56.041Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-22T19:01:56.041Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "AE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "Dubai",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
> Make a on_session payment with some other card, lets say `4111`, the recurring enabled will be false as there was no mandate setup with the connector
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \
--data-raw ' {"amount": 7000,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "CustomerX",
"email": "something@gmail.com",
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1
}
},
"setup_future_usage": "on_session"
}'
```
```
Confirm
curl --location 'http://localhost:8080/payments/pay_Ig6fQkfaXJfMYNWFYRp2/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_7bjDyp3n0wrRt2q8JiftvA6eggv0vWNQNNSFL7YgtDg0q4JTQIPvvRJf9WF6FR9H' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "12",
"card_exp_year": "2043",
"card_holder_name": "Cy1",
"card_cvc": "123"
}
},
"routing": {
"type": "single",
"data": {"connector":"cybersource","merchant_connector_id":"mca_JfI8xFhxTnL5q2bFhpUW"}
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}}
}'
```
```
Response
{
"customer_payment_methods": [
{
"payment_token": "token_bz048kmTQUOIn9ZVXt6P",
"payment_method_id": "pm_SkeqCzMYhN4ztURPxxw9",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "1111",
"expiry_month": "12",
"expiry_year": "2043",
"card_token": null,
"card_holder_name": "Cy1",
"card_fingerprint": null,
"nick_name": null,
"card_network": null,
"card_isin": "411111",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-05-23T07:19:38.071Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-23T07:19:38.071Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_XwND8wiXdMykgcfZQprc",
"payment_method_id": "pm_N1PKc4pShnNg3zCCKFrY",
"customer_id": "CustomerX",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "11",
"expiry_year": "2040",
"card_token": null,
"card_holder_name": "AKA",
"card_fingerprint": null,
"nick_name": "HELO",
"card_network": null,
"card_isin": "424242",
"card_issuer": null,
"card_type": null,
"saved_to_locker": true
},
"metadata": null,
"created": "2024-05-23T07:11:00.434Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-23T07:11:00.434Z",
"default_payment_method_set": false,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
}
},
{
"payment_token": "token_RDoIFRCyyWgRcaB2JPGa",
"payment_method_id": "pm_rHGmYfEiZU2tMjFV3Gka",
"customer_id": "CustomerX",
"payment_method": "wallet",
"payment_method_type": "google_pay",
"payment_method_issuer": null,
"payment_method_issuer_code": null,
"recurring_enabled": true,
"installment_payment_enabled": false,
"payment_experience": [
"redirect_to_url"
],
"card": null,
"metadata": null,
"created": "2024-05-22T19:01:56.041Z",
"bank": null,
"surcharge_details": null,
"requires_cvv": true,
"last_used_at": "2024-05-22T19:01:56.041Z",
"default_payment_method_set": true,
"billing": {
"address": {
"city": "San Fransico",
"country": "AE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "Dubai",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
},
"email": null
}
}
],
"is_guest_customer": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4764
|
Bug: feat: Use redis in Begin and Verify TOTP
- Currently begin TOTP is directly replacing the secret in the db. This will cause issues when user didn't complete generating recovery codes. So we should keep the new secret in redis temporarily.
- And Verify TOTP should not complete the TOTP flow as user should complete the generation of recovery codes.
- There should be a new API which verifies the TOTP with the redis's secret and update the DB.
|
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 5423fc830a5..0c8678d2ef8 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -255,12 +255,11 @@ pub struct BeginTotpResponse {
pub struct TotpSecret {
pub secret: Secret<String>,
pub totp_url: Secret<String>,
- pub recovery_codes: Vec<Secret<String>>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VerifyTotpRequest {
- pub totp: Option<Secret<String>>,
+ pub totp: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 2f347dc3d3e..3c6cd8b6ccd 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -13,5 +13,7 @@ pub const TOTP_TOLERANCE: u8 = 1;
pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
-pub const TOTP_PREFIX: &str = "TOTP_";
+pub const REDIS_TOTP_PREFIX: &str = "TOTP_";
pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_";
+pub const REDIS_TOTP_SECRET_PREFIX: &str = "TOTP_SEC_";
+pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 5 * 60; // 5 minutes
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index adcf8794b83..865bc1d4124 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -78,6 +78,8 @@ pub enum UserErrors {
TwoFactorAuthRequired,
#[error("TwoFactorAuthNotSetup")]
TwoFactorAuthNotSetup,
+ #[error("TOTP secret not found")]
+ TotpSecretNotFound,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -199,6 +201,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::TwoFactorAuthNotSetup => {
AER::BadRequest(ApiError::new(sub_code, 41, self.get_error_message(), None))
}
+ Self::TotpSecretNotFound => {
+ AER::BadRequest(ApiError::new(sub_code, 42, self.get_error_message(), None))
+ }
}
}
}
@@ -241,6 +246,7 @@ impl UserErrors {
Self::InvalidRecoveryCode => "Invalid Recovery Code",
Self::TwoFactorAuthRequired => "Two factor auth required",
Self::TwoFactorAuthNotSetup => "Two factor auth not setup",
+ Self::TotpSecretNotFound => "TOTP secret not found",
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 4fd9fa865cd..7b6e8ebd365 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1633,41 +1633,14 @@ pub async fn begin_totp(
}
let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?;
- let recovery_codes = domain::RecoveryCodes::generate_new();
-
- let key_store = user_from_db.get_or_create_key_store(&state).await?;
+ let secret = totp.get_secret_base32().into();
- state
- .store
- .update_user_by_user_id(
- user_from_db.get_user_id(),
- storage_user::UserUpdate::TotpUpdate {
- totp_status: Some(TotpStatus::InProgress),
- totp_secret: Some(
- // TODO: Impl conversion trait for User and move this there
- domain::types::encrypt::<String, masking::WithType>(
- totp.get_secret_base32().into(),
- key_store.key.peek(),
- )
- .await
- .change_context(UserErrors::InternalServerError)?
- .into(),
- ),
- totp_recovery_codes: Some(
- recovery_codes
- .get_hashed()
- .change_context(UserErrors::InternalServerError)?,
- ),
- },
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
+ 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.get_secret_base32().into(),
+ secret,
totp_url: totp.get_url().into(),
- recovery_codes: recovery_codes.into_inner(),
}),
}))
}
@@ -1684,54 +1657,93 @@ pub async fn verify_totp(
.change_context(UserErrors::InternalServerError)?
.into();
- if let Some(user_totp) = req.totp {
- if user_from_db.get_totp_status() == TotpStatus::NotSet {
- return Err(UserErrors::TotpNotSetup.into());
- }
+ if user_from_db.get_totp_status() != TotpStatus::Set {
+ return Err(UserErrors::TotpNotSetup.into());
+ }
- let user_totp_secret = user_from_db
- .decrypt_and_get_totp_secret(&state)
- .await?
- .ok_or(UserErrors::InternalServerError)?;
+ 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))?;
+ let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?;
- if totp
- .generate_current()
- .change_context(UserErrors::InternalServerError)?
- != user_totp.expose()
- {
- return Err(UserErrors::InvalidTotp.into());
- }
+ if totp
+ .generate_current()
+ .change_context(UserErrors::InternalServerError)?
+ != req.totp.expose()
+ {
+ return Err(UserErrors::InvalidTotp.into());
+ }
- if user_from_db.get_totp_status() == TotpStatus::InProgress {
- state
- .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)?;
- }
+ tfa_utils::insert_totp_in_redis(&state, &user_token.user_id).await?;
+
+ Ok(ApplicationResponse::StatusOk)
+}
+
+pub async fn update_totp(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ req: user_api::VerifyTotpRequest,
+) -> UserResponse<()> {
+ let user_from_db: domain::UserFromStorage = state
+ .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))?;
+
+ if totp
+ .generate_current()
+ .change_context(UserErrors::InternalServerError)?
+ != req.totp.expose()
+ {
+ return Err(UserErrors::InvalidTotp.into());
}
- let current_flow = domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::TOTP.into())?;
- let next_flow = current_flow.next(user_from_db, &state).await?;
- let token = next_flow.get_token(&state).await?;
+ let key_store = user_from_db.get_or_create_key_store(&state).await?;
- auth::cookies::set_cookie_response(
- user_api::TokenResponse {
- token: token.clone(),
- token_type: next_flow.get_flow().into(),
- },
- token,
- )
+ state
+ .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::encrypt::<String, masking::WithType>(
+ totp.get_secret_base32().into(),
+ key_store.key.peek(),
+ )
+ .await
+ .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(|e| logger::error!(?e));
+
+ // 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(|e| logger::error!(?e));
+
+ Ok(ApplicationResponse::StatusOk)
}
pub async fn generate_recovery_codes(
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index bad5ab5a926..b38479cd2b6 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1209,17 +1209,33 @@ impl User {
web::resource("/data")
.route(web::get().to(get_multiple_dashboard_metadata))
.route(web::post().to(set_dashboard_metadata)),
- )
- .service(web::resource("/totp/begin").route(web::get().to(totp_begin)))
- .service(web::resource("/totp/verify").route(web::post().to(totp_verify)))
- .service(
- web::resource("/2fa/terminate").route(web::get().to(terminate_two_factor_auth)),
);
+ // Two factor auth routes
route = route.service(
- web::scope("/recovery_code")
- .service(web::resource("/verify").route(web::post().to(verify_recovery_code)))
- .service(web::resource("/generate").route(web::post().to(generate_recovery_codes))),
+ web::scope("/2fa")
+ .service(
+ web::scope("/totp")
+ .service(web::resource("/begin").route(web::get().to(totp_begin)))
+ .service(
+ web::resource("/verify")
+ .route(web::post().to(totp_verify))
+ .route(web::put().to(totp_update)),
+ ),
+ )
+ .service(
+ web::scope("/recovery_code")
+ .service(
+ web::resource("/verify").route(web::post().to(verify_recovery_code)),
+ )
+ .service(
+ web::resource("/generate")
+ .route(web::get().to(generate_recovery_codes)),
+ ),
+ )
+ .service(
+ web::resource("/terminate").route(web::get().to(terminate_two_factor_auth)),
+ ),
);
#[cfg(feature = "email")]
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 75821bbd2ba..9e53eb35473 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -215,9 +215,11 @@ impl From<Flow> for ApiIdentifier {
| Flow::UpdateUserAccountDetails
| Flow::TotpBegin
| Flow::TotpVerify
+ | Flow::TotpUpdate
| Flow::RecoveryCodeVerify
| Flow::RecoveryCodesGenerate
| Flow::TerminateTwoFactorAuth => Self::User,
+
Flow::ListRoles
| Flow::GetRole
| Flow::GetRoleFromToken
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 6b8015ac3e5..5ba7ec8da25 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -684,6 +684,24 @@ pub async fn verify_recovery_code(
.await
}
+pub async fn totp_update(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<user_api::VerifyTotpRequest>,
+) -> HttpResponse {
+ let flow = Flow::TotpUpdate;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ |state, user, req_body, _| user_core::update_totp(state, user, req_body),
+ &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::RecoveryCodesGenerate;
Box::pin(api::server_wrap(
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 9c67dbfcab5..db1d0ea2508 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -1,9 +1,10 @@
-use std::collections::HashMap;
+use std::{collections::HashMap, sync::Arc};
use api_models::user as user_api;
use common_utils::errors::CustomResult;
use diesel_models::{enums::UserStatus, user_role::UserRole};
use error_stack::ResultExt;
+use redis_interface::RedisConnectionPool;
use crate::{
core::errors::{StorageError, UserErrors, UserResult},
@@ -191,3 +192,11 @@ pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> maskin
user_api::SignInResponse::MerchantSelect(data) => data.token.clone(),
}
}
+
+pub fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool>> {
+ state
+ .store
+ .get_redis_conn()
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get redis connection")
+}
diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs
index e9e3f66005c..6bd693c07f5 100644
--- a/crates/router/src/utils/user/two_factor_auth.rs
+++ b/crates/router/src/utils/user/two_factor_auth.rs
@@ -1,9 +1,6 @@
-use std::sync::Arc;
-
use common_utils::pii;
use error_stack::ResultExt;
-use masking::ExposeInterface;
-use redis_interface::RedisConnectionPool;
+use masking::{ExposeInterface, PeekInterface};
use totp_rs::{Algorithm, TOTP};
use crate::{
@@ -35,8 +32,8 @@ pub fn generate_default_totp(
}
pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> {
- let redis_conn = get_redis_connection(state)?;
- let key = format!("{}{}", consts::user::TOTP_PREFIX, user_id);
+ let redis_conn = super::get_redis_connection(state)?;
+ let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id);
redis_conn
.exists::<()>(&key)
.await
@@ -44,7 +41,7 @@ pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult<
}
pub async fn check_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> {
- let redis_conn = get_redis_connection(state)?;
+ let redis_conn = super::get_redis_connection(state)?;
let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id);
redis_conn
.exists::<()>(&key)
@@ -52,16 +49,62 @@ pub async fn check_recovery_code_in_redis(state: &AppState, user_id: &str) -> Us
.change_context(UserErrors::InternalServerError)
}
-fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool>> {
- state
- .store
- .get_redis_conn()
+pub async fn insert_totp_in_redis(state: &AppState, user_id: &str) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection(state)?;
+ let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id);
+ redis_conn
+ .set_key_with_expiry(
+ key.as_str(),
+ common_utils::date_time::now_unix_timestamp(),
+ state.conf.user.two_factor_auth_expiry_in_secs,
+ )
+ .await
.change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to get redis connection")
+}
+
+pub async fn insert_totp_secret_in_redis(
+ state: &AppState,
+ user_id: &str,
+ secret: &masking::Secret<String>,
+) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection(state)?;
+ redis_conn
+ .set_key_with_expiry(
+ &get_totp_secret_key(user_id),
+ secret.peek(),
+ consts::user::REDIS_TOTP_SECRET_TTL_IN_SECS,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+
+pub async fn get_totp_secret_from_redis(
+ state: &AppState,
+ user_id: &str,
+) -> UserResult<Option<masking::Secret<String>>> {
+ let redis_conn = super::get_redis_connection(state)?;
+ redis_conn
+ .get_key::<Option<String>>(&get_totp_secret_key(user_id))
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|secret| secret.map(Into::into))
+}
+
+pub async fn delete_totp_secret_from_redis(state: &AppState, user_id: &str) -> UserResult<()> {
+ let redis_conn = super::get_redis_connection(state)?;
+ redis_conn
+ .delete_key(&get_totp_secret_key(user_id))
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .map(|_| ())
+}
+
+fn get_totp_secret_key(user_id: &str) -> String {
+ format!("{}{}", consts::user::REDIS_TOTP_SECRET_PREFIX, user_id)
}
pub async fn insert_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<()> {
- let redis_conn = get_redis_connection(state)?;
+ let redis_conn = super::get_redis_connection(state)?;
let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id);
redis_conn
.set_key_with_expiry(
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 35b55b6fb97..1bfc20ff1ca 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -406,6 +406,8 @@ pub enum Flow {
TotpBegin,
/// Verify TOTP
TotpVerify,
+ /// Update TOTP secret
+ TotpUpdate,
/// Verify Access Code
RecoveryCodeVerify,
/// Generate or Regenerate recovery codes
|
2024-05-24T12:57:30Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Begin TOTP will now insert the TOTP secret in redis instead of DB directly, which allows the old secret to stay if it exists and recovery codes are also removed from Begin TOTP.
- Verify TOTP will now send 200 OK and puts the timestamp in the redis when the TOTP is verified.
- Update TOTP is a new API which will take the TOTP and verifies the TOTP against the redis secret instead of db secret. If the TOTP is correct, it will replace the redis secret in the db.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #4764.
Closes #4707.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. TOTP Routes
1. Begin TOTP
```curl
curl --location 'http://localhost:8080/user/2fa/totp/begin' \
--header 'Authorization: Bearer SPT with Purpose as TOTP'
```
```
{
"secret": {
"secret": "Q54GEKFSVTP4FU3YHDFMEN5KMGD2P3IN",
"totp_url": "otpauth://totp/Hyperswitch:mani.dchandra%40juspay.in?secret=Q54GEKFSVTP4FU3YHDFMEN5KMGD2P3IN&issuer=Hyperswitch"
}
}
```
2. Verify TOTP
```
curl --location 'http://localhost:8080/user/2fa/totp/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
--data '{
"totp": "701394"
}'
```
Response will be 200 OK if the TOTP is correct.
2. Recovery Codes Routes
1. Verify Recovery Code
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
--data '{
"recovery_code": "m14a-0ni6"
}'
```
Response will be 200 OK if the Recovery code is correct.
2. Generate Recovery codes
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
```
```
{
"recovery_codes": [
"w5fM-NLm0",
"TumH-oyXE",
"wDIr-zEmu",
"HZjm-e16M",
"Q4qB-MupL",
"5BtN-vRuY",
"4vG6-URGf",
"Dbq8-n5V1"
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
d686ec7acda6ce852fac8d7413f9ba903adcee1d
|
1. TOTP Routes
1. Begin TOTP
```curl
curl --location 'http://localhost:8080/user/2fa/totp/begin' \
--header 'Authorization: Bearer SPT with Purpose as TOTP'
```
```
{
"secret": {
"secret": "Q54GEKFSVTP4FU3YHDFMEN5KMGD2P3IN",
"totp_url": "otpauth://totp/Hyperswitch:mani.dchandra%40juspay.in?secret=Q54GEKFSVTP4FU3YHDFMEN5KMGD2P3IN&issuer=Hyperswitch"
}
}
```
2. Verify TOTP
```
curl --location 'http://localhost:8080/user/2fa/totp/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
--data '{
"totp": "701394"
}'
```
Response will be 200 OK if the TOTP is correct.
2. Recovery Codes Routes
1. Verify Recovery Code
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
--data '{
"recovery_code": "m14a-0ni6"
}'
```
Response will be 200 OK if the Recovery code is correct.
2. Generate Recovery codes
```
curl --location 'http://localhost:8080/user/2fa/recovery_code/generate' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
```
```
{
"recovery_codes": [
"w5fM-NLm0",
"TumH-oyXE",
"wDIr-zEmu",
"HZjm-e16M",
"Q4qB-MupL",
"5BtN-vRuY",
"4vG6-URGf",
"Dbq8-n5V1"
]
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4740
|
Bug: Setup for Data services locally targeting clickhouse/ kafka and the relevant features on dashboard
|
diff --git a/README.md b/README.md
index 5bfcfdfd62b..62e016d3620 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@ The single API to access payment ecosystems across 130+ countries</div>
<p align="center">
<a href="#%EF%B8%8F-quick-start-guide">Quick Start Guide</a> •
- <a href="https://github.com/juspay/hyperswitch/blob/main/docs/try_local_system.md">Local Setup Guide</a> •
+ <a href="/docs/try_local_system.md">Local Setup Guide</a> •
<a href="#-fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> •
<a href="https://api-reference.hyperswitch.io/introduction"> API Docs </a> •
<a href="#-supported-features">Supported Features</a> •
diff --git a/config/dashboard.toml b/config/dashboard.toml
new file mode 100644
index 00000000000..9bb2b6bf336
--- /dev/null
+++ b/config/dashboard.toml
@@ -0,0 +1,38 @@
+[default.theme]
+primary_color="#006DF9"
+primary_hover_color="#005ED6"
+sidebar_color="#242F48"
+
+[default.endpoints]
+api_url="http://localhost:8080" # The backend hyperswitch API server for making payments
+sdk_url="http://localhost:9050/HyperLoader.js" # SDK distribution url used for loading the SDK in control center
+logo_url=""
+favicon_url=""
+mixpanel_token=""
+
+[default.features]
+test_live_toggle=false
+is_live_mode=false
+email=false
+quick_start=false
+audit_trail=true
+system_metrics=false
+sample_data=false
+frm=false
+payout=true
+recon=false
+test_processors=true
+feedback=false
+mixpanel=false
+generate_report=false
+user_journey_analytics=false
+authentication_analytics=false
+surcharge=false
+dispute_evidence_upload=false
+paypal_automatic_flow=false
+threeds_authenticator=false
+global_search=false
+dispute_analytics=true
+configure_pmts=false
+branding=false
+totp=false
\ No newline at end of file
diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md
new file mode 100644
index 00000000000..b822edd810e
--- /dev/null
+++ b/crates/analytics/docs/README.md
@@ -0,0 +1,104 @@
+# Running Kafka & Clickhouse with Analytics and Events Source Configuration
+
+This document provides instructions on how to run Kafka and Clickhouse using Docker Compose, and how to configure the analytics and events source.
+
+## Architecture
+ +------------------------+
+ | Hyperswitch |
+ +------------------------+
+ |
+ |
+ v
+ +------------------------+
+ | Kafka |
+ | (Event Stream Broker) |
+ +------------------------+
+ |
+ |
+ v
+ +------------------------+
+ | ClickHouse |
+ | +------------------+ |
+ | | Kafka Engine | |
+ | | Table | |
+ | +------------------+ |
+ | | |
+ | v |
+ | +------------------+ |
+ | | Materialized | |
+ | | View (MV) | |
+ | +------------------+ |
+ | | |
+ | v |
+ | +------------------+ |
+ | | Storage Table | |
+ | +------------------+ |
+ +------------------------+
+
+
+## Starting the Containers
+
+Docker Compose can be used to start all the components.
+
+Run the following command:
+
+```bash
+docker compose --profile olap up -d
+```
+This will spawn up the following services
+1. kafka
+2. clickhouse
+3. opensearch
+
+## Setting up Kafka
+
+Kafka-UI is a visual tool for inspecting Kafka and it can be accessed at `localhost:8090` to view topics, partitions, consumers & generated events.
+
+## Setting up Clickhouse
+
+Once Clickhouse is up and running, you can interact with it via web.
+
+You can either visit the URL (`http://localhost:8123/play`) where the Clickhouse server is running to get a playground, or you can bash into the Clickhouse container and execute commands manually.
+
+Run the following commands:
+
+```bash
+# On your local terminal
+docker compose exec clickhouse-server bash
+
+# Inside the clickhouse-server container shell
+clickhouse-client --user default
+
+# Inside the clickhouse-client shell
+SHOW TABLES;
+```
+
+## Configuring Analytics and Events Source
+
+To use Clickhouse and Kafka, you need to enable the `analytics.source` and update the `events.source` in the configuration file.
+
+You can do this in either the `config/development.toml` or `config/docker_compose.toml` file.
+
+Here's an example of how to do this:
+
+```toml
+[analytics]
+source = "clickhouse"
+
+[events]
+source = "kafka"
+```
+
+After making this change, save the file and restart your application for the changes to take effect.
+
+## Enabling Data Features in Dashboard
+
+To check the data features in the dashboard, you need to enable them in the `config/dashboard.toml` configuration file.
+
+Here's an example of how to do this:
+
+```toml
+[default.features]
+audit_trail=true
+system_metrics=true
+```
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/README.md b/crates/analytics/docs/clickhouse/README.md
deleted file mode 100644
index 2fd48a30c29..00000000000
--- a/crates/analytics/docs/clickhouse/README.md
+++ /dev/null
@@ -1,45 +0,0 @@
-#### Starting the containers
-
-In our use case we rely on kafka for ingesting events.
-hence we can use docker compose to start all the components
-
-```
-docker compose up -d clickhouse-server kafka-ui
-```
-
-> kafka-ui is a visual tool for inspecting kafka on localhost:8090
-
-#### Setting up Clickhouse
-
-Once clickhouse is up & running you need to create the required tables for it
-
-you can either visit the url (http://localhost:8123/play) in which the clickhouse-server is running to get a playground
-Alternatively you can bash into the clickhouse container & execute commands manually
-```
-# On your local terminal
-docker compose exec clickhouse-server bash
-
-# Inside the clickhouse-server container shell
-clickhouse-client --user default
-
-# Inside the clickhouse-client shell
-SHOW TABLES;
-CREATE TABLE ......
-```
-
-The table creation scripts are provided [here](./scripts)
-
-#### Running/Debugging your application
-Once setup you can run your application either via docker compose or normally via cargo run
-
-Remember to enable the kafka_events via development.toml/docker_compose.toml files
-
-Inspect the [kafka-ui](http://localhost:8090) to check the messages being inserted in queue
-
-If the messages/topic are available then you can run select queries on your clickhouse table to ensure data is being populated...
-
-If the data is not being populated in clickhouse, you can check the error logs in clickhouse server via
-```
-# Inside the clickhouse-server container shell
-tail -f /var/log/clickhouse-server/clickhouse-server.err.log
-```
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index 64d36caf248..a1e9e1dee92 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,5 +1,3 @@
-version: "3.8"
-
volumes:
pg_data:
redisinsight_store:
@@ -137,8 +135,8 @@ services:
context: ./docker
dockerfile: web.Dockerfile
environment:
- - HYPERSWITCH_PUBLISHABLE_KEY=$HYPERSWITCH_PUBLISHABLE_KEY
- - HYPERSWITCH_SECRET_KEY=$HYPERSWITCH_SECRET_KEY
+ - HYPERSWITCH_PUBLISHABLE_KEY=${HYPERSWITCH_PUBLISHABLE_KEY:PUBLISHABLE_KEY}
+ - HYPERSWITCH_SECRET_KEY=${HYPERSWITCH_SECRET_KEY:SECRET_KEY}
- HYPERSWITCH_SERVER_URL=${HYPERSWITCH_SERVER_URL:-http://hyperswitch-server:8080}
- HYPERSWITCH_CLIENT_URL=${HYPERSWITCH_CLIENT_URL:-http://localhost:9050}
- SELF_SERVER_URL=${SELF_SERVER_URL:-http://localhost:5252}
@@ -156,8 +154,11 @@ services:
ports:
- "9000:9000"
environment:
- - apiBaseUrl=http://localhost:8080
- - sdkBaseUrl=http://localhost:9050/HyperLoader.js
+ - configPath=/tmp/dashboard-config.toml
+ volumes:
+ - ./config/dashboard.toml:/tmp/dashboard-config.toml
+ depends_on:
+ - hyperswitch-web
labels:
logs: "promtail"
@@ -185,38 +186,23 @@ services:
- redis-cluster
networks:
- router_net
- command: "bash -c 'export COUNT=${REDIS_CLUSTER_COUNT:-3}
-
- \ if [ $$COUNT -lt 3 ]
-
- \ then
-
- \ echo \"Minimum 3 nodes are needed for redis cluster\"
-
- \ exit 1
-
- \ fi
-
- \ HOSTS=\"\"
-
- \ for ((c=1; c<=$$COUNT;c++))
-
- \ do
-
- \ NODE=$COMPOSE_PROJECT_NAME-redis-cluster-$$c:6379
-
- \ echo $$NODE
-
- \ HOSTS=\"$$HOSTS $$NODE\"
-
- \ done
-
- \ echo Creating a cluster with $$HOSTS
-
- \ redis-cli --cluster create $$HOSTS --cluster-yes
-
- \ '"
-
+ command: |-
+ bash -c 'export COUNT=${REDIS_CLUSTER_COUNT:-3}
+ if [ $$COUNT -lt 3 ]
+ then
+ echo \"Minimum 3 nodes are needed for redis cluster\"
+ exit 1
+ fi
+ HOSTS=\"\"
+ for ((c=1; c<=$$COUNT;c++))
+ do
+ NODE=$COMPOSE_PROJECT_NAME-redis-cluster-$$c:6379
+ echo $$NODE
+ HOSTS=\"$$HOSTS $$NODE\"
+ done
+ echo Creating a cluster with $$HOSTS
+ redis-cli --cluster create $$HOSTS --cluster-yes
+ '
### Monitoring
grafana:
image: grafana/grafana:latest
@@ -304,7 +290,7 @@ services:
networks:
- router_net
profiles:
- - full_kv
+ - monitoring
ports:
- "8001:8001"
volumes:
@@ -390,24 +376,20 @@ services:
hostname: opensearch
environment:
- "discovery.type=single-node"
- expose:
- - "9200"
+ profiles:
+ - olap
ports:
- "9200:9200"
networks:
- router_net
- profiles:
- - olap
opensearch-dashboards:
image: opensearchproject/opensearch-dashboards:1.3.14
ports:
- 5601:5601
- expose:
- - "5601"
+ profiles:
+ - olap
environment:
OPENSEARCH_HOSTS: '["https://opensearch:9200"]'
networks:
- router_net
- profiles:
- - olap
|
2024-05-23T07:33:28Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Fixes #4740
- Update `docker-compose.yml` profiles to unfiy them
- Add steps in `try_local_system.md` to setup data services
- Add additional documentation in `analytics` crate to enable features in `control-center`
- update architecture diagram to include data services
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Providing a better user experience for self hosting users
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Don't need to test since doc changes only
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
13f6efc7e8c01b4a377f627b9cfe2319b518204d
|
- Don't need to test since doc changes only
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4730
|
Bug: refactor: Separate out totp completion from verify
Currently,`verify_totp` is the terminating 2fa API and also it was setting the TOTP status as "SET".
So , we want to separate the logic of terminating the 2FA to a separate API so that the job of the `verify_totp` API will only be to verify if the totp is valid or not which will also help in reusing it inside dashboard.
|
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 7864117856e..6b2748ca344 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -224,6 +224,11 @@ pub struct TokenOnlyQueryParam {
pub token_only: Option<bool>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct SkipTwoFactorAuthQueryParam {
+ pub skip_two_factor_auth: Option<bool>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct TokenResponse {
pub token: Secret<String>,
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 33642205d57..7b61a834f60 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -14,3 +14,4 @@ pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
pub const TOTP_PREFIX: &str = "TOTP_";
+pub const REDIS_RECOVERY_CODES_PREFIX: &str = "RC_";
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 2d1c196f5df..cda85078718 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -72,6 +72,10 @@ pub enum UserErrors {
InvalidTotp,
#[error("TotpRequired")]
TotpRequired,
+ #[error("TwoFactorAuthRequired")]
+ TwoFactorAuthRequired,
+ #[error("TwoFactorAuthNotSetup")]
+ TwoFactorAuthNotSetup,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -184,6 +188,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::TotpRequired => {
AER::BadRequest(ApiError::new(sub_code, 38, self.get_error_message(), None))
}
+ Self::TwoFactorAuthRequired => {
+ AER::BadRequest(ApiError::new(sub_code, 39, self.get_error_message(), None))
+ }
+ Self::TwoFactorAuthNotSetup => {
+ AER::BadRequest(ApiError::new(sub_code, 40, self.get_error_message(), None))
+ }
}
}
}
@@ -223,6 +233,8 @@ impl UserErrors {
Self::TotpNotSetup => "TOTP not setup",
Self::InvalidTotp => "Invalid TOTP",
Self::TotpRequired => "TOTP required",
+ Self::TwoFactorAuthRequired => "Two factor auth required",
+ Self::TwoFactorAuthNotSetup => "Two factor auth not setup",
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 7a0ef683e7a..705c12907ff 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -24,8 +24,9 @@ use crate::{
routes::{app::ReqState, AppState},
services::{authentication as auth, authorization::roles, ApplicationResponse},
types::{domain, transformers::ForeignInto},
- utils,
+ utils::{self, user::two_factor_auth as tfa_utils},
};
+
pub mod dashboard_metadata;
#[cfg(feature = "dummy_connector")]
pub mod sample_data;
@@ -1631,7 +1632,7 @@ pub async fn begin_totp(
}));
}
- let totp = utils::user::two_factor_auth::generate_default_totp(user_from_db.get_email(), None)?;
+ let totp = tfa_utils::generate_default_totp(user_from_db.get_email(), None)?;
let recovery_codes = domain::RecoveryCodes::generate_new();
let key_store = user_from_db.get_or_create_key_store(&state).await?;
@@ -1693,10 +1694,8 @@ pub async fn verify_totp(
.await?
.ok_or(UserErrors::InternalServerError)?;
- let totp = utils::user::two_factor_auth::generate_default_totp(
- user_from_db.get_email(),
- Some(user_totp_secret),
- )?;
+ let totp =
+ tfa_utils::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?;
if totp
.generate_current()
@@ -1739,7 +1738,7 @@ pub async fn generate_recovery_codes(
state: AppState,
user_token: auth::UserFromSinglePurposeToken,
) -> UserResponse<user_api::RecoveryCodes> {
- if !utils::user::two_factor_auth::check_totp_in_redis(&state, &user_token.user_id).await? {
+ if !tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await? {
return Err(UserErrors::TotpRequired.into());
}
@@ -1766,3 +1765,55 @@ pub async fn generate_recovery_codes(
recovery_codes: recovery_codes.into_inner(),
}))
}
+
+pub async fn terminate_two_factor_auth(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ skip_two_factor_auth: bool,
+) -> UserResponse<user_api::TokenResponse> {
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_id(&user_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ if !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
+ .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.origin, domain::SPTFlow::TOTP.into())?;
+ let next_flow = current_flow.next(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,
+ )
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 0e152ec32c1..cf2e986c325 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1215,6 +1215,9 @@ impl User {
.service(
web::resource("/recovery_codes/generate")
.route(web::get().to(generate_recovery_codes)),
+ )
+ .service(
+ web::resource("/2fa/terminate").route(web::get().to(terminate_two_factor_auth)),
);
#[cfg(feature = "email")]
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 706726979dc..97d92d49911 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -215,6 +215,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::UpdateUserAccountDetails
| Flow::TotpBegin
| Flow::TotpVerify
+ | Flow::TerminateTwoFactorAuth
| Flow::GenerateRecoveryCodes => Self::User,
Flow::ListRoles
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index f542c446e49..2019855114a 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -679,3 +679,23 @@ pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpReques
))
.await
}
+
+pub async fn terminate_two_factor_auth(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<user_api::SkipTwoFactorAuthQueryParam>,
+) -> HttpResponse {
+ let flow = Flow::TerminateTwoFactorAuth;
+ let skip_two_factor_auth = query.into_inner().skip_two_factor_auth.unwrap_or(false);
+
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| user_core::terminate_two_factor_auth(state, user, skip_two_factor_auth),
+ &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 051e6ccf38e..0704e51e781 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -930,6 +930,10 @@ impl UserFromStorage {
self.0.totp_status
}
+ pub fn get_recovery_codes(&self) -> Option<Vec<Secret<String>>> {
+ self.0.totp_recovery_codes.clone()
+ }
+
pub async fn decrypt_and_get_totp_secret(
&self,
state: &AppState,
diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs
index 62bcf2f7eb1..479c346b6e5 100644
--- a/crates/router/src/utils/user/two_factor_auth.rs
+++ b/crates/router/src/utils/user/two_factor_auth.rs
@@ -43,6 +43,15 @@ pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult<
.change_context(UserErrors::InternalServerError)
}
+pub async fn check_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> {
+ let redis_conn = get_redis_connection(state)?;
+ let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODES_PREFIX, user_id);
+ redis_conn
+ .exists::<()>(&key)
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+
fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool>> {
state
.store
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 0e35aba3174..be071ffefc3 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -408,6 +408,8 @@ pub enum Flow {
TotpVerify,
/// Generate or Regenerate recovery codes
GenerateRecoveryCodes,
+ // Terminate two factor authentication
+ TerminateTwoFactorAuth,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
2024-05-22T12:38:12Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Currently completion of 2fa and setting the status of the 2fa status as "SET" is handled by `verify_totp` API. We want to remove this from `verify_totp`, so this PR creates a new API to terminate the 2fa flow.
### Additional Changes
- [X] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
This will close the issue #4730
## How did you test it?
This can only be tested locally as it requires some changes in the redis.
1. terminate 2fa without skip_two_factor_auth query param
a. If the keys with `TOTP_{user_id}` or `RC_{user_id}` is not present in redis
Request
```
curl --location 'http://localhost:8080/user/2fa/terminate' \
--header 'Authorization: Bearer SPT with purpose as TOTP'
```
Response
```
{
"error": {
"type": "invalid_request",
"message": "Two factor auth required",
"code": "UR_39"
}
}
```
b. Add the keys to the redis with prefix as `TOTP_{user_id}` or `RC_{user_id}`
Request
```
curl --location 'http://localhost:8080/user/2fa/terminate' \
--header 'Authorization: Bearer SPT with purpose as TOTP'
```
Response
This will also set the totp_status for the user as "set"
```
{
"token": "Bearer token",
"token_type": "next flow token type"
}
```
2. terminate 2fa with skip_two_factor_auth query param
a. skip_two_factor_auth=true
Irrespective if the keys are present in redis or not if skip_two_factor_auth is sent as true it will not change the status and will give the token and token_type for the next flow
Request
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \
--header 'Authorization: Bearer SPT with purpose as TOTP'
```
Response
```
{
"token": "Bearer token",
"token_type": "next flow token type"
}
```
b. skip_two_factor_auth=false
Request
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \
--header 'Authorization: Bearer SPT with purpose as TOTP'
```
Response
This will also set the totp_status for the user as "set"
```
{
"token": "Bearer token",
"token_type": "next flow token type"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [X] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8afeda54fc5e3f3d510c48c81c222387e9cacc0e
|
This can only be tested locally as it requires some changes in the redis.
1. terminate 2fa without skip_two_factor_auth query param
a. If the keys with `TOTP_{user_id}` or `RC_{user_id}` is not present in redis
Request
```
curl --location 'http://localhost:8080/user/2fa/terminate' \
--header 'Authorization: Bearer SPT with purpose as TOTP'
```
Response
```
{
"error": {
"type": "invalid_request",
"message": "Two factor auth required",
"code": "UR_39"
}
}
```
b. Add the keys to the redis with prefix as `TOTP_{user_id}` or `RC_{user_id}`
Request
```
curl --location 'http://localhost:8080/user/2fa/terminate' \
--header 'Authorization: Bearer SPT with purpose as TOTP'
```
Response
This will also set the totp_status for the user as "set"
```
{
"token": "Bearer token",
"token_type": "next flow token type"
}
```
2. terminate 2fa with skip_two_factor_auth query param
a. skip_two_factor_auth=true
Irrespective if the keys are present in redis or not if skip_two_factor_auth is sent as true it will not change the status and will give the token and token_type for the next flow
Request
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=true' \
--header 'Authorization: Bearer SPT with purpose as TOTP'
```
Response
```
{
"token": "Bearer token",
"token_type": "next flow token type"
}
```
b. skip_two_factor_auth=false
Request
```
curl --location 'http://localhost:8080/user/2fa/terminate?skip_two_factor_auth=false' \
--header 'Authorization: Bearer SPT with purpose as TOTP'
```
Response
This will also set the totp_status for the user as "set"
```
{
"token": "Bearer token",
"token_type": "next flow token type"
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4736
|
Bug: feat: add support to verify using recovery code
Create a new endpoint that adds,
- support to verify 2FA with recovery code
- the provided recovery code can be used only once
- then verification can be done with the remaining recovery codes only next time ( there are total 8 set of recovery codes that are being generated when configuring 2FA)
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 5d575b5ba09..d5bdfb5a6a7 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -351,7 +351,8 @@ email_role_arn = "" # The amazon resource name ( arn ) of the role which
sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session.
[user]
-password_validity_in_days = 90 # Number of days after which password should be updated
+password_validity_in_days = 90 # Number of days after which password should be updated
+two_factor_auth_expiry_in_secs = 300 # Number of seconds after which 2FA should be done again if doing update/change from inside
#tokenization configuration which describe token lifetime and payment method for specific connector
[tokenization]
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 5b6c5fe152d..9551cd2a80d 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -113,6 +113,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw
[user]
password_validity_in_days = 90
+two_factor_auth_expiry_in_secs = 300
[frm]
enabled = true
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index b5441f0059d..5f940867438 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -120,6 +120,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw
[user]
password_validity_in_days = 90
+two_factor_auth_expiry_in_secs = 300
[frm]
enabled = false
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index e168fab121d..d5f63524e6b 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -120,6 +120,7 @@ slack_invite_url = "https://join.slack.com/t/hyperswitch-io/shared_invite/zt-2aw
[user]
password_validity_in_days = 90
+two_factor_auth_expiry_in_secs = 300
[frm]
enabled = true
diff --git a/config/development.toml b/config/development.toml
index af26d91446f..a9f7f4d7b4d 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -269,6 +269,7 @@ sts_role_session_name = ""
[user]
password_validity_in_days = 90
+two_factor_auth_expiry_in_secs = 300
[bank_config.eps]
stripe = { banks = "arzte_und_apotheker_bank,austrian_anadi_bank_ag,bank_austria,bankhaus_carl_spangler,bankhaus_schelhammer_und_schattera_ag,bawag_psk_ag,bks_bank_ag,brull_kallmus_bank_ag,btv_vier_lander_bank,capital_bank_grawe_gruppe_ag,dolomitenbank,easybank_ag,erste_bank_und_sparkassen,hypo_alpeadriabank_international_ag,hypo_noe_lb_fur_niederosterreich_u_wien,hypo_oberosterreich_salzburg_steiermark,hypo_tirol_bank_ag,hypo_vorarlberg_bank_ag,hypo_bank_burgenland_aktiengesellschaft,marchfelder_bank,oberbank_ag,raiffeisen_bankengruppe_osterreich,schoellerbank_ag,sparda_bank_wien,volksbank_gruppe,volkskreditbank_ag,vr_bank_braunau" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 0d615b11b5c..6661d164032 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -53,6 +53,7 @@ recon_admin_api_key = "recon_test_admin"
[user]
password_validity_in_days = 90
+two_factor_auth_expiry_in_secs = 300
[locker]
host = ""
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index b7d7adbf8e3..a472b3a76e6 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -17,7 +17,7 @@ use crate::user::{
RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest,
SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
TokenOrPayloadResponse, TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest,
- UserMerchantCreate, VerifyEmailRequest, VerifyTotpRequest,
+ UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -75,6 +75,7 @@ common_utils::impl_misc_api_event_type!(
TokenResponse,
UserFromEmailRequest,
BeginTotpResponse,
+ VerifyRecoveryCodeRequest,
VerifyTotpRequest,
RecoveryCodes
);
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 6b2748ca344..5423fc830a5 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -263,6 +263,11 @@ pub struct VerifyTotpRequest {
pub totp: Option<Secret<String>>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VerifyRecoveryCodeRequest {
+ pub recovery_code: Secret<String>,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct RecoveryCodes {
pub recovery_codes: Vec<Secret<String>>,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 9564a759ccd..b8a315f944b 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -395,6 +395,7 @@ pub struct Secrets {
#[derive(Debug, Clone, Default, Deserialize)]
pub struct UserSettings {
pub password_validity_in_days: u16,
+ pub two_factor_auth_expiry_in_secs: i64,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 7b61a834f60..2f347dc3d3e 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -14,4 +14,4 @@ pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
pub const TOTP_PREFIX: &str = "TOTP_";
-pub const REDIS_RECOVERY_CODES_PREFIX: &str = "RC_";
+pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_";
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index cda85078718..adcf8794b83 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -72,6 +72,8 @@ pub enum UserErrors {
InvalidTotp,
#[error("TotpRequired")]
TotpRequired,
+ #[error("InvalidRecoveryCode")]
+ InvalidRecoveryCode,
#[error("TwoFactorAuthRequired")]
TwoFactorAuthRequired,
#[error("TwoFactorAuthNotSetup")]
@@ -188,12 +190,15 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::TotpRequired => {
AER::BadRequest(ApiError::new(sub_code, 38, self.get_error_message(), None))
}
- Self::TwoFactorAuthRequired => {
+ Self::InvalidRecoveryCode => {
AER::BadRequest(ApiError::new(sub_code, 39, self.get_error_message(), None))
}
- Self::TwoFactorAuthNotSetup => {
+ Self::TwoFactorAuthRequired => {
AER::BadRequest(ApiError::new(sub_code, 40, self.get_error_message(), None))
}
+ Self::TwoFactorAuthNotSetup => {
+ AER::BadRequest(ApiError::new(sub_code, 41, self.get_error_message(), None))
+ }
}
}
}
@@ -233,6 +238,7 @@ impl UserErrors {
Self::TotpNotSetup => "TOTP not setup",
Self::InvalidTotp => "Invalid TOTP",
Self::TotpRequired => "TOTP required",
+ Self::InvalidRecoveryCode => "Invalid Recovery Code",
Self::TwoFactorAuthRequired => "Two factor auth required",
Self::TwoFactorAuthNotSetup => "Two factor auth not setup",
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 705c12907ff..4fd9fa865cd 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -179,7 +179,7 @@ pub async fn signin(
})?
.into();
- user_from_db.compare_password(request.password)?;
+ user_from_db.compare_password(&request.password)?;
let signin_strategy =
if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() {
@@ -217,7 +217,7 @@ pub async fn signin_token_only_flow(
.to_not_found_response(UserErrors::InvalidCredentials)?
.into();
- user_from_db.compare_password(request.password)?;
+ user_from_db.compare_password(&request.password)?;
let next_flow =
domain::NextFlow::from_origin(domain::Origin::SignIn, user_from_db.clone(), &state).await?;
@@ -341,7 +341,7 @@ pub async fn change_password(
.change_context(UserErrors::InternalServerError)?
.into();
- user.compare_password(request.old_password.to_owned())
+ user.compare_password(&request.old_password)
.change_context(UserErrors::InvalidOldPassword)?;
if request.old_password == request.new_password {
@@ -439,7 +439,7 @@ pub async fn rotate_password(
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() {
+ if user.compare_password(&request.password).is_ok() {
return Err(UserErrors::ChangePasswordError.into());
}
@@ -1766,6 +1766,51 @@ pub async fn generate_recovery_codes(
}))
}
+pub async fn verify_recovery_code(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ req: user_api::VerifyRecoveryCodeRequest,
+) -> UserResponse<user_api::TokenResponse> {
+ let user_from_db: domain::UserFromStorage = state
+ .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 mut recovery_codes = user_from_db
+ .get_recovery_codes()
+ .ok_or(UserErrors::InternalServerError)?;
+
+ let matching_index = utils::user::password::get_index_for_correct_recovery_code(
+ &req.recovery_code,
+ &recovery_codes,
+ )?
+ .ok_or(UserErrors::InvalidRecoveryCode)?;
+
+ tfa_utils::insert_recovery_code_in_redis(&state, user_from_db.get_user_id()).await?;
+ let _ = recovery_codes.remove(matching_index);
+
+ state
+ .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: AppState,
user_token: auth::UserFromSinglePurposeToken,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index cf2e986c325..bad5ab5a926 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1212,14 +1212,16 @@ impl User {
)
.service(web::resource("/totp/begin").route(web::get().to(totp_begin)))
.service(web::resource("/totp/verify").route(web::post().to(totp_verify)))
- .service(
- web::resource("/recovery_codes/generate")
- .route(web::get().to(generate_recovery_codes)),
- )
.service(
web::resource("/2fa/terminate").route(web::get().to(terminate_two_factor_auth)),
);
+ route = route.service(
+ web::scope("/recovery_code")
+ .service(web::resource("/verify").route(web::post().to(verify_recovery_code)))
+ .service(web::resource("/generate").route(web::post().to(generate_recovery_codes))),
+ );
+
#[cfg(feature = "email")]
{
route = route
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 97d92d49911..75821bbd2ba 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -215,9 +215,9 @@ impl From<Flow> for ApiIdentifier {
| Flow::UpdateUserAccountDetails
| Flow::TotpBegin
| Flow::TotpVerify
- | Flow::TerminateTwoFactorAuth
- | Flow::GenerateRecoveryCodes => Self::User,
-
+ | Flow::RecoveryCodeVerify
+ | Flow::RecoveryCodesGenerate
+ | Flow::TerminateTwoFactorAuth => Self::User,
Flow::ListRoles
| Flow::GetRole
| Flow::GetRoleFromToken
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 2019855114a..6b8015ac3e5 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -666,8 +666,26 @@ pub async fn totp_verify(
.await
}
+pub async fn verify_recovery_code(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<user_api::VerifyRecoveryCodeRequest>,
+) -> HttpResponse {
+ let flow = Flow::RecoveryCodeVerify;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ |state, user, req_body, _| user_core::verify_recovery_code(state, user, req_body),
+ &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
- let flow = Flow::GenerateRecoveryCodes;
+ let flow = Flow::RecoveryCodesGenerate;
Box::pin(api::server_wrap(
flow,
state.clone(),
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 0704e51e781..91323b0c16d 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -774,8 +774,8 @@ impl UserFromStorage {
self.0.user_id.as_str()
}
- pub fn compare_password(&self, candidate: Secret<String>) -> UserResult<()> {
- match password::is_correct_password(candidate, self.0.password.clone()) {
+ pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()> {
+ match password::is_correct_password(candidate, &self.0.password) {
Ok(true) => Ok(()),
Ok(false) => Err(UserErrors::InvalidCredentials.into()),
Err(e) => Err(e),
diff --git a/crates/router/src/utils/user/password.rs b/crates/router/src/utils/user/password.rs
index beb87c325b6..e01181acb9d 100644
--- a/crates/router/src/utils/user/password.rs
+++ b/crates/router/src/utils/user/password.rs
@@ -7,7 +7,7 @@ use argon2::{
};
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
-use masking::{ExposeInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use rand::{seq::SliceRandom, Rng};
use crate::core::errors::UserErrors;
@@ -25,13 +25,13 @@ pub fn generate_password_hash(
}
pub fn is_correct_password(
- candidate: Secret<String>,
- password: Secret<String>,
+ candidate: &Secret<String>,
+ password: &Secret<String>,
) -> CustomResult<bool, UserErrors> {
- let password = password.expose();
+ let password = password.peek();
let parsed_hash =
- PasswordHash::new(&password).change_context(UserErrors::InternalServerError)?;
- let result = Argon2::default().verify_password(candidate.expose().as_bytes(), &parsed_hash);
+ PasswordHash::new(password).change_context(UserErrors::InternalServerError)?;
+ let result = Argon2::default().verify_password(candidate.peek().as_bytes(), &parsed_hash);
match result {
Ok(_) => Ok(true),
Err(argon2Err::Password) => Ok(false),
@@ -40,6 +40,19 @@ pub fn is_correct_password(
.change_context(UserErrors::InternalServerError)
}
+pub fn get_index_for_correct_recovery_code(
+ candidate: &Secret<String>,
+ recovery_codes: &[Secret<String>],
+) -> CustomResult<Option<usize>, UserErrors> {
+ for (index, recovery_code) in recovery_codes.iter().enumerate() {
+ let is_match = is_correct_password(candidate, recovery_code)?;
+ if is_match {
+ return Ok(Some(index));
+ }
+ }
+ Ok(None)
+}
+
pub fn get_temp_password() -> Secret<String> {
let uuid_pass = uuid::Uuid::new_v4().to_string();
let mut rng = rand::thread_rng();
diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs
index 479c346b6e5..e9e3f66005c 100644
--- a/crates/router/src/utils/user/two_factor_auth.rs
+++ b/crates/router/src/utils/user/two_factor_auth.rs
@@ -45,7 +45,7 @@ pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult<
pub async fn check_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> {
let redis_conn = get_redis_connection(state)?;
- let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODES_PREFIX, user_id);
+ let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id);
redis_conn
.exists::<()>(&key)
.await
@@ -59,3 +59,16 @@ fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool>
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get redis connection")
}
+
+pub async fn insert_recovery_code_in_redis(state: &AppState, user_id: &str) -> UserResult<()> {
+ let redis_conn = get_redis_connection(state)?;
+ let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id);
+ redis_conn
+ .set_key_with_expiry(
+ key.as_str(),
+ common_utils::date_time::now_unix_timestamp(),
+ state.conf.user.two_factor_auth_expiry_in_secs,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index be071ffefc3..35b55b6fb97 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -406,8 +406,10 @@ pub enum Flow {
TotpBegin,
/// Verify TOTP
TotpVerify,
+ /// Verify Access Code
+ RecoveryCodeVerify,
/// Generate or Regenerate recovery codes
- GenerateRecoveryCodes,
+ RecoveryCodesGenerate,
// Terminate two factor authentication
TerminateTwoFactorAuth,
/// List initial webhook delivery attempts
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index a104f5760b4..2c3e83ad2ba 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -30,6 +30,7 @@ jwt_secret = "secret"
[user]
password_validity_in_days = 90
+two_factor_auth_expiry_in_secs = 300
[locker]
host = ""
|
2024-05-22T19:54:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
The PR adds support to verify 2FA using recovery code, in case TOTP is lost
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#4736](https://github.com/juspay/hyperswitch/issues/4736)
## How did you test it?
First Sign in for user for which 2FA is already set.
Then to verify 2FA:
Use the below curl to test it
```
curl --location 'http://localhost:8080/user/recovery_code/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT' \
--header 'Cookie: Cookie_1=value' \
--data '{
"recovery_code": "j4Az-W7Fk"
}'
```
If the recovery code is correct then response will be `200 ok`.
Else proper error would be thrown
```
{
"error": {
"type": "invalid_request",
"message": "Invalid Recovery Code",
"code": "UR_39"
}
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
42e5ef155128f4df717e8fb101da6e6929659a0a
|
First Sign in for user for which 2FA is already set.
Then to verify 2FA:
Use the below curl to test it
```
curl --location 'http://localhost:8080/user/recovery_code/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT' \
--header 'Cookie: Cookie_1=value' \
--data '{
"recovery_code": "j4Az-W7Fk"
}'
```
If the recovery code is correct then response will be `200 ok`.
Else proper error would be thrown
```
{
"error": {
"type": "invalid_request",
"message": "Invalid Recovery Code",
"code": "UR_39"
}
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4722
|
Bug: Enable auto-retries for apple pay
Currently for apple pay pre-routing is done before the session call and a connector is decided based on the routing logic. Because of this we are not able retry the failed apple pay payments.
As the certificates use in the simplified flows are same across the connectors the failed apple pay payment can be retired with the other connectors with apple pay simplified flow configured. In order to achieve this we need to pass a list of apple pay simplified flow configured connectors and in pre routing.
|
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 175400c54bf..9b2082cf31f 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3170,6 +3170,28 @@ where
{
routing_data.business_sub_label = choice.sub_label.clone();
}
+
+ if payment_data.payment_attempt.payment_method_type
+ == Some(storage_enums::PaymentMethodType::ApplePay)
+ {
+ let retryable_connector_data = helpers::get_apple_pay_retryable_connectors(
+ state,
+ merchant_account,
+ payment_data,
+ key_store,
+ connector_data.clone(),
+ #[cfg(feature = "connector_choice_mca_id")]
+ choice.merchant_connector_id.clone().as_ref(),
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ None,
+ )
+ .await?;
+
+ if let Some(connector_data_list) = retryable_connector_data {
+ return Ok(ConnectorCallType::Retryable(connector_data_list));
+ }
+ }
+
return Ok(ConnectorCallType::PreDetermined(connector_data));
}
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 2eb0c921bbf..76ff96c7021 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -122,36 +122,6 @@ fn is_dynamic_fields_required(
.unwrap_or(false)
}
-fn get_applepay_metadata(
- connector_metadata: Option<common_utils::pii::SecretSerdeValue>,
-) -> RouterResult<payment_types::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(),
- })
-}
-
fn build_apple_pay_session_request(
state: &routes::AppState,
request: payment_types::ApplepaySessionRequest,
@@ -196,7 +166,8 @@ async fn create_applepay_session_token(
)
} else {
// Get the apple pay metadata
- let apple_pay_metadata = get_applepay_metadata(router_data.connector_meta_data.clone())?;
+ let apple_pay_metadata =
+ helpers::get_applepay_metadata(router_data.connector_meta_data.clone())?;
// Get payment request data , apple pay session request and merchant keys
let (
@@ -213,6 +184,8 @@ async fn create_applepay_session_token(
payment_request_data,
session_token_data,
} => {
+ logger::info!("Apple pay simplified flow");
+
let merchant_identifier = state
.conf
.applepay_merchant_configs
@@ -254,6 +227,8 @@ async fn create_applepay_session_token(
payment_request_data,
session_token_data,
} => {
+ logger::info!("Apple pay manual flow");
+
let apple_pay_session_request =
get_session_request_for_manual_apple_pay(session_token_data.clone());
@@ -269,6 +244,8 @@ async fn create_applepay_session_token(
}
},
payment_types::ApplepaySessionTokenMetadata::ApplePay(apple_pay_metadata) => {
+ logger::info!("Apple pay manual flow");
+
let apple_pay_session_request = get_session_request_for_manual_apple_pay(
apple_pay_metadata.session_token_data.clone(),
);
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index eb3dca11060..06c8c7f2c94 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3888,6 +3888,122 @@ pub fn validate_customer_access(
Ok(())
}
+pub fn is_apple_pay_simplified_flow(
+ connector_metadata: Option<pii::SecretSerdeValue>,
+) -> CustomResult<bool, errors::ApiErrorResponse> {
+ let apple_pay_metadata = get_applepay_metadata(connector_metadata)?;
+
+ Ok(match apple_pay_metadata {
+ api_models::payments::ApplepaySessionTokenMetadata::ApplePayCombined(
+ apple_pay_combined_metadata,
+ ) => match apple_pay_combined_metadata {
+ api_models::payments::ApplePayCombinedMetadata::Simplified { .. } => true,
+ api_models::payments::ApplePayCombinedMetadata::Manual { .. } => false,
+ },
+ api_models::payments::ApplepaySessionTokenMetadata::ApplePay(_) => false,
+ })
+}
+
+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 async fn get_apple_pay_retryable_connectors<F>(
+ state: AppState,
+ merchant_account: &domain::MerchantAccount,
+ payment_data: &mut PaymentData<F>,
+ key_store: &domain::MerchantKeyStore,
+ decided_connector_data: api::ConnectorData,
+ merchant_connector_id: Option<&String>,
+) -> CustomResult<Option<Vec<api::ConnectorData>>, errors::ApiErrorResponse>
+where
+ F: Send + Clone,
+{
+ let profile_id = &payment_data
+ .payment_intent
+ .profile_id
+ .clone()
+ .get_required_value("profile_id")
+ .change_context(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "profile_id",
+ })?;
+
+ let merchant_connector_account = get_merchant_connector_account(
+ &state,
+ merchant_account.merchant_id.as_str(),
+ payment_data.creds_identifier.to_owned(),
+ key_store,
+ profile_id, // need to fix this
+ &decided_connector_data.connector_name.to_string(),
+ merchant_connector_id,
+ )
+ .await?
+ .get_metadata();
+
+ let connector_data_list = if is_apple_pay_simplified_flow(merchant_connector_account)? {
+ let merchant_connector_account_list = state
+ .store
+ .find_merchant_connector_account_by_merchant_id_and_disabled_list(
+ merchant_account.merchant_id.as_str(),
+ true,
+ key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
+
+ let mut connector_data_list = vec![decided_connector_data.clone()];
+
+ for merchant_connector_account in merchant_connector_account_list {
+ if is_apple_pay_simplified_flow(merchant_connector_account.metadata)? {
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &merchant_connector_account.connector_name.to_string(),
+ api::GetToken::Connector,
+ Some(merchant_connector_account.merchant_connector_id),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Invalid connector name received")?;
+
+ if !connector_data_list.iter().any(|connector_details| {
+ connector_details.merchant_connector_id == connector_data.merchant_connector_id
+ }) {
+ connector_data_list.push(connector_data)
+ }
+ }
+ }
+ Some(connector_data_list)
+ } else {
+ None
+ };
+ Ok(connector_data_list)
+}
+
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ApplePayData {
version: masking::Secret<String>,
@@ -4040,6 +4156,8 @@ impl ApplePayData {
&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)?;
|
2024-05-21T15:54:52Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently for apple pay pre-routing is done before the session call and a connector is decided based on the routing logic. Because of this we are not able retry the failed apple pay payments.
As the certificates use in the simplified flows are same across the connectors the failed apple pay payment can be retired with the other connectors with apple pay simplified flow configured. In order to achieve this we need to pass a list of apple pay simplified flow configured connectors and in pre routing.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Create a merchant account
-> Enable gcm for the `merchant_id`
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "should_call_gsm_{merchant_id}",
"value": "true"
}'
```
-> Set the maximum retries count
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "max_auto_retries_enabled_{merchant_id}",
"value": "1"
}'
```
-> Create MCA for stripe and cybersource with apple pay simplified flow
metadata for simplified flow
```
"metadata": {
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
},
"google_pay": {
"merchant_info": {
"merchant_name": "Stripe"
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
]
}
}
}
```
-> Do a apple pay payment create with confirm false
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}
```
<img width="1007" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67deb74e-e0dd-4af3-b5d9-7298d65c3e01">
-> Do payment method list for merchant
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_V1VBfr3VW6MVXaFw01sT_secret_6bByPi9DrnPk0uv6vYJj' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_cc7a8a8132a840338323ac8f7f6860d0'
```
<img width="1059" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/38f97f9d-ff51-41dc-9a06-20137f2ead1a">
-> Confirm the above create payment with `payment_id` and payment_data
```
curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: api_key' \
--data '{
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}'
```
<img width="1045" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1b5c8cb4-43bf-42ea-a82f-9c6db940950b">
-> Apple pay retry connectors
<img width="1174" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/f3612f01-ee02-4687-b42c-af70eaf3e521">
-> Payment retrieve have two payment attempts
```
curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT?expand_attempts=true' \
--header 'Accept: application/json' \
--header 'api-key: api_key'
```
<img width="720" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/705f2a0e-c057-47e1-8edf-e63139975a42">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8afeda54fc5e3f3d510c48c81c222387e9cacc0e
|
-> Create a merchant account
-> Enable gcm for the `merchant_id`
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "should_call_gsm_{merchant_id}",
"value": "true"
}'
```
-> Set the maximum retries count
```
curl --location 'localhost:8080/configs/' \
--header 'api-key: test_admin' \
--header 'Content-Type: application/json' \
--data '{
"key": "max_auto_retries_enabled_{merchant_id}",
"value": "1"
}'
```
-> Create MCA for stripe and cybersource with apple pay simplified flow
metadata for simplified flow
```
"metadata": {
"apple_pay_combined": {
"simplified": {
"session_token_data": {
"initiative_context": "sdk-test-app.netlify.app",
"merchant_business_country": "US"
},
"payment_request_data": {
"label": "applepay",
"supported_networks": [
"visa",
"masterCard",
"amex",
"discover"
],
"merchant_capabilities": [
"supports3DS"
]
}
}
},
"google_pay": {
"merchant_info": {
"merchant_name": "Stripe"
},
"allowed_payment_methods": [
{
"type": "CARD",
"parameters": {
"allowed_auth_methods": [
"PAN_ONLY",
"CRYPTOGRAM_3DS"
],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
"INTERAC",
"JCB",
"MASTERCARD",
"VISA"
]
},
"tokenization_specification": {
"type": "PAYMENT_GATEWAY",
"parameters": {
"gateway": "stripe",
"stripe:version": "2018-10-31",
"stripe:publishableKey": "pk_test_51Msk2GAGHc77EJXX78h549SX2uaOnEkUYqBfjcoD05PIpAnDkYxMn8nQ4d19im85NQuX4Z6WDyHaUw2fFTPBWsIY00Wa7oNerO"
}
}
}
]
}
}
}
```
-> Do a apple pay payment create with confirm false
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}
```
<img width="1007" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/67deb74e-e0dd-4af3-b5d9-7298d65c3e01">
-> Do payment method list for merchant
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_V1VBfr3VW6MVXaFw01sT_secret_6bByPi9DrnPk0uv6vYJj' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_cc7a8a8132a840338323ac8f7f6860d0'
```
<img width="1059" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/38f97f9d-ff51-41dc-9a06-20137f2ead1a">
-> Confirm the above create payment with `payment_id` and payment_data
```
curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: api_key' \
--data '{
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiSWJKaWp1TTRXT0lpM1BZcTRWVlpIL2wwUld1Qm5JRk5vMHBsWGp1L1E2bW9uQ0JVOE9rVHFDbnkwWDlZVVBZYzVBMXRIckE1eTV0NlpsSFVkZFJyYlY3QXIzMVVEc0NSbVlDVDRweFdEQ0oxTnF5WWYrK3NPQThZRkh5di83aUJiTnJ6K1g0Q0dwelNtelRNL2V6TUxzY2VCdHM4dkozQk05VnRGdVY2bXJsN2lPcGNHUGlNam5wK2ZkaG1OYlNHcGt0Qmt4QVRmaHlpM3VjbWNBejNjYWlMV3RSN2Yrc2owUmlzL0pBcmhuVzVZdmNodE53K2prSFBXZW9HeG1KTEFFUW1HRnZ3dGJCaWFKVFEvVnpmdEJtK3RGYkliWTBYeFdrRXdSQllIajlCVnVmbEVDaVlKK2NYLytBdVhlS2ZHZHZMQWZrNjNSYmZJQm5hTVR6dWlXZ2tEM1N5T3hJbE82MGxveHFPSmkxbkgvQXZSdFlMOUt4NWM0dzEwYnZVcENZZys4aytpdmg0aEdIdTF3PT0iLCJzaWduYXR1cmUiOiJNSUFHQ1NxR1NJYjNEUUVIQXFDQU1JQUNBUUV4RFRBTEJnbGdoa2dCWlFNRUFnRXdnQVlKS29aSWh2Y05BUWNCQUFDZ2dEQ0NBK013Z2dPSW9BTUNBUUlDQ0JaalRJc09NRmNYTUFvR0NDcUdTTTQ5QkFNQ01Ib3hMakFzQmdOVkJBTU1KVUZ3Y0d4bElFRndjR3hwWTJGMGFXOXVJRWx1ZEdWbmNtRjBhVzl1SUVOQklDMGdSek14SmpBa0JnTlZCQXNNSFVGd2NHeGxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpBZUZ3MHlOREEwTWpreE56UTNNamRhRncweU9UQTBNamd4TnpRM01qWmFNRjh4SlRBakJnTlZCQU1NSEdWall5MXpiWEF0WW5KdmEyVnlMWE5wWjI1ZlZVTTBMVkJTVDBReEZEQVNCZ05WQkFzTUMybFBVeUJUZVhOMFpXMXpNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV6QlpNQk1HQnlxR1NNNDlBZ0VHQ0NxR1NNNDlBd0VIQTBJQUJNSVZkKzNyMXNleUlZOW8zWENRb1NHTng3QzlieXdvUFlSZ2xkbEs5S1ZCRzROQ0R0Z1I4MEIrZ3pNZkhGVEQ5K3N5SU5hNjFkVHY5SktKaVQ1OER4T2pnZ0lSTUlJQ0RUQU1CZ05WSFJNQkFmOEVBakFBTUI4R0ExVWRJd1FZTUJhQUZDUHlTY1JQaytUdkorYkU5aWhzUDZLNy9TNUxNRVVHQ0NzR0FRVUZCd0VCQkRrd056QTFCZ2dyQmdFRkJRY3dBWVlwYUhSMGNEb3ZMMjlqYzNBdVlYQndiR1V1WTI5dEwyOWpjM0F3TkMxaGNIQnNaV0ZwWTJFek1ESXdnZ0VkQmdOVkhTQUVnZ0VVTUlJQkVEQ0NBUXdHQ1NxR1NJYjNZMlFGQVRDQi9qQ0J3d1lJS3dZQkJRVUhBZ0l3Z2JZTWdiTlNaV3hwWVc1alpTQnZiaUIwYUdseklHTmxjblJwWm1sallYUmxJR0o1SUdGdWVTQndZWEowZVNCaGMzTjFiV1Z6SUdGalkyVndkR0Z1WTJVZ2IyWWdkR2hsSUhSb1pXNGdZWEJ3YkdsallXSnNaU0J6ZEdGdVpHRnlaQ0IwWlhKdGN5QmhibVFnWTI5dVpHbDBhVzl1Y3lCdlppQjFjMlVzSUdObGNuUnBabWxqWVhSbElIQnZiR2xqZVNCaGJtUWdZMlZ5ZEdsbWFXTmhkR2x2YmlCd2NtRmpkR2xqWlNCemRHRjBaVzFsYm5SekxqQTJCZ2dyQmdFRkJRY0NBUllxYUhSMGNEb3ZMM2QzZHk1aGNIQnNaUzVqYjIwdlkyVnlkR2xtYVdOaGRHVmhkWFJvYjNKcGRIa3ZNRFFHQTFVZEh3UXRNQ3N3S2FBbm9DV0dJMmgwZEhBNkx5OWpjbXd1WVhCd2JHVXVZMjl0TDJGd2NHeGxZV2xqWVRNdVkzSnNNQjBHQTFVZERnUVdCQlNVVjl0djFYU0Job21KZGk5K1Y0VUg1NXRZSkRBT0JnTlZIUThCQWY4RUJBTUNCNEF3RHdZSktvWklodmRqWkFZZEJBSUZBREFLQmdncWhrak9QUVFEQWdOSkFEQkdBaUVBeHZBanl5WVV1ekE0aUtGaW1ENGFrL0VGYjFENmVNMjV1a3lpUWN3VTRsNENJUUMrUE5EZjBXSkg5a2xFZFRnT25VVENLS0VJa0tPaDNISkxpMHk0aUpnWXZEQ0NBdTR3Z2dKMW9BTUNBUUlDQ0VsdEw3ODZtTnFYTUFvR0NDcUdTTTQ5QkFNQ01HY3hHekFaQmdOVkJBTU1Fa0Z3Y0d4bElGSnZiM1FnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUI0WERURTBNRFV3TmpJek5EWXpNRm9YRFRJNU1EVXdOakl6TkRZek1Gb3dlakV1TUN3R0ExVUVBd3dsUVhCd2JHVWdRWEJ3YkdsallYUnBiMjRnU1c1MFpXZHlZWFJwYjI0Z1EwRWdMU0JITXpFbU1DUUdBMVVFQ3d3ZFFYQndiR1VnUTJWeWRHbG1hV05oZEdsdmJpQkJkWFJvYjNKcGRIa3hFekFSQmdOVkJBb01Da0Z3Y0d4bElFbHVZeTR4Q3pBSkJnTlZCQVlUQWxWVE1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRThCY1JoQm5YWklYVkdsNGxnUWQyNklDaTc5NTdyazNnamZ4TGsrRXpWdFZtV3pXdUl0Q1hkZzBpVG51NkNQMTJGODZJeTNhN1puQyt5T2dwaFA5VVJhT0I5ekNCOURCR0JnZ3JCZ0VGQlFjQkFRUTZNRGd3TmdZSUt3WUJCUVVITUFHR0ttaDBkSEE2THk5dlkzTndMbUZ3Y0d4bExtTnZiUzl2WTNOd01EUXRZWEJ3YkdWeWIyOTBZMkZuTXpBZEJnTlZIUTRFRmdRVUkvSkp4RStUNU84bjVzVDJLR3cvb3J2OUxrc3dEd1lEVlIwVEFRSC9CQVV3QXdFQi96QWZCZ05WSFNNRUdEQVdnQlM3c042aFdET0ltcVNLbWQ2K3ZldXYyc3NrcXpBM0JnTlZIUjhFTURBdU1DeWdLcUFvaGlab2RIUndPaTh2WTNKc0xtRndjR3hsTG1OdmJTOWhjSEJzWlhKdmIzUmpZV2N6TG1OeWJEQU9CZ05WSFE4QkFmOEVCQU1DQVFZd0VBWUtLb1pJaHZkalpBWUNEZ1FDQlFBd0NnWUlLb1pJemowRUF3SURad0F3WkFJd09zOXlnMUVXbWJHRyt6WERWc3Bpdi9RWDdka1BkVTJpanI3eG5JRmVRcmVKK0pqM20xbWZtTlZCRFkrZDZjTCtBakF5TGRWRUliQ2pCWGRzWGZNNE81Qm4vUmQ4TENGdGxrL0djbW1DRW05VStIcDlHNW5MbXdtSklXRUdtUThKa2gwQUFER0NBWWN3Z2dHREFnRUJNSUdHTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVd0lJRm1OTWl3NHdWeGN3Q3dZSllJWklBV1VEQkFJQm9JR1RNQmdHQ1NxR1NJYjNEUUVKQXpFTEJna3Foa2lHOXcwQkJ3RXdIQVlKS29aSWh2Y05BUWtGTVE4WERUSTBNRFV5TVRBM016TXlORm93S0FZSktvWklodmNOQVFrME1Sc3dHVEFMQmdsZ2hrZ0JaUU1FQWdHaENnWUlLb1pJemowRUF3SXdMd1lKS29aSWh2Y05BUWtFTVNJRUlEa29VdTlwZ01JUHR2R0VEZi9tSXk3LzNjSTg2b3U5eTJaZkV6RkhuRFN0TUFvR0NDcUdTTTQ5QkFNQ0JFWXdSQUlnTWdkSG9rZHNWQndya3RYRzd1VmowMm9QVVNsQllaWGVPeXJyd3RsQk5MUUNJRDdzZnZPaThZcjVWNkVyNjFqU05sKzR3ZDhpR050YUxEdFRMZjNBQ0VhNkFBQUFBQUFBIiwiaGVhZGVyIjp7InB1YmxpY0tleUhhc2giOiJ4MnFmMTFaemRXbnFCZnc0U0NyOWxIYzZRc1JQOEp6Z2xrZnU5RTVkWUpnPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRTR0bHR1ODRldG5zeWR0ZXh5RnJVeVRhN3pqbXlYcjZ3OFIraU9TUm1qUDV5ZWlWUEs4OWFoZDJYM1JtaUZtUjQxdHN4S1AwOEpBZVYrSXpvUXBnPT0iLCJ0cmFuc2FjdGlvbklkIjoiMmEzZDYyYTUzZDBmMzg1NGUwNTA0Y2RhZDU2MzlmYjA2MjJiZTI0YzY0ZDg2ZGYxMDlkMTNjZjdkNTAxNjA1MSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}'
```
<img width="1045" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/1b5c8cb4-43bf-42ea-a82f-9c6db940950b">
-> Apple pay retry connectors
<img width="1174" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/f3612f01-ee02-4687-b42c-af70eaf3e521">
-> Payment retrieve have two payment attempts
```
curl --location 'http://localhost:8080/payments/pay_V1VBfr3VW6MVXaFw01sT?expand_attempts=true' \
--header 'Accept: application/json' \
--header 'api-key: api_key'
```
<img width="720" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/705f2a0e-c057-47e1-8edf-e63139975a42">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4729
|
Bug: [FEATURE] [Iatapay] add upi qr support
### Feature Description
Add support for Upi QR code through Iatapay
### Possible Implementation
1. Add a upi intent payment id
2. Add a upi_qr payment data type
3. Do necessary contract changes
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 5f9618738b2..cd405e3ca98 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1664,7 +1664,10 @@ impl GetPaymentMethodType for CryptoData {
impl GetPaymentMethodType for UpiData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
- api_enums::PaymentMethodType::UpiCollect
+ match self {
+ Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect,
+ Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent,
+ }
}
}
impl GetPaymentMethodType for VoucherData {
@@ -2119,11 +2122,21 @@ pub struct CryptoData {
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
-pub struct UpiData {
+pub enum UpiData {
+ UpiCollect(UpiCollectData),
+ UpiIntent(UpiIntentData),
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct UpiCollectData {
#[schema(value_type = Option<String>, example = "successtest@iata")]
pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
}
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct UpiIntentData {}
+
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct SofortBilling {
/// The country associated with the billing
@@ -2960,6 +2973,11 @@ pub enum NextActionData {
/// The url for Qr code given by the connector
qr_code_url: Option<Url>,
},
+ /// Contains url to fetch Qr code data
+ FetchQrCodeInformation {
+ #[schema(value_type = String)]
+ qr_code_fetch_url: Url,
+ },
/// Contains the download url and the reference number for transaction
DisplayVoucherInformation {
#[schema(value_type = String)]
@@ -3045,6 +3063,11 @@ pub struct SdkNextActionData {
pub next_action: NextActionCall,
}
+#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct FetchQrCodeInformation {
+ pub qr_code_fetch_url: Url,
+}
+
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct BankTransferNextStepsData {
/// The instructions for performing a bank transfer
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index dc4ca6b2cb3..3df291d5681 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1430,6 +1430,7 @@ pub enum PaymentMethodType {
Trustly,
Twint,
UpiCollect,
+ UpiIntent,
Vipps,
Venmo,
Walley,
diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs
index faca2579c0a..cb37180c987 100644
--- a/crates/common_enums/src/transformers.rs
+++ b/crates/common_enums/src/transformers.rs
@@ -1854,6 +1854,7 @@ impl From<PaymentMethodType> for PaymentMethod {
PaymentMethodType::Trustly => Self::BankRedirect,
PaymentMethodType::Twint => Self::Wallet,
PaymentMethodType::UpiCollect => Self::Upi,
+ PaymentMethodType::UpiIntent => Self::Upi,
PaymentMethodType::Vipps => Self::Wallet,
PaymentMethodType::Venmo => Self::Wallet,
PaymentMethodType::Walley => Self::PayLater,
diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs
index c5f864bf770..133fee18c0d 100644
--- a/crates/euclid/src/frontend/dir/enums.rs
+++ b/crates/euclid/src/frontend/dir/enums.rs
@@ -268,6 +268,7 @@ pub enum CryptoType {
#[strum(serialize_all = "snake_case")]
pub enum UpiType {
UpiCollect,
+ UpiIntent,
}
#[derive(
diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs
index f6b156bf909..cc4c9be2a2d 100644
--- a/crates/euclid/src/frontend/dir/lowering.rs
+++ b/crates/euclid/src/frontend/dir/lowering.rs
@@ -75,6 +75,7 @@ impl From<enums::UpiType> for global_enums::PaymentMethodType {
fn from(value: enums::UpiType) -> Self {
match value {
enums::UpiType::UpiCollect => Self::UpiCollect,
+ enums::UpiType::UpiIntent => Self::UpiIntent,
}
}
}
diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs
index bcc951b0057..052561b5aab 100644
--- a/crates/euclid/src/frontend/dir/transformers.rs
+++ b/crates/euclid/src/frontend/dir/transformers.rs
@@ -109,6 +109,7 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet
}
global_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
global_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
+ global_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
global_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
global_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
global_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs
index 9dc85c103e9..7517918ed95 100644
--- a/crates/hyperswitch_domain_models/src/payment_method_data.rs
+++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs
@@ -289,10 +289,20 @@ pub struct CryptoData {
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
-pub struct UpiData {
+pub enum UpiData {
+ UpiCollect(UpiCollectData),
+ UpiIntent(UpiIntentData),
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub struct UpiCollectData {
pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
}
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+pub struct UpiIntentData {}
+
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VoucherData {
@@ -690,8 +700,12 @@ impl From<api_models::payments::CryptoData> for CryptoData {
impl From<api_models::payments::UpiData> for UpiData {
fn from(value: api_models::payments::UpiData) -> Self {
- let api_models::payments::UpiData { vpa_id } = value;
- Self { vpa_id }
+ match value {
+ api_models::payments::UpiData::UpiCollect(upi) => {
+ Self::UpiCollect(UpiCollectData { vpa_id: upi.vpa_id })
+ }
+ api_models::payments::UpiData::UpiIntent(_) => Self::UpiIntent(UpiIntentData {}),
+ }
}
}
diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs
index b32c8c23bd9..76c7381bf22 100644
--- a/crates/kgraph_utils/src/mca.rs
+++ b/crates/kgraph_utils/src/mca.rs
@@ -77,7 +77,6 @@ fn get_dir_value_payment_method(
api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)),
api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
- api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
@@ -133,6 +132,8 @@ fn get_dir_value_payment_method(
api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)),
api_enums::PaymentMethodType::CardRedirect => Ok(dirval!(CardRedirectType = CardRedirect)),
api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)),
+ api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
+ api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
}
}
diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs
index 3e43a4324f9..1bff0eac0d7 100644
--- a/crates/kgraph_utils/src/transformers.rs
+++ b/crates/kgraph_utils/src/transformers.rs
@@ -230,6 +230,7 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) {
api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)),
api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
+ api_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index c67ea2d2746..fd0688ed293 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -291,6 +291,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::CryptoData,
api_models::payments::RewardData,
api_models::payments::UpiData,
+ api_models::payments::UpiCollectData,
+ api_models::payments::UpiIntentData,
api_models::payments::VoucherData,
api_models::payments::BoletoVoucherData,
api_models::payments::AlfamartVoucherData,
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index 5e8c9ea08c0..0526eacb2e8 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -141,10 +141,10 @@ impl From<StripeWallet> for payments::WalletData {
}
impl From<StripeUpi> for payments::UpiData {
- fn from(upi: StripeUpi) -> Self {
- Self {
- vpa_id: Some(upi.vpa_id),
- }
+ fn from(upi_data: StripeUpi) -> Self {
+ Self::UpiCollect(payments::UpiCollectData {
+ vpa_id: Some(upi_data.vpa_id),
+ })
}
}
@@ -315,6 +315,18 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest {
let amount = item.amount.map(|amount| MinorUnit::new(amount).into());
+ let payment_method_data = item.payment_method_data.as_ref().map(|pmd| {
+ let payment_method_data = match pmd.payment_method_details.as_ref() {
+ Some(spmd) => Some(payments::PaymentMethodData::from(spmd.to_owned())),
+ None => get_pmd_based_on_payment_method_type(item.payment_method_types),
+ };
+
+ payments::PaymentMethodDataRequest {
+ payment_method_data,
+ billing: pmd.billing_details.clone().map(payments::Address::from),
+ }
+ });
+
let request = Ok(Self {
payment_id: item.id.map(payments::PaymentIdType::PaymentIntentId),
amount,
@@ -334,16 +346,7 @@ impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest {
phone: item.shipping.as_ref().and_then(|s| s.phone.clone()),
description: item.description,
return_url: item.return_url,
- payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| {
- pmd.payment_method_details
- .as_ref()
- .map(|spmd| payments::PaymentMethodDataRequest {
- payment_method_data: Some(payments::PaymentMethodData::from(
- spmd.to_owned(),
- )),
- billing: pmd.billing_details.clone().map(payments::Address::from),
- })
- }),
+ payment_method_data,
payment_method: item
.payment_method_data
.as_ref()
@@ -816,6 +819,9 @@ pub enum StripeNextAction {
display_to_timestamp: Option<i64>,
qr_code_url: Option<url::Url>,
},
+ FetchQrCodeInformation {
+ qr_code_fetch_url: url::Url,
+ },
DisplayVoucherInformation {
voucher_details: payments::VoucherNextStepData,
},
@@ -858,6 +864,9 @@ pub(crate) fn into_stripe_next_action(
display_to_timestamp,
qr_code_url,
},
+ payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => {
+ StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url }
+ }
payments::NextActionData::DisplayVoucherInformation { voucher_details } => {
StripeNextAction::DisplayVoucherInformation { voucher_details }
}
@@ -884,3 +893,15 @@ pub(crate) fn into_stripe_next_action(
pub struct StripePaymentRetrieveBody {
pub client_secret: Option<String>,
}
+
+//To handle payment types that have empty payment method data
+fn get_pmd_based_on_payment_method_type(
+ payment_method_type: Option<api_enums::PaymentMethodType>,
+) -> Option<payments::PaymentMethodData> {
+ match payment_method_type {
+ Some(api_enums::PaymentMethodType::UpiIntent) => Some(payments::PaymentMethodData::Upi(
+ payments::UpiData::UpiIntent(payments::UpiIntentData {}),
+ )),
+ _ => None,
+ }
+}
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index bbcafb65e9f..9a1cf58f11b 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -382,6 +382,9 @@ pub enum StripeNextAction {
display_to_timestamp: Option<i64>,
qr_code_url: Option<url::Url>,
},
+ FetchQrCodeInformation {
+ qr_code_fetch_url: url::Url,
+ },
DisplayVoucherInformation {
voucher_details: payments::VoucherNextStepData,
},
@@ -424,6 +427,9 @@ pub(crate) fn into_stripe_next_action(
display_to_timestamp,
qr_code_url,
},
+ payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => {
+ StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url }
+ }
payments::NextActionData::DisplayVoucherInformation { voucher_details } => {
StripeNextAction::DisplayVoucherInformation { voucher_details }
}
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index e2effb2e325..1a63dc50c9e 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -214,7 +214,8 @@ impl ConnectorValidation for Adyen {
| PaymentMethodType::SamsungPay
| PaymentMethodType::Evoucher
| PaymentMethodType::Cashapp
- | PaymentMethodType::UpiCollect => {
+ | PaymentMethodType::UpiCollect
+ | PaymentMethodType::UpiIntent => {
capture_method_not_supported!(connector, capture_method, payment_method_type)
}
},
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index 5daa33ab944..b36792e90ca 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -1,7 +1,8 @@
use std::collections::HashMap;
use api_models::enums::PaymentMethod;
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, ext_traits::Encode};
+use error_stack::ResultExt;
use masking::{Secret, SwitchStrategy};
use serde::{Deserialize, Serialize};
@@ -84,6 +85,13 @@ pub struct PayerInfo {
token_id: Secret<String>,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum PreferredCheckoutMethod {
+ Vpa,
+ Qr,
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IatapayPaymentsRequest {
@@ -95,7 +103,9 @@ pub struct IatapayPaymentsRequest {
locale: String,
redirect_urls: RedirectUrls,
notification_url: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
payer_info: Option<PayerInfo>,
+ preferred_checkout_method: Option<PreferredCheckoutMethod>,
}
impl
@@ -136,24 +146,31 @@ impl
| PaymentMethod::GiftCard => item.router_data.get_billing_country()?.to_string(),
};
let return_url = item.router_data.get_return_url()?;
- let payer_info = match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Upi(upi_data) => upi_data.vpa_id.map(|id| PayerInfo {
- token_id: id.switch_strategy(),
- }),
- domain::PaymentMethodData::Card(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardToken(_) => None,
- };
+ let (payer_info, preferred_checkout_method) =
+ match item.router_data.request.payment_method_data.clone() {
+ domain::PaymentMethodData::Upi(upi_type) => match upi_type {
+ domain::UpiData::UpiCollect(upi_data) => (
+ upi_data.vpa_id.map(|id| PayerInfo {
+ token_id: id.switch_strategy(),
+ }),
+ Some(PreferredCheckoutMethod::Vpa),
+ ),
+ domain::UpiData::UpiIntent(_) => (None, Some(PreferredCheckoutMethod::Qr)),
+ },
+ domain::PaymentMethodData::Card(_)
+ | domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => (None, None),
+ };
let payload = Self {
merchant_id: IatapayAuthType::try_from(&item.router_data.connector_auth_type)?
.merchant_id,
@@ -165,6 +182,7 @@ impl
redirect_urls: get_redirect_url(return_url),
payer_info,
notification_url: item.router_data.request.get_webhook_url()?,
+ preferred_checkout_method,
};
Ok(payload)
}
@@ -291,8 +309,46 @@ fn get_iatpay_response(
};
let connector_response_reference_id = response.merchant_payment_id.or(response.iata_payment_id);
- let payment_response_data = response.checkout_methods.map_or(
- types::PaymentsResponseData::TransactionResponse {
+ let payment_response_data = match response.checkout_methods {
+ Some(checkout_methods) => {
+ let (connector_metadata, redirection_data) =
+ match checkout_methods.redirect.redirect_url.ends_with("qr") {
+ true => {
+ let qr_code_info = api_models::payments::FetchQrCodeInformation {
+ qr_code_fetch_url: url::Url::parse(
+ &checkout_methods.redirect.redirect_url,
+ )
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?,
+ };
+ (
+ Some(qr_code_info.encode_to_value())
+ .transpose()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?,
+ None,
+ )
+ }
+ false => (
+ None,
+ Some(services::RedirectForm::Form {
+ endpoint: checkout_methods.redirect.redirect_url,
+ method: services::Method::Get,
+ form_fields,
+ }),
+ ),
+ };
+
+ types::PaymentsResponseData::TransactionResponse {
+ resource_id: id,
+ redirection_data,
+ mandate_reference: None,
+ connector_metadata,
+ network_txn_id: None,
+ connector_response_reference_id: connector_response_reference_id.clone(),
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }
+ }
+ None => types::PaymentsResponseData::TransactionResponse {
resource_id: id.clone(),
redirection_data: None,
mandate_reference: None,
@@ -302,21 +358,8 @@ fn get_iatpay_response(
incremental_authorization_allowed: None,
charge_id: None,
},
- |checkout_methods| types::PaymentsResponseData::TransactionResponse {
- resource_id: id,
- redirection_data: Some(services::RedirectForm::Form {
- endpoint: checkout_methods.redirect.redirect_url,
- method: services::Method::Get,
- form_fields,
- }),
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: connector_response_reference_id.clone(),
- incremental_authorization_allowed: None,
- charge_id: None,
- },
- );
+ };
+
Ok((status, error, payment_response_data))
}
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 5c174c69e3b..48b6616a64e 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -398,6 +398,7 @@ impl
| common_enums::PaymentMethodType::Trustly
| common_enums::PaymentMethodType::Twint
| common_enums::PaymentMethodType::UpiCollect
+ | common_enums::PaymentMethodType::UpiIntent
| common_enums::PaymentMethodType::Venmo
| common_enums::PaymentMethodType::Vipps
| common_enums::PaymentMethodType::Walley
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 55b0d7f4675..83bca39626f 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -675,6 +675,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType {
| enums::PaymentMethodType::Paypal
| enums::PaymentMethodType::Pix
| enums::PaymentMethodType::UpiCollect
+ | enums::PaymentMethodType::UpiIntent
| enums::PaymentMethodType::Cashapp
| enums::PaymentMethodType::Oxxo => Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index a39f0deb3ca..db99ff590cd 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1009,6 +1009,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
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,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 973ca4b2266..6e3f6a9bf6e 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2338,7 +2338,7 @@ pub fn validate_payment_method_type_against_payment_method(
),
api_enums::PaymentMethod::Upi => matches!(
payment_method_type,
- api_enums::PaymentMethodType::UpiCollect
+ api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent
),
api_enums::PaymentMethod::Voucher => matches!(
payment_method_type,
@@ -4252,9 +4252,9 @@ pub fn get_key_params_for_surcharge_details(
)),
api_models::payments::PaymentMethodData::MandatePayment => None,
api_models::payments::PaymentMethodData::Reward => None,
- api_models::payments::PaymentMethodData::Upi(_) => Some((
+ api_models::payments::PaymentMethodData::Upi(upi_data) => Some((
common_enums::PaymentMethod::Upi,
- common_enums::PaymentMethodType::UpiCollect,
+ upi_data.get_payment_method_type(),
None,
)),
api_models::payments::PaymentMethodData::Voucher(voucher) => Some((
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 7f6b0cc1f61..8f6af2f89bc 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -541,6 +541,9 @@ where
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())?;
@@ -550,6 +553,7 @@ where
|| next_action_containing_qr_code_url.is_some()
|| next_action_containing_wait_screen.is_some()
|| papal_sdk_next_action.is_some()
+ || next_action_containing_fetch_qr_code_url.is_some()
|| payment_data.authentication.is_some()
{
next_action_response = bank_transfer_next_steps
@@ -566,6 +570,11 @@ where
.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
@@ -899,6 +908,18 @@ pub fn paypal_sdk_next_steps_check(
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 wait_screen_next_steps_check(
payment_attempt: storage::PaymentAttempt,
) -> RouterResult<Option<api_models::payments::WaitScreenInstructions>> {
@@ -1108,8 +1129,8 @@ impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::paymen
display_to_timestamp,
} => Self::QrCodeInformation {
qr_code_url: Some(qr_code_url),
- display_to_timestamp,
image_data_url: None,
+ display_to_timestamp,
},
}
}
diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs
index 7b1f3365490..51d3210a70f 100644
--- a/crates/router/src/types/domain/payments.rs
+++ b/crates/router/src/types/domain/payments.rs
@@ -5,6 +5,6 @@ pub use hyperswitch_domain_models::payment_method_data::{
GooglePayPaymentMethodInfo, GooglePayRedirectData, GooglePayThirdPartySdkData,
GooglePayWalletData, GpayTokenizationData, IndomaretVoucherData, KakaoPayRedirection,
MbWayRedirection, PayLaterData, PaymentMethodData, SamsungPayWalletData,
- SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, VoucherData, WalletData,
- WeChatPayQr,
+ SepaAndBacsBillingDetails, SwishQrData, TouchNGoRedirection, UpiCollectData, UpiData,
+ UpiIntentData, VoucherData, WalletData, WeChatPayQr,
};
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index da8e8c621b7..59ec42abfd2 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -461,7 +461,9 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod {
| api_enums::PaymentMethodType::Trustly
| api_enums::PaymentMethodType::Bizum
| api_enums::PaymentMethodType::Interac => Self::BankRedirect,
- api_enums::PaymentMethodType::UpiCollect => Self::Upi,
+ api_enums::PaymentMethodType::UpiCollect | api_enums::PaymentMethodType::UpiIntent => {
+ Self::Upi
+ }
api_enums::PaymentMethodType::CryptoCurrency => Self::Crypto,
api_enums::PaymentMethodType::Ach
| api_enums::PaymentMethodType::Sepa
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index b87b516de28..30bd356cd45 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -11757,6 +11757,25 @@
}
}
},
+ {
+ "type": "object",
+ "description": "Contains url to fetch Qr code data",
+ "required": [
+ "qr_code_fetch_url",
+ "type"
+ ],
+ "properties": {
+ "qr_code_fetch_url": {
+ "type": "string"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "fetch_qr_code_information"
+ ]
+ }
+ }
+ },
{
"type": "object",
"description": "Contains the download url and the reference number for transaction",
@@ -13529,6 +13548,7 @@
"trustly",
"twint",
"upi_collect",
+ "upi_intent",
"vipps",
"venmo",
"walley",
@@ -18692,7 +18712,7 @@
},
"additionalProperties": false
},
- "UpiData": {
+ "UpiCollectData": {
"type": "object",
"properties": {
"vpa_id": {
@@ -18702,6 +18722,35 @@
}
}
},
+ "UpiData": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "upi_collect"
+ ],
+ "properties": {
+ "upi_collect": {
+ "$ref": "#/components/schemas/UpiCollectData"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "upi_intent"
+ ],
+ "properties": {
+ "upi_intent": {
+ "$ref": "#/components/schemas/UpiIntentData"
+ }
+ }
+ }
+ ]
+ },
+ "UpiIntentData": {
+ "type": "object"
+ },
"ValueType": {
"oneOf": [
{
|
2024-05-22T10:09:28Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR introduces a new payment_method_type: `upi_intent` and a new payment_method_data: `upi_qr: {}` along with iatapay qr code implementation.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
_Note:Test through stripe compatibility layer_
1. Create a upi qr payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ZLiIlOCsh5GUTiRJCCSc6lOIXpo0tTGuROyxvZokpKSIl5Lh5mCYwBB9IZV3Jno2' \
--data-raw '{
"amount": 5000,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 5000,
"customer_id": "IatapayCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "upi",
"payment_method_type": "upi_intent",
"payment_method_data": {
"upi": {
"upi_intent": {
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "IN",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response
```
{
"payment_id": "pay_ZBLXkfFi0wcdBPrQkKPL",
"merchant_id": "merchant_1716310637",
"status": "requires_customer_action",
"amount": 5000,
"net_amount": 5000,
"amount_capturable": 5000,
"amount_received": null,
"connector": "iatapay",
"client_secret": "pay_ZBLXkfFi0wcdBPrQkKPL_secret_YYAnlcRyF7ZX3r82WtjL",
"created": "2024-05-22T10:04:05.468Z",
"currency": "INR",
"customer_id": "IatapayCustomer",
"customer": {
"id": "IatapayCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "upi",
"payment_method_data": {
"upi": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "IN",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "fetch_qr_code_information",
"qr_code_fetch_url": "https://sandbox.iata-pay.iata.org/api/v1/payments/PJHE6F45O1D7M/checkout/api/qr"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "upi_intent",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "IatapayCustomer",
"created_at": 1716372245,
"expires": 1716375845,
"secret": "epk_41f95816c9844c2e9c8672ec5bc91d65"
},
"manual_retry_allowed": null,
"connector_transaction_id": "P1D74RYCPET6J",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_ZBLXkfFi0wcdBPrQkKPL_1",
"payment_link": null,
"profile_id": "pro_aqLkyMdeFcYrp3v3yPd8",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nLDpyk2OF9mrlivQTJnS",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T10:19:05.468Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-22T10:04:08.642Z",
"frm_metadata": null
}
```
2. Create a upi payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:""' \
--data-raw '{
"amount": 5000,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 5000,
"customer_id": "IatapayCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "upi",
"payment_method_type": "upi_collect",
"payment_method_data": {
"upi": {
"upi_collect": {
"vpa_id": "successtest@ita"
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "IN",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response
```
{
"payment_id": "pay_VfMfCw7jxtbHNc5xvF4Z",
"merchant_id": "merchant_1716310637",
"status": "requires_customer_action",
"amount": 5000,
"net_amount": 5000,
"amount_capturable": 5000,
"amount_received": null,
"connector": "iatapay",
"client_secret": "pay_VfMfCw7jxtbHNc5xvF4Z_secret_lMsdWF0m50OBBvxe1fl7",
"created": "2024-05-22T09:54:19.813Z",
"currency": "INR",
"customer_id": "IatapayCustomer",
"customer": {
"id": "IatapayCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "upi",
"payment_method_data": {
"upi": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "IN",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_VfMfCw7jxtbHNc5xvF4Z/merchant_1716310637/pay_VfMfCw7jxtbHNc5xvF4Z_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "upi_collect",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "IatapayCustomer",
"created_at": 1716371659,
"expires": 1716375259,
"secret": "epk_7bb67ee9c3304c8a9458ba6ef2488225"
},
"manual_retry_allowed": null,
"connector_transaction_id": "P46Y265SXCTXZ",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_VfMfCw7jxtbHNc5xvF4Z_1",
"payment_link": null,
"profile_id": "pro_aqLkyMdeFcYrp3v3yPd8",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nLDpyk2OF9mrlivQTJnS",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T10:09:19.813Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-22T09:54:21.635Z",
"frm_metadata": null
}
```
Stimulate Terminal status (for Failed - `FAILED`)
```
curl --location --request PUT 'https://sandbox.iata-pay.iata.org/api/v2/payments/P50G9SL4HD0A7/simulate' \
--header 'Content-Type: application/json' \
--header 'Authorization: access_token' \
--data '{
"status": "SETTLED"
}'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
b3d4d13db81143cf663142d8bd8fdf95b0882b3f
|
_Note:Test through stripe compatibility layer_
1. Create a upi qr payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ZLiIlOCsh5GUTiRJCCSc6lOIXpo0tTGuROyxvZokpKSIl5Lh5mCYwBB9IZV3Jno2' \
--data-raw '{
"amount": 5000,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 5000,
"customer_id": "IatapayCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "upi",
"payment_method_type": "upi_intent",
"payment_method_data": {
"upi": {
"upi_intent": {
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "IN",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response
```
{
"payment_id": "pay_ZBLXkfFi0wcdBPrQkKPL",
"merchant_id": "merchant_1716310637",
"status": "requires_customer_action",
"amount": 5000,
"net_amount": 5000,
"amount_capturable": 5000,
"amount_received": null,
"connector": "iatapay",
"client_secret": "pay_ZBLXkfFi0wcdBPrQkKPL_secret_YYAnlcRyF7ZX3r82WtjL",
"created": "2024-05-22T10:04:05.468Z",
"currency": "INR",
"customer_id": "IatapayCustomer",
"customer": {
"id": "IatapayCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "upi",
"payment_method_data": {
"upi": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "IN",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "fetch_qr_code_information",
"qr_code_fetch_url": "https://sandbox.iata-pay.iata.org/api/v1/payments/PJHE6F45O1D7M/checkout/api/qr"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "upi_intent",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "IatapayCustomer",
"created_at": 1716372245,
"expires": 1716375845,
"secret": "epk_41f95816c9844c2e9c8672ec5bc91d65"
},
"manual_retry_allowed": null,
"connector_transaction_id": "P1D74RYCPET6J",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_ZBLXkfFi0wcdBPrQkKPL_1",
"payment_link": null,
"profile_id": "pro_aqLkyMdeFcYrp3v3yPd8",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nLDpyk2OF9mrlivQTJnS",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T10:19:05.468Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-22T10:04:08.642Z",
"frm_metadata": null
}
```
2. Create a upi payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:""' \
--data-raw '{
"amount": 5000,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 5000,
"customer_id": "IatapayCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "upi",
"payment_method_type": "upi_collect",
"payment_method_data": {
"upi": {
"upi_collect": {
"vpa_id": "successtest@ita"
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "IN",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response
```
{
"payment_id": "pay_VfMfCw7jxtbHNc5xvF4Z",
"merchant_id": "merchant_1716310637",
"status": "requires_customer_action",
"amount": 5000,
"net_amount": 5000,
"amount_capturable": 5000,
"amount_received": null,
"connector": "iatapay",
"client_secret": "pay_VfMfCw7jxtbHNc5xvF4Z_secret_lMsdWF0m50OBBvxe1fl7",
"created": "2024-05-22T09:54:19.813Z",
"currency": "INR",
"customer_id": "IatapayCustomer",
"customer": {
"id": "IatapayCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "upi",
"payment_method_data": {
"upi": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "IN",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_VfMfCw7jxtbHNc5xvF4Z/merchant_1716310637/pay_VfMfCw7jxtbHNc5xvF4Z_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "upi_collect",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "IatapayCustomer",
"created_at": 1716371659,
"expires": 1716375259,
"secret": "epk_7bb67ee9c3304c8a9458ba6ef2488225"
},
"manual_retry_allowed": null,
"connector_transaction_id": "P46Y265SXCTXZ",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_VfMfCw7jxtbHNc5xvF4Z_1",
"payment_link": null,
"profile_id": "pro_aqLkyMdeFcYrp3v3yPd8",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_nLDpyk2OF9mrlivQTJnS",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-22T10:09:19.813Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-22T09:54:21.635Z",
"frm_metadata": null
}
```
Stimulate Terminal status (for Failed - `FAILED`)
```
curl --location --request PUT 'https://sandbox.iata-pay.iata.org/api/v2/payments/P50G9SL4HD0A7/simulate' \
--header 'Content-Type: application/json' \
--header 'Authorization: access_token' \
--data '{
"status": "SETTLED"
}'
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4719
|
Bug: [ENHANCEMENT] Make `redis_interface` crate agnostic of `router_env` dependencies
|
diff --git a/Cargo.lock b/Cargo.lock
index d5dc4e2ee9f..e6278079b20 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5365,11 +5365,11 @@ dependencies = [
"error-stack",
"fred",
"futures 0.3.30",
- "router_env",
"serde",
"thiserror",
"tokio 1.37.0",
"tokio-stream",
+ "tracing",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 82687a32ba6..fc2095275d3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -5,6 +5,9 @@ package.edition = "2021"
package.rust-version = "1.70"
package.license = "Apache-2.0"
+[workspace.dependencies]
+tracing = { version = "0.1.40" }
+
[profile.release]
strip = true
lto = true
diff --git a/crates/redis_interface/Cargo.toml b/crates/redis_interface/Cargo.toml
index 1fb74be79d9..d55ff86bcea 100644
--- a/crates/redis_interface/Cargo.toml
+++ b/crates/redis_interface/Cargo.toml
@@ -15,10 +15,10 @@ serde = { version = "1.0.197", features = ["derive"] }
thiserror = "1.0.58"
tokio = "1.37.0"
tokio-stream = {version = "0.1.15", features = ["sync"]}
+tracing = { workspace = true }
# First party crates
common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext"] }
-router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
[dev-dependencies]
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] }
diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs
index 46e3a35fd33..504820822c0 100644
--- a/crates/redis_interface/src/commands.rs
+++ b/crates/redis_interface/src/commands.rs
@@ -23,7 +23,7 @@ use fred::{
},
};
use futures::StreamExt;
-use router_env::{instrument, logger, tracing};
+use tracing::instrument;
use crate::{
errors,
@@ -379,7 +379,7 @@ impl super::RedisConnectionPool {
Some(futures::stream::iter(v))
}
Err(err) => {
- logger::error!(?err);
+ tracing::error!(?err);
None
}
}
diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs
index 0ab1ea394c9..df74d728331 100644
--- a/crates/redis_interface/src/lib.rs
+++ b/crates/redis_interface/src/lib.rs
@@ -26,7 +26,6 @@ use common_utils::errors::CustomResult;
use error_stack::ResultExt;
pub use fred::interfaces::PubsubInterface;
use fred::{interfaces::ClientLike, prelude::EventInterface};
-use router_env::logger;
pub use self::types::*;
@@ -189,10 +188,10 @@ impl RedisConnectionPool {
let mut error_rx = futures::stream::select_all(error_rxs);
loop {
if let Some(Ok(error)) = error_rx.next().await {
- logger::error!(?error, "Redis protocol or connection error");
+ tracing::error!(?error, "Redis protocol or connection error");
if self.pool.state() == fred::types::ClientState::Disconnected {
if tx.send(()).is_err() {
- logger::error!("The redis shutdown signal sender failed to signal");
+ tracing::error!("The redis shutdown signal sender failed to signal");
}
self.is_redis_available
.store(false, atomic::Ordering::SeqCst);
@@ -205,7 +204,7 @@ impl RedisConnectionPool {
pub async fn on_unresponsive(&self) {
let _ = self.pool.clients().iter().map(|client| {
client.on_unresponsive(|server| {
- logger::warn!(redis_server =?server.host, "Redis server is unresponsive");
+ tracing::warn!(redis_server =?server.host, "Redis server is unresponsive");
Ok(())
})
});
diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml
index 3b95d5f22fd..b9b1184fedf 100644
--- a/crates/router_env/Cargo.toml
+++ b/crates/router_env/Cargo.toml
@@ -22,7 +22,7 @@ serde_path_to_error = "0.1.16"
strum = { version = "0.26.2", features = ["derive"] }
time = { version = "0.3.35", default-features = false, features = ["formatting"] }
tokio = { version = "1.37.0" }
-tracing = { version = "0.1.40" }
+tracing = { workspace = true }
tracing-actix-web = { version = "0.7.10", features = ["opentelemetry_0_19", "uuid_v7"], optional = true }
tracing-appender = { version = "0.2.3" }
tracing-attributes = "0.1.27"
|
2024-05-21T12:10:21Z
|
…ndency for redis_interface
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR removes `router_env` as a dependency of `redis_interface` crate. To accomplish this we declare `tracing` as a workspace dependency and use that individually in `redis_interface` and `router_env`.
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
This is done to make `redis_interface` more self-sufficient and improve its usage as a autonomous dependency.
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
This is dependency relocation, no domain logic or framework code was changed
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2e79ee0615292182111586fda7655dd9a796ef4f
|
This is dependency relocation, no domain logic or framework code was changed
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4724
|
Bug: [FEATURE] Add support for external 3ds authentication in cybersource.
### Feature Description
Currenctly hyperswitch supports 3ds authenticated payments through cybersource. But we cannot complete 3ds authentication through a separate authentication provider(eg: netcetera). and then do payment authorization through cybersource.
### Possible Implementation
This feature is already supported by NMI and Checkout. Similar solution can be used here.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 59a85841212..4d5b709bba3 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -244,10 +244,9 @@ impl Connector {
| Self::Riskified
| Self::Threedsecureio
| Self::Netcetera
- | Self::Cybersource
| Self::Noon
| Self::Stripe => false,
- Self::Checkout | Self::Nmi => true,
+ Self::Checkout | Self::Nmi| Self::Cybersource => true,
}
}
}
diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs
index 9b7c4c96ee0..71a16dcb863 100644
--- a/crates/diesel_models/src/authentication.rs
+++ b/crates/diesel_models/src/authentication.rs
@@ -42,6 +42,7 @@ pub struct Authentication {
pub profile_id: String,
pub payment_id: Option<String>,
pub merchant_connector_id: String,
+ pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
}
@@ -87,6 +88,7 @@ pub struct AuthenticationNew {
pub profile_id: String,
pub payment_id: Option<String>,
pub merchant_connector_id: String,
+ pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
}
@@ -115,6 +117,7 @@ pub enum AuthenticationUpdate {
acs_trans_id: Option<String>,
acs_signed_content: Option<String>,
authentication_status: common_enums::AuthenticationStatus,
+ ds_trans_id: Option<String>,
},
PostAuthenticationUpdate {
trans_status: common_enums::TransactionStatus,
@@ -162,6 +165,7 @@ pub struct AuthenticationUpdateInternal {
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
+ pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
}
@@ -193,6 +197,7 @@ impl Default for AuthenticationUpdateInternal {
acs_reference_number: Default::default(),
acs_trans_id: Default::default(),
acs_signed_content: Default::default(),
+ ds_trans_id: Default::default(),
directory_server_id: Default::default(),
}
}
@@ -226,6 +231,7 @@ impl AuthenticationUpdateInternal {
acs_reference_number,
acs_trans_id,
acs_signed_content,
+ ds_trans_id,
directory_server_id,
} = self;
Authentication {
@@ -258,6 +264,7 @@ impl AuthenticationUpdateInternal {
acs_reference_number: acs_reference_number.or(source.acs_reference_number),
acs_trans_id: acs_trans_id.or(source.acs_trans_id),
acs_signed_content: acs_signed_content.or(source.acs_signed_content),
+ ds_trans_id: ds_trans_id.or(source.ds_trans_id),
directory_server_id: directory_server_id.or(source.directory_server_id),
..source
}
@@ -336,6 +343,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {
acs_trans_id,
acs_signed_content,
authentication_status,
+ ds_trans_id,
} => Self {
cavv: authentication_value,
trans_status: Some(trans_status),
@@ -346,6 +354,7 @@ impl From<AuthenticationUpdate> for AuthenticationUpdateInternal {
acs_trans_id,
acs_signed_content,
authentication_status: Some(authentication_status),
+ ds_trans_id,
..Default::default()
},
AuthenticationUpdate::PostAuthenticationUpdate {
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index de5b536dcda..6074fdc10b7 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -115,6 +115,8 @@ diesel::table! {
payment_id -> Nullable<Varchar>,
#[max_length = 128]
merchant_connector_id -> Varchar,
+ #[max_length = 64]
+ ds_trans_id -> Nullable<Varchar>,
#[max_length = 128]
directory_server_id -> Nullable<Varchar>,
}
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 56a4ba739c0..c8e68586dad 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -1,7 +1,7 @@
pub mod authentication;
pub mod fraud_check;
use api_models::payments::RequestSurchargeDetails;
-use common_utils::{consts, errors, ext_traits::OptionExt, pii};
+use common_utils::{consts, errors, ext_traits::OptionExt, pii, types as common_types};
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
use masking::Secret;
@@ -447,7 +447,8 @@ pub struct AuthenticationData {
pub eci: Option<String>,
pub cavv: String,
pub threeds_server_transaction_id: String,
- pub message_version: String,
+ pub message_version: common_types::SemanticVersion,
+ pub ds_trans_id: Option<String>,
}
#[derive(Debug, Clone)]
diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs
index 3d89163b3da..57d579e1a0a 100644
--- a/crates/hyperswitch_domain_models/src/router_response_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_response_types.rs
@@ -219,6 +219,7 @@ pub enum AuthenticationResponseData {
authn_flow_type: AuthNFlowType,
authentication_value: Option<String>,
trans_status: common_enums::TransactionStatus,
+ ds_trans_id: Option<String>,
},
PostAuthNResponse {
trans_status: common_enums::TransactionStatus,
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index c92d75f1de8..10918b7bc6e 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -383,7 +383,7 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
eci: authentication_data.and_then(|auth| auth.eci.clone()),
cryptogram: authentication_data.map(|auth| auth.cavv.clone()),
xid: authentication_data.map(|auth| auth.threeds_server_transaction_id.clone()),
- version: authentication_data.map(|auth| auth.message_version.clone()),
+ version: authentication_data.map(|auth| auth.message_version.to_string()),
},
enums::AuthenticationType::NoThreeDs => CheckoutThreeDS {
enabled: false,
diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs
index 43e5660d2b9..3cccb8dcf5c 100644
--- a/crates/router/src/connector/cybersource.rs
+++ b/crates/router/src/connector/cybersource.rs
@@ -848,6 +848,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
if req.is_three_ds()
&& req.request.is_card()
&& req.request.connector_mandate_id().is_none()
+ && req.request.authentication_data.is_none()
{
Ok(format!(
"{}risk/v1/authentication-setups",
@@ -875,6 +876,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
if req.is_three_ds()
&& req.request.is_card()
&& req.request.connector_mandate_id().is_none()
+ && req.request.authentication_data.is_none()
{
let connector_req =
cybersource::CybersourceAuthSetupRequest::try_from(&connector_router_data)?;
@@ -915,6 +917,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
if data.is_three_ds()
&& data.request.is_card()
&& data.request.connector_mandate_id().is_none()
+ && data.request.authentication_data.is_none()
{
let response: cybersource::CybersourceAuthSetupResponse = res
.response
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index f1774a0de39..4527ea3950a 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -6,7 +6,7 @@ use api_models::{
};
use base64::Engine;
use common_enums::FutureUsage;
-use common_utils::{ext_traits::ValueExt, pii};
+use common_utils::{ext_traits::ValueExt, pii, types::SemanticVersion};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
@@ -261,7 +261,16 @@ pub struct CybersourceConsumerAuthInformation {
xid: Option<String>,
directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<String>,
+ /// This field specifies the 3ds version
+ pa_specification_version: Option<SemanticVersion>,
+ /// Verification response enrollment status.
+ ///
+ /// This field is supported only on Asia, Middle East, and Africa Gateway.
+ ///
+ /// For external authentication, this field will always be "Y"
+ veres_enrolled: Option<String>,
}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantDefinedInformation {
@@ -655,6 +664,19 @@ impl
} else {
(None, None, None)
};
+ // this logic is for external authenticated card
+ let commerce_indicator_for_external_authentication = item
+ .router_data
+ .request
+ .authentication_data
+ .as_ref()
+ .and_then(|authn_data| {
+ authn_data
+ .eci
+ .clone()
+ .map(|eci| get_commerce_indicator_for_external_authentication(network, eci))
+ });
+
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
@@ -665,11 +687,62 @@ impl
action_token_types,
authorization_options,
capture_options: None,
- commerce_indicator,
+ commerce_indicator: commerce_indicator_for_external_authentication
+ .unwrap_or(commerce_indicator),
})
}
}
+fn get_commerce_indicator_for_external_authentication(
+ card_network: Option<String>,
+ eci: String,
+) -> String {
+ let card_network_lower_case = card_network
+ .as_ref()
+ .map(|card_network| card_network.to_lowercase());
+ match eci.as_str() {
+ "00" | "01" | "02" => {
+ if matches!(
+ card_network_lower_case.as_deref(),
+ Some("mastercard") | Some("maestro")
+ ) {
+ "spa"
+ } else {
+ "internet"
+ }
+ }
+ "05" => match card_network_lower_case.as_deref() {
+ Some("amex") => "aesk",
+ Some("discover") => "dipb",
+ Some("mastercard") => "spa",
+ Some("visa") => "vbv",
+ Some("diners") => "pb",
+ Some("upi") => "up3ds",
+ _ => "internet",
+ },
+ "06" => match card_network_lower_case.as_deref() {
+ Some("amex") => "aesk_attempted",
+ Some("discover") => "dipb_attempted",
+ Some("mastercard") => "spa",
+ Some("visa") => "vbv_attempted",
+ Some("diners") => "pb_attempted",
+ Some("upi") => "up3ds_attempted",
+ _ => "internet",
+ },
+ "07" => match card_network_lower_case.as_deref() {
+ Some("amex") => "internet",
+ Some("discover") => "internet",
+ Some("mastercard") => "spa",
+ Some("visa") => "vbv_failure",
+ Some("diners") => "internet",
+ Some("upi") => "up3ds_failure",
+ _ => "internet",
+ },
+ _ => "vbv_failure",
+ }
+ .to_string()
+}
+
impl
From<(
&CybersourceRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
@@ -852,12 +925,39 @@ impl
Vec::<MerchantDefinedInformation>::foreign_from(metadata.peek().to_owned())
});
+ let consumer_authentication_information = item
+ .router_data
+ .request
+ .authentication_data
+ .as_ref()
+ .map(|authn_data| {
+ let (ucaf_authentication_data, cavv) =
+ if ccard.card_network == Some(common_enums::CardNetwork::Mastercard) {
+ (Some(Secret::new(authn_data.cavv.clone())), None)
+ } else {
+ (None, Some(authn_data.cavv.clone()))
+ };
+ CybersourceConsumerAuthInformation {
+ ucaf_collection_indicator: None,
+ cavv,
+ ucaf_authentication_data,
+ xid: Some(authn_data.threeds_server_transaction_id.clone()),
+ directory_server_transaction_id: authn_data
+ .ds_trans_id
+ .clone()
+ .map(Secret::new),
+ specification_version: None,
+ pa_specification_version: Some(authn_data.message_version.clone()),
+ veres_enrolled: Some("Y".to_string()),
+ }
+ });
+
Ok(Self {
processing_information,
payment_information,
order_information,
client_reference_information,
- consumer_authentication_information: None,
+ consumer_authentication_information,
merchant_defined_information,
})
}
@@ -922,6 +1022,8 @@ impl
.three_ds_data
.directory_server_transaction_id,
specification_version: three_ds_info.three_ds_data.specification_version,
+ pa_specification_version: None,
+ veres_enrolled: None,
});
let merchant_defined_information =
@@ -1000,6 +1102,8 @@ impl
xid: None,
directory_server_transaction_id: None,
specification_version: None,
+ pa_specification_version: None,
+ veres_enrolled: None,
}),
merchant_defined_information,
})
@@ -1131,6 +1235,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
xid: None,
directory_server_transaction_id: None,
specification_version: None,
+ pa_specification_version: None,
+ veres_enrolled: None,
},
),
})
diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs
index fffacc3ea4d..25ed7c5271e 100644
--- a/crates/router/src/connector/netcetera/transformers.rs
+++ b/crates/router/src/connector/netcetera/transformers.rs
@@ -167,6 +167,7 @@ impl
authn_flow_type,
authentication_value: response.authentication_value,
trans_status: response.trans_status,
+ ds_trans_id: response.authentication_response.ds_trans_id,
},
)
}
@@ -646,6 +647,8 @@ pub struct AuthenticationResponse {
pub acs_reference_number: Option<String>,
#[serde(rename = "acsTransID")]
pub acs_trans_id: Option<String>,
+ #[serde(rename = "dsTransID")]
+ pub ds_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
}
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 2a8498bfbad..44836002024 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -625,7 +625,7 @@ impl TryFrom<(&domain::payments::Card, &types::PaymentsAuthorizeData)> for Payme
cavv: Some(auth_data.cavv.clone()),
eci: auth_data.eci.clone(),
cardholder_auth: None,
- three_ds_version: Some(auth_data.message_version.clone()),
+ three_ds_version: Some(auth_data.message_version.to_string()),
directory_server_id: Some(auth_data.threeds_server_transaction_id.clone().into()),
};
diff --git a/crates/router/src/connector/threedsecureio/transformers.rs b/crates/router/src/connector/threedsecureio/transformers.rs
index fe26e509c12..242d0dee946 100644
--- a/crates/router/src/connector/threedsecureio/transformers.rs
+++ b/crates/router/src/connector/threedsecureio/transformers.rs
@@ -187,6 +187,7 @@ impl
types::authentication::AuthNFlowType::Frictionless
},
authentication_value: response.authentication_value,
+ ds_trans_id: Some(response.ds_trans_id),
},
)
}
diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs
index 0152fb4321d..f67f66bfffb 100644
--- a/crates/router/src/core/authentication/utils.rs
+++ b/crates/router/src/core/authentication/utils.rs
@@ -84,6 +84,7 @@ pub async fn update_trackers<F: Clone, Req>(
authn_flow_type,
authentication_value,
trans_status,
+ ds_trans_id,
} => {
let authentication_status =
common_enums::AuthenticationStatus::foreign_from(trans_status.clone());
@@ -97,6 +98,7 @@ pub async fn update_trackers<F: Clone, Req>(
acs_signed_content: authn_flow_type.get_acs_signed_content(),
authentication_type: authn_flow_type.get_decoupled_authentication_type(),
authentication_status,
+ ds_trans_id,
}
}
AuthenticationResponseData::PostAuthNResponse {
@@ -183,6 +185,7 @@ pub async fn create_new_authentication(
profile_id,
payment_id,
merchant_connector_id,
+ ds_trans_id: None,
directory_server_id: None,
};
state
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index d39527b4229..92c9eec5ff8 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -369,7 +369,8 @@ impl ForeignTryFrom<&storage::Authentication> for AuthenticationData {
eci: authentication.eci.clone(),
cavv,
threeds_server_transaction_id,
- message_version: message_version.to_string(),
+ message_version,
+ ds_trans_id: authentication.ds_trans_id.clone(),
})
} else {
Err(errors::ApiErrorResponse::PaymentAuthenticationFailed { data: None }.into())
diff --git a/crates/router/src/db/authentication.rs b/crates/router/src/db/authentication.rs
index 4eff3dfdbfd..cd3bb663ec9 100644
--- a/crates/router/src/db/authentication.rs
+++ b/crates/router/src/db/authentication.rs
@@ -147,6 +147,7 @@ impl AuthenticationInterface for MockDb {
profile_id: authentication.profile_id,
payment_id: authentication.payment_id,
merchant_connector_id: authentication.merchant_connector_id,
+ ds_trans_id: authentication.ds_trans_id,
directory_server_id: authentication.directory_server_id,
};
authentications.push(authentication.clone());
diff --git a/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/down.sql b/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/down.sql
new file mode 100644
index 00000000000..146b91185c2
--- /dev/null
+++ b/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE authentication DROP COLUMN If EXISTS ds_trans_id;
\ No newline at end of file
diff --git a/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/up.sql b/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/up.sql
new file mode 100644
index 00000000000..b02613777c8
--- /dev/null
+++ b/migrations/2024-05-21-065403_add_ds_trans_id_to_authentication_table/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE authentication ADD COLUMN IF NOT EXISTS ds_trans_id VARCHAR(64);
\ No newline at end of file
|
2024-05-21T11:09:06Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
add support for external authentication for cybersource.
After this change is merged, we'll be able to authenticate a payment through an external 3ds authentication(threedsecureio or netcetera) and authorise the same payment through cybersource.
Other changes:
Added `ds_trans_id` field to `authentication` table since it is required for authorization through cybersource.
### Additional Changes
- [ ] This PR modifies the API contract
- [x] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Ran cybersource postman collection to make sure existing 3ds flow is not affected.
<img width="785" alt="Screenshot 2024-05-23 at 1 00 07 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/c210e8ce-1864-444d-8f81-2ef3a7133160">
curls:
1. Create a cybersource connector and netcetera authentication connector.
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "",
"key1": "",
"api_secret": ""
},
"test_mode": false,
"disabled": false,
"business_country": "US",
"business_label": "default",
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "authentication_processor",
"business_country": "US",
"business_label": "default",
"connector_name": "netcetera",
"connector_account_details": {
"auth_type": "CertificateAuth",
"certificate": "",
"private_key": ""
},
"test_mode": true,
"disabled": false,
"metadata": {
"mcc": "5411",
"merchant_country_code": "840",
"merchant_name": "Dummy Merchant",
"endpoint_prefix": "flowbird",
"three_ds_requestor_name": "juspay-prev",
"three_ds_requestor_id": "juspay-prev",
"pull_mechanism_for_external_3ds_enabled": false
}
}'
```
2. Create a payment with "request_external_three_ds_authentication": true, and "authentication_type": "three_ds",
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mv6wkxquIeO6WDvY49Mpd4hullQ4CW05hBRT7tlIX4EOS5NaG5fmDzuY5NqacvXT' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "123456789",
"country_code": "12"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "123456789",
"country_code": "12"
}
},
"request_external_three_ds_authentication": true,
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
3. Confirm the payment
```
curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_d777ba4dfb764db2a6f851870a00a7e5' \
--data '{
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "115.99.183.2"
},
"client_secret": "pay_XPc0gwoIZLYpMBKI8Yng_secret_vRjk6g87hvftbO9z18BO",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4929251897047956",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
}
}'
```
4. Authenticate the payment.
```
curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/3ds/authentication' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_d777ba4dfb764db2a6f851870a00a7e5' \
--data '{
"client_secret": "pay_XPc0gwoIZLYpMBKI8Yng_secret_vRjk6g87hvftbO9z18BO",
"device_channel": "BRW",
"threeds_method_comp_ind": "N"
}'
```
5. Authorize the payment.
```
curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/authorize/checkout' \
--header 'Content-Type: application/json' \
--data '{
}'
```
6. Retrive the payment.
```
curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mv6wkxquIeO6WDvY49Mpd4hullQ4CW05hBRT7tlIX4EOS5NaG5fmDzuY5NqacvXT'
```
Payment should `succeed` and below object should be returned in the payment response body.
```
"external_authentication_details": {
"authentication_flow": "frictionless",
"electronic_commerce_indicator": null,
"status": "success",
"ds_transaction_id": "3961a5b1-593f-4f94-851e-2793cd7f9e77",
"version": "2.2.0",
"error_code": null,
"error_message": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
dd333298f8b4e8ff3c15fc79fbc528a61fa1b63f
|
Ran cybersource postman collection to make sure existing 3ds flow is not affected.
<img width="785" alt="Screenshot 2024-05-23 at 1 00 07 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/c210e8ce-1864-444d-8f81-2ef3a7133160">
curls:
1. Create a cybersource connector and netcetera authentication connector.
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "",
"key1": "",
"api_secret": ""
},
"test_mode": false,
"disabled": false,
"business_country": "US",
"business_label": "default",
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "apple_pay",
"payment_experience": "invoke_sdk_client",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"acquirer_bin": "438309",
"acquirer_merchant_id": "00002000000"
}
}'
```
```
curl --location 'http://localhost:8080/account/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "authentication_processor",
"business_country": "US",
"business_label": "default",
"connector_name": "netcetera",
"connector_account_details": {
"auth_type": "CertificateAuth",
"certificate": "",
"private_key": ""
},
"test_mode": true,
"disabled": false,
"metadata": {
"mcc": "5411",
"merchant_country_code": "840",
"merchant_name": "Dummy Merchant",
"endpoint_prefix": "flowbird",
"three_ds_requestor_name": "juspay-prev",
"three_ds_requestor_id": "juspay-prev",
"pull_mechanism_for_external_3ds_enabled": false
}
}'
```
2. Create a payment with "request_external_three_ds_authentication": true, and "authentication_type": "three_ds",
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mv6wkxquIeO6WDvY49Mpd4hullQ4CW05hBRT7tlIX4EOS5NaG5fmDzuY5NqacvXT' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "123456789",
"country_code": "12"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "123456789",
"country_code": "12"
}
},
"request_external_three_ds_authentication": true,
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
3. Confirm the payment
```
curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_d777ba4dfb764db2a6f851870a00a7e5' \
--data '{
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "115.99.183.2"
},
"client_secret": "pay_XPc0gwoIZLYpMBKI8Yng_secret_vRjk6g87hvftbO9z18BO",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4929251897047956",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
}
}'
```
4. Authenticate the payment.
```
curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/3ds/authentication' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_d777ba4dfb764db2a6f851870a00a7e5' \
--data '{
"client_secret": "pay_XPc0gwoIZLYpMBKI8Yng_secret_vRjk6g87hvftbO9z18BO",
"device_channel": "BRW",
"threeds_method_comp_ind": "N"
}'
```
5. Authorize the payment.
```
curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng/postman_merchant_GHAction_7360288d-b77e-4624-8a48-74c11c31d3a0/authorize/checkout' \
--header 'Content-Type: application/json' \
--data '{
}'
```
6. Retrive the payment.
```
curl --location 'http://localhost:8080/payments/pay_XPc0gwoIZLYpMBKI8Yng?force_sync=true' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mv6wkxquIeO6WDvY49Mpd4hullQ4CW05hBRT7tlIX4EOS5NaG5fmDzuY5NqacvXT'
```
Payment should `succeed` and below object should be returned in the payment response body.
```
"external_authentication_details": {
"authentication_flow": "frictionless",
"electronic_commerce_indicator": null,
"status": "success",
"ds_transaction_id": "3961a5b1-593f-4f94-851e-2793cd7f9e77",
"version": "2.2.0",
"error_code": null,
"error_message": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4712
|
Bug: [Refcator] Refactor Payment Response to show the Payment Method Data
### Feature Description
Refactor Payment Response to show the Payment Method Data after a recurring payment using payment token
### Possible Implementation
Refactor Payment Response to show the Payment Method Data after a recurring payment using payment token
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 7d1858bd0d7..6cbdb86a750 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1,6 +1,10 @@
use std::marker::PhantomData;
-use api_models::{admin::ExtendedCardInfoConfig, enums::FrmSuggestion, payments::ExtendedCardInfo};
+use api_models::{
+ admin::ExtendedCardInfoConfig,
+ enums::FrmSuggestion,
+ payments::{AdditionalCardInfo, AdditionalPaymentData, ExtendedCardInfo},
+};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, StringExt, ValueExt};
use error_stack::{report, ResultExt};
@@ -17,6 +21,7 @@ use crate::{
blocklist::utils as blocklist_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
+ payment_methods::cards,
payments::{
self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress,
PaymentData,
@@ -1035,6 +1040,26 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode additional pm data")?;
+ let key = key_store.key.get_inner().peek();
+
+ let card_detail_from_locker = payment_data
+ .payment_method_info
+ .as_ref()
+ .async_map(|pm| async move {
+ cards::get_card_details_without_locker_fallback(pm, key, state).await
+ })
+ .await
+ .transpose()?;
+
+ let additional_data: Option<AdditionalCardInfo> = card_detail_from_locker.map(From::from);
+
+ let encode_additional_pm_to_value = additional_data
+ .map(|additional_data| AdditionalPaymentData::Card(Box::new(additional_data)))
+ .as_ref()
+ .map(Encode::encode_to_value)
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode additional pm data")?;
let business_sub_label = payment_data.payment_attempt.business_sub_label.clone();
let authentication_type = payment_data.payment_attempt.authentication_type;
@@ -1079,12 +1104,20 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
.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();
+ 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 = additional_pm_data.clone();
+ let m_additional_pm_data = additional_pm_data.clone().or(encode_additional_pm_to_value);
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();
|
2024-05-21T08:22:32Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
add support to enable pm_data and pm_id in payments response
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Create a MA and a MCA
- Create a Off session payment with Customer Acceptance
>
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>
```
Confirm
curl --location 'http://localhost:8080/payments/pay_2iVBNXi0blHcB0tyjeMW/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "12",
"card_exp_year": "2043",
"card_holder_name": "Cy1",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
}
}'
```
- Create a off session payment with payment token
>
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>
```
Confirm
curl --location 'http://localhost:8080/payments/pay_2iVBNXi0blHcB0tyjeMW/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_token": "{{payment_token}}"
}'
```
- Retrieve the Payment, the card details will be shown in the response
>
```
Response
{
"payment_id": "pay_2iVBNXi0blHcB0tyjeMW",
"merchant_id": "merchant_1716278979",
"status": "succeeded",
"amount": 6777,
"net_amount": 6777,
"amount_capturable": 0,
"amount_received": 6777,
"connector": "cybersource",
"client_secret": "pay_2iVBNXi0blHcB0tyjeMW_secret_Chc0A7EDkeiAoqfbuFKU",
"created": "2024-05-21T08:10:04.739Z",
"currency": "USD",
"customer_id": "new-c777",
"customer": {
"id": "new-c777",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "12",
"card_exp_year": "2043",
"card_holder_name": "Cy1",
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_JHzGpIqfTEJ0zm0QNE8T",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7162790289656608304951",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_2iVBNXi0blHcB0tyjeMW_1",
"payment_link": null,
"profile_id": "pro_3sd18D4q96QhAGUAI7K7",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_tSrvrQbl3NvDlS9GkQdd",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-21T08:25:04.739Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_UnNkHBpGbeX6pSecvsCt",
"payment_method_status": "active",
"updated": "2024-05-21T08:10:29.812Z",
"frm_metadata": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
44681ab058f081a5621ba147d5491111cfbc55bc
|
- Create a MA and a MCA
- Create a Off session payment with Customer Acceptance
>
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>
```
Confirm
curl --location 'http://localhost:8080/payments/pay_2iVBNXi0blHcB0tyjeMW/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "12",
"card_exp_year": "2043",
"card_holder_name": "Cy1",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
}
}'
```
- Create a off session payment with payment token
>
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \
--data-raw '{
"amount": 6777,
"currency": "USD",
"confirm": false,
"customer_id": "new-c777",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"setup_future_usage":"off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
>
```
Confirm
curl --location 'http://localhost:8080/payments/pay_2iVBNXi0blHcB0tyjeMW/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Mg6I2ovVxNBp6ZJmf84J2CPS3aDBtKeara9bYS08ep8h8PknW2S8yiprQGwmc4lQ' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_token": "{{payment_token}}"
}'
```
- Retrieve the Payment, the card details will be shown in the response
>
```
Response
{
"payment_id": "pay_2iVBNXi0blHcB0tyjeMW",
"merchant_id": "merchant_1716278979",
"status": "succeeded",
"amount": 6777,
"net_amount": 6777,
"amount_capturable": 0,
"amount_received": 6777,
"connector": "cybersource",
"client_secret": "pay_2iVBNXi0blHcB0tyjeMW_secret_Chc0A7EDkeiAoqfbuFKU",
"created": "2024-05-21T08:10:04.739Z",
"currency": "USD",
"customer_id": "new-c777",
"customer": {
"id": "new-c777",
"name": "Joseph Doe",
"email": "something@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "12",
"card_exp_year": "2043",
"card_holder_name": "Cy1",
"payment_checks": {
"avs_response": {
"code": "Y",
"codeRaw": "Y"
},
"card_verification": null
},
"authentication_data": null
},
"billing": null
},
"payment_token": "token_JHzGpIqfTEJ0zm0QNE8T",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "7162790289656608304951",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_2iVBNXi0blHcB0tyjeMW_1",
"payment_link": null,
"profile_id": "pro_3sd18D4q96QhAGUAI7K7",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_tSrvrQbl3NvDlS9GkQdd",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-21T08:25:04.739Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_UnNkHBpGbeX6pSecvsCt",
"payment_method_status": "active",
"updated": "2024-05-21T08:10:29.812Z",
"frm_metadata": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4718
|
Bug: [BUG] handle empty string updated_by for soft kill kv
### Bug Description
some entries for payment attempt is inserted with '' value in db, in which case we are not sure where the data is present
### Expected Behavior
handle these cases in the safest way by having a lookup in redis and deciding the storage scheme
### Actual Behavior
configured scheme gets picked
### Steps To Reproduce
tested in integ, not reproducible in local machine
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs
index 9c429058b70..c39e67eb841 100644
--- a/crates/storage_impl/src/redis/kv_store.rs
+++ b/crates/storage_impl/src/redis/kv_store.rs
@@ -249,7 +249,9 @@ impl<'a> std::fmt::Display for Op<'a> {
match self {
Op::Insert => f.write_str("insert"),
Op::Find => f.write_str("find"),
- Op::Update(p_key, _, _) => f.write_str(&format!("update_{}", p_key)),
+ Op::Update(p_key, _, updated_by) => {
+ f.write_str(&format!("update_{} for updated_by_{:?}", p_key, updated_by))
+ }
}
}
}
@@ -273,7 +275,8 @@ where
let updated_scheme = match operation {
Op::Insert => MerchantStorageScheme::PostgresOnly,
Op::Find => MerchantStorageScheme::RedisKv,
- Op::Update(partition_key, field, Some("redis_kv")) => {
+ Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly,
+ Op::Update(partition_key, field, Some(_updated_by)) => {
match kv_wrapper::<D, _, _>(store, KvOperation::<D>::HGet(field), partition_key)
.await
{
@@ -286,11 +289,6 @@ where
}
Op::Update(_, _, None) => MerchantStorageScheme::PostgresOnly,
- Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly,
- _ => {
- logger::debug!("soft_kill_mode - using default storage scheme");
- storage_scheme
- }
};
let type_name = std::any::type_name::<D>();
|
2024-05-21T11:59:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
there are some entries created with updated_by as '' for payment_attempt, which is causing decide storage scheme to select the configured scheme which is an issue during soft kill with configured scheme as redis_kv as we want db entities to be processed in db
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
there are some entries created with updated_by as '' for payment_attempt, which is causing decide storage scheme to select the configured scheme which is an issue during soft kill with configured scheme as redis_kv as we want db entities to be processed in db
`select created_at , updated_by from payment_attempt where updated_by = '' order by created_at desc limit 100`
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2e79ee0615292182111586fda7655dd9a796ef4f
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4707
|
Bug: refactor: Separate out recovery codes from TOTP
Even though recovery codes is dependent entity on TOTP. But the new findings suggest that TOTP is a part of entity called 2FA and TOTP is depended on the 2FA entity not the TOTP entity.
This will be more clear when we add multiple 2FAs like SMS OTP.
So, we want to separate out recovery codes from the TOTP. This means `begin_totp` should not return the recovery codes anymore.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index e9eb5157095..b7d7adbf8e3 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -14,10 +14,10 @@ use crate::user::{
ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse,
ForgotPasswordRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest,
GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest,
- ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse,
- SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse,
- TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate,
- VerifyEmailRequest, VerifyTotpRequest,
+ RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest,
+ SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
+ TokenOrPayloadResponse, TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest,
+ UserMerchantCreate, VerifyEmailRequest, VerifyTotpRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -75,7 +75,8 @@ common_utils::impl_misc_api_event_type!(
TokenResponse,
UserFromEmailRequest,
BeginTotpResponse,
- VerifyTotpRequest
+ VerifyTotpRequest,
+ RecoveryCodes
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 7dbf867d1a0..7864117856e 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -257,3 +257,8 @@ pub struct TotpSecret {
pub struct VerifyTotpRequest {
pub totp: Option<Secret<String>>,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct RecoveryCodes {
+ pub recovery_codes: Vec<Secret<String>>,
+}
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index 8d6aa6265d8..33642205d57 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -12,3 +12,5 @@ pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30;
pub const TOTP_TOLERANCE: u8 = 1;
pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
+
+pub const TOTP_PREFIX: &str = "TOTP_";
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 580e34ba7e8..2d1c196f5df 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -66,10 +66,12 @@ pub enum UserErrors {
RoleNameParsingError,
#[error("RoleNameAlreadyExists")]
RoleNameAlreadyExists,
- #[error("TOTPNotSetup")]
+ #[error("TotpNotSetup")]
TotpNotSetup,
- #[error("InvalidTOTP")]
+ #[error("InvalidTotp")]
InvalidTotp,
+ #[error("TotpRequired")]
+ TotpRequired,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -179,6 +181,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::InvalidTotp => {
AER::BadRequest(ApiError::new(sub_code, 37, self.get_error_message(), None))
}
+ Self::TotpRequired => {
+ AER::BadRequest(ApiError::new(sub_code, 38, self.get_error_message(), None))
+ }
}
}
}
@@ -217,6 +222,7 @@ impl UserErrors {
Self::RoleNameAlreadyExists => "Role name already exists",
Self::TotpNotSetup => "TOTP not setup",
Self::InvalidTotp => "Invalid TOTP",
+ Self::TotpRequired => "TOTP required",
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 5d1eaeaeb8d..7a0ef683e7a 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1631,7 +1631,7 @@ pub async fn begin_totp(
}));
}
- let totp = utils::user::generate_default_totp(user_from_db.get_email(), None)?;
+ let totp = utils::user::two_factor_auth::generate_default_totp(user_from_db.get_email(), None)?;
let recovery_codes = domain::RecoveryCodes::generate_new();
let key_store = user_from_db.get_or_create_key_store(&state).await?;
@@ -1693,8 +1693,10 @@ pub async fn verify_totp(
.await?
.ok_or(UserErrors::InternalServerError)?;
- let totp =
- utils::user::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?;
+ let totp = utils::user::two_factor_auth::generate_default_totp(
+ user_from_db.get_email(),
+ Some(user_totp_secret),
+ )?;
if totp
.generate_current()
@@ -1732,3 +1734,35 @@ pub async fn verify_totp(
token,
)
}
+
+pub async fn generate_recovery_codes(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+) -> UserResponse<user_api::RecoveryCodes> {
+ if !utils::user::two_factor_auth::check_totp_in_redis(&state, &user_token.user_id).await? {
+ return Err(UserErrors::TotpRequired.into());
+ }
+
+ let recovery_codes = domain::RecoveryCodes::generate_new();
+
+ state
+ .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(),
+ }))
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index f4eded24be6..7c8f7e32be1 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1207,7 +1207,11 @@ impl User {
.route(web::post().to(set_dashboard_metadata)),
)
.service(web::resource("/totp/begin").route(web::get().to(totp_begin)))
- .service(web::resource("/totp/verify").route(web::post().to(totp_verify)));
+ .service(web::resource("/totp/verify").route(web::post().to(totp_verify)))
+ .service(
+ web::resource("/recovery_codes/generate")
+ .route(web::get().to(generate_recovery_codes)),
+ );
#[cfg(feature = "email")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 30b582079e3..542a18d45be 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -213,7 +213,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::VerifyEmailRequest
| Flow::UpdateUserAccountDetails
| Flow::TotpBegin
- | Flow::TotpVerify => Self::User,
+ | Flow::TotpVerify
+ | Flow::GenerateRecoveryCodes => Self::User,
Flow::ListRoles
| Flow::GetRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index f28064901e5..f542c446e49 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -665,3 +665,17 @@ pub async fn totp_verify(
))
.await
}
+
+pub async fn generate_recovery_codes(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::GenerateRecoveryCodes;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| user_core::generate_recovery_codes(state, user),
+ &auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 4980958c9ac..9c67dbfcab5 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -1,14 +1,11 @@
use std::collections::HashMap;
use api_models::user as user_api;
-use common_utils::{errors::CustomResult, pii};
+use common_utils::errors::CustomResult;
use diesel_models::{enums::UserStatus, user_role::UserRole};
use error_stack::ResultExt;
-use masking::ExposeInterface;
-use totp_rs::{Algorithm, TOTP};
use crate::{
- consts,
core::errors::{StorageError, UserErrors, UserResult},
routes::AppState,
services::{
@@ -22,6 +19,7 @@ pub mod dashboard_metadata;
pub mod password;
#[cfg(feature = "dummy_connector")]
pub mod sample_data;
+pub mod two_factor_auth;
impl UserFromToken {
pub async fn get_merchant_account_from_db(
@@ -193,25 +191,3 @@ pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> maskin
user_api::SignInResponse::MerchantSelect(data) => data.token.clone(),
}
}
-
-pub fn generate_default_totp(
- email: pii::Email,
- secret: Option<masking::Secret<String>>,
-) -> UserResult<TOTP> {
- let secret = secret
- .map(|sec| totp_rs::Secret::Encoded(sec.expose()))
- .unwrap_or_else(totp_rs::Secret::generate_secret)
- .to_bytes()
- .change_context(UserErrors::InternalServerError)?;
-
- TOTP::new(
- Algorithm::SHA1,
- consts::user::TOTP_DIGITS,
- consts::user::TOTP_TOLERANCE,
- consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS,
- secret,
- Some(consts::user::TOTP_ISSUER_NAME.to_string()),
- email.expose().expose(),
- )
- .change_context(UserErrors::InternalServerError)
-}
diff --git a/crates/router/src/utils/user/two_factor_auth.rs b/crates/router/src/utils/user/two_factor_auth.rs
new file mode 100644
index 00000000000..62bcf2f7eb1
--- /dev/null
+++ b/crates/router/src/utils/user/two_factor_auth.rs
@@ -0,0 +1,52 @@
+use std::sync::Arc;
+
+use common_utils::pii;
+use error_stack::ResultExt;
+use masking::ExposeInterface;
+use redis_interface::RedisConnectionPool;
+use totp_rs::{Algorithm, TOTP};
+
+use crate::{
+ consts,
+ core::errors::{UserErrors, UserResult},
+ routes::AppState,
+};
+
+pub fn generate_default_totp(
+ email: pii::Email,
+ secret: Option<masking::Secret<String>>,
+) -> UserResult<TOTP> {
+ let secret = secret
+ .map(|sec| totp_rs::Secret::Encoded(sec.expose()))
+ .unwrap_or_else(totp_rs::Secret::generate_secret)
+ .to_bytes()
+ .change_context(UserErrors::InternalServerError)?;
+
+ TOTP::new(
+ Algorithm::SHA1,
+ consts::user::TOTP_DIGITS,
+ consts::user::TOTP_TOLERANCE,
+ consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS,
+ secret,
+ Some(consts::user::TOTP_ISSUER_NAME.to_string()),
+ email.expose().expose(),
+ )
+ .change_context(UserErrors::InternalServerError)
+}
+
+pub async fn check_totp_in_redis(state: &AppState, user_id: &str) -> UserResult<bool> {
+ let redis_conn = get_redis_connection(state)?;
+ let key = format!("{}{}", consts::user::TOTP_PREFIX, user_id);
+ redis_conn
+ .exists::<()>(&key)
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+
+fn get_redis_connection(state: &AppState) -> UserResult<Arc<RedisConnectionPool>> {
+ state
+ .store
+ .get_redis_conn()
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get redis connection")
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index ffa492bc60d..186ee4a6704 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -404,6 +404,8 @@ pub enum Flow {
TotpBegin,
/// Verify TOTP
TotpVerify,
+ /// Generate or Regenerate recovery codes
+ GenerateRecoveryCodes,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
2024-05-20T13:58:53Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently recovery code are being generated in `begin_totp` API. We want to make a separate out recovery codes and TOTP, so this PR creates a new API which generates the recovery codes.
This API will also be used to regenerate recovery codes later.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
This is a sub part of #4707
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
**This can only be tested locally as it requires some changes in the redis.**
```
curl --location 'http://localhost:8080/user/recovery_codes/generate' \
--header 'Authorization: Bearer SPT with purpose as TOTP' \
```
```
{
"recovery_codes": [
"w5fM-NLm0",
"TumH-oyXE",
"wDIr-zEmu",
"HZjm-e16M",
"Q4qB-MupL",
"5BtN-vRuY",
"4vG6-URGf",
"Dbq8-n5V1"
]
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
36409bdc9185d4241971a30c55e1e331568abd2f
|
**This can only be tested locally as it requires some changes in the redis.**
```
curl --location 'http://localhost:8080/user/recovery_codes/generate' \
--header 'Authorization: Bearer SPT with purpose as TOTP' \
```
```
{
"recovery_codes": [
"w5fM-NLm0",
"TumH-oyXE",
"wDIr-zEmu",
"HZjm-e16M",
"Q4qB-MupL",
"5BtN-vRuY",
"4vG6-URGf",
"Dbq8-n5V1"
]
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4706
|
Bug: [bug]: fix timestamp sent to kafka events
rdkafka library expects time in millis but we send seconds.
This can be reflected in the kafka-ui at localhost:8090 as well.
We can fix this by either truncating the unix_timestamp_nanos or padding the seconds.
|
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index 58657c59fd8..6f2aa9fcd10 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -259,7 +259,7 @@ impl KafkaProducer {
.timestamp(
event
.creation_timestamp()
- .unwrap_or_else(|| OffsetDateTime::now_utc().unix_timestamp()),
+ .unwrap_or_else(|| OffsetDateTime::now_utc().unix_timestamp() * 1_000),
),
)
.map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}")))
@@ -476,7 +476,7 @@ impl MessagingInterface for KafkaProducer {
.key(&data.identifier())
.payload(&json_data)
.timestamp(
- (timestamp.assume_utc().unix_timestamp_nanos() / 1_000)
+ (timestamp.assume_utc().unix_timestamp_nanos() / 1_000_000)
.to_i64()
.unwrap_or_else(|| {
// kafka producer accepts milliseconds
diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs
index c01089855c6..1950fb253a7 100644
--- a/crates/router/src/services/kafka/dispute.rs
+++ b/crates/router/src/services/kafka/dispute.rs
@@ -70,10 +70,6 @@ impl<'a> super::KafkaMessage for KafkaDispute<'a> {
)
}
- fn creation_timestamp(&self) -> Option<i64> {
- Some(self.modified_at.unix_timestamp())
- }
-
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Dispute
}
diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs
index dfa7da0d0a4..86ea378bfa3 100644
--- a/crates/router/src/services/kafka/payment_attempt.rs
+++ b/crates/router/src/services/kafka/payment_attempt.rs
@@ -108,10 +108,6 @@ impl<'a> super::KafkaMessage for KafkaPaymentAttempt<'a> {
)
}
- fn creation_timestamp(&self) -> Option<i64> {
- Some(self.modified_at.unix_timestamp())
- }
-
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentAttempt
}
diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs
index ad61e102955..bcdf23e7941 100644
--- a/crates/router/src/services/kafka/payment_intent.rs
+++ b/crates/router/src/services/kafka/payment_intent.rs
@@ -66,10 +66,6 @@ impl<'a> super::KafkaMessage for KafkaPaymentIntent<'a> {
format!("{}_{}", self.merchant_id, self.payment_id)
}
- fn creation_timestamp(&self) -> Option<i64> {
- Some(self.modified_at.unix_timestamp())
- }
-
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentIntent
}
diff --git a/crates/router/src/services/kafka/payout.rs b/crates/router/src/services/kafka/payout.rs
index 6b25c724eb8..a07b90ee288 100644
--- a/crates/router/src/services/kafka/payout.rs
+++ b/crates/router/src/services/kafka/payout.rs
@@ -80,10 +80,6 @@ impl<'a> super::KafkaMessage for KafkaPayout<'a> {
format!("{}_{}", self.merchant_id, self.payout_attempt_id)
}
- fn creation_timestamp(&self) -> Option<i64> {
- Some(self.last_modified_at.unix_timestamp())
- }
-
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Payout
}
|
2024-05-20T14:16:14Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
fixes #4706
Convert secs to millis when sending creation timestamp to kafka
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- This will fix problems encountered down the pipeline with data retention
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- the timestamp listed in kafka-ui
- can't be tested without infra access and no visible changes on UI
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ae601e8e1be9215488daaae7cb39ad5a030e98d9
|
- the timestamp listed in kafka-ui
- can't be tested without infra access and no visible changes on UI
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4703
|
Bug: [FEATURE] [AUTHORIZEDOTNET] Implement non-zero mandates
### Feature Description
Non-zero dollar mandates need to be implemented for connector Authorizedotnet.
### Possible Implementation
Non-zero dollar mandates need to be implemented for connector Authorizedotnet.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index a9e000b82b9..8d0c1db37a2 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -79,6 +79,16 @@ impl ConnectorValidation for Authorizedotnet {
),
}
}
+
+ fn validate_mandate_payment(
+ &self,
+ pm_type: Option<types::storage::enums::PaymentMethodType>,
+ pm_data: types::domain::payments::PaymentMethodData,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ let mandate_supported_pmd =
+ std::collections::HashSet::from([crate::connector::utils::PaymentMethodDataType::Card]);
+ connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
+ }
}
impl api::Payment for Authorizedotnet {}
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 3e4d0a382e6..de68438edc4 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -133,20 +133,36 @@ pub enum WalletMethod {
struct TransactionRequest {
transaction_type: TransactionType,
amount: f64,
- currency_code: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- profile: Option<CustomerProfileDetails>,
+ currency_code: common_enums::Currency,
#[serde(skip_serializing_if = "Option::is_none")]
payment: Option<PaymentDetails>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ profile: Option<ProfileDetails>,
order: Order,
#[serde(skip_serializing_if = "Option::is_none")]
+ customer: Option<CustomerDetails>,
+ #[serde(skip_serializing_if = "Option::is_none")]
bill_to: Option<BillTo>,
+ #[serde(skip_serializing_if = "Option::is_none")]
processing_options: Option<ProcessingOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
subsequent_auth_information: Option<SubsequentAuthInformation>,
authorization_indicator_type: Option<AuthorizationIndicator>,
}
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(untagged)]
+enum ProfileDetails {
+ CreateProfileDetails(CreateProfileDetails),
+ CustomerProfileDetails(CustomerProfileDetails),
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateProfileDetails {
+ create_profile: bool,
+}
+
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct CustomerProfileDetails {
@@ -160,6 +176,12 @@ struct PaymentProfileDetails {
payment_profile_id: Secret<String>,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CustomerDetails {
+ id: String,
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingOptions {
@@ -461,37 +483,37 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
fn try_from(
item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
- let (payment_details, processing_options, subsequent_auth_information, profile) = match item
+ let merchant_authentication =
+ AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
+
+ let ref_id = if item.router_data.connector_request_reference_id.len() <= 20 {
+ Some(item.router_data.connector_request_reference_id.clone())
+ } else {
+ None
+ };
+
+ let transaction_request = match item
.router_data
.request
.mandate_id
- .to_owned()
+ .clone()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id)
{
Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => {
- let processing_options = Some(ProcessingOptions {
- is_subsequent_auth: true,
- });
- let subsequent_auth_info = Some(SubsequentAuthInformation {
- original_network_trans_id: Secret::new(network_trans_id),
- reason: Reason::Resubmission,
- });
- match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ref ccard) => {
- let payment_details = PaymentDetails::CreditCard(CreditCardDetails {
- card_number: (*ccard.card_number).clone(),
- expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
- card_code: None,
- });
- (
- Some(payment_details),
- processing_options,
- subsequent_auth_info,
- None,
- )
+ TransactionRequest::try_from((item, network_trans_id))?
+ }
+ Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
+ connector_mandate_id,
+ )) => TransactionRequest::try_from((item, connector_mandate_id))?,
+ None => {
+ match &item.router_data.request.payment_method_data {
+ domain::PaymentMethodData::Card(ccard) => {
+ TransactionRequest::try_from((item, ccard))
+ }
+ domain::PaymentMethodData::Wallet(wallet_data) => {
+ TransactionRequest::try_from((item, wallet_data))
}
domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
| domain::PaymentMethodData::PayLater(_)
| domain::PaymentMethodData::BankRedirect(_)
| domain::PaymentMethodData::BankDebit(_)
@@ -510,16 +532,116 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
))?
}
}
- }
- Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
- connector_mandate_id,
- )) => (
- None,
- Some(ProcessingOptions {
- is_subsequent_auth: true,
+ }?,
+ };
+ Ok(Self {
+ create_transaction_request: AuthorizedotnetPaymentsRequest {
+ merchant_authentication,
+ ref_id,
+ transaction_request,
+ },
+ })
+ }
+}
+
+impl
+ TryFrom<(
+ &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ String,
+ )> for TransactionRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, network_trans_id): (
+ &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ String,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
+ amount: item.amount,
+ currency_code: item.router_data.request.currency,
+ payment: Some(match item.router_data.request.payment_method_data {
+ domain::PaymentMethodData::Card(ref ccard) => {
+ PaymentDetails::CreditCard(CreditCardDetails {
+ card_number: (*ccard.card_number).clone(),
+ expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
+ card_code: None,
+ })
+ }
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::Upi(_)
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
+ ))?
+ }
+ }),
+ profile: None,
+ order: Order {
+ description: item.router_data.connector_request_reference_id.clone(),
+ },
+ customer: None,
+ bill_to: item
+ .router_data
+ .get_optional_billing()
+ .and_then(|billing_address| billing_address.address.as_ref())
+ .map(|address| BillTo {
+ first_name: address.first_name.clone(),
+ last_name: address.last_name.clone(),
+ address: address.line1.clone(),
+ city: address.city.clone(),
+ state: address.state.clone(),
+ zip: address.zip.clone(),
+ country: address.country,
+ }),
+ processing_options: Some(ProcessingOptions {
+ is_subsequent_auth: true,
+ }),
+ subsequent_auth_information: Some(SubsequentAuthInformation {
+ original_network_trans_id: Secret::new(network_trans_id),
+ reason: Reason::Resubmission,
+ }),
+ authorization_indicator_type: match item.router_data.request.capture_method {
+ Some(capture_method) => Some(AuthorizationIndicator {
+ authorization_indicator: capture_method.try_into()?,
}),
- None,
- Some(CustomerProfileDetails {
+ None => None,
+ },
+ })
+ }
+}
+
+impl
+ TryFrom<(
+ &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ api_models::payments::ConnectorMandateReferenceId,
+ )> for TransactionRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, connector_mandate_id): (
+ &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ api_models::payments::ConnectorMandateReferenceId,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
+ amount: item.amount,
+ currency_code: item.router_data.request.currency,
+ payment: None,
+ profile: Some(ProfileDetails::CustomerProfileDetails(
+ CustomerProfileDetails {
customer_profile_id: Secret::from(
connector_mandate_id
.connector_mandate_id
@@ -532,64 +654,86 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
.ok_or(errors::ConnectorError::MissingConnectorMandateID)?,
),
},
- }),
- ),
- None => {
- match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ref ccard) => {
- (
- Some(PaymentDetails::CreditCard(CreditCardDetails {
- card_number: (*ccard.card_number).clone(),
- // expiration_date: format!("{expiry_year}-{expiry_month}").into(),
- expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
- card_code: Some(ccard.card_cvc.clone()),
- })),
- Some(ProcessingOptions {
- is_subsequent_auth: true,
- }),
- None,
- None,
- )
- }
- domain::PaymentMethodData::Wallet(ref wallet_data) => (
- Some(get_wallet_data(
- wallet_data,
- &item.router_data.request.complete_authorize_url,
- )?),
- None,
- None,
- None,
- ),
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message(
- "authorizedotnet",
- ),
- ))?
- }
- }
- }
- };
- let authorization_indicator_type = match item.router_data.request.capture_method {
- Some(capture_method) => Some(AuthorizationIndicator {
- authorization_indicator: capture_method.try_into()?,
+ },
+ )),
+ order: Order {
+ description: item.router_data.connector_request_reference_id.clone(),
+ },
+ customer: None,
+ bill_to: None,
+ processing_options: Some(ProcessingOptions {
+ is_subsequent_auth: true,
}),
- None => None,
+ subsequent_auth_information: None,
+ authorization_indicator_type: match item.router_data.request.capture_method {
+ Some(capture_method) => Some(AuthorizationIndicator {
+ authorization_indicator: capture_method.try_into()?,
+ }),
+ None => None,
+ },
+ })
+ }
+}
+
+impl
+ TryFrom<(
+ &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ &domain::Card,
+ )> for TransactionRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, ccard): (
+ &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ &domain::Card,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let (profile, customer) = if item
+ .router_data
+ .request
+ .setup_future_usage
+ .map_or(false, |future_usage| {
+ matches!(future_usage, common_enums::FutureUsage::OffSession)
+ })
+ && (item.router_data.request.customer_acceptance.is_some()
+ || item
+ .router_data
+ .request
+ .setup_mandate_details
+ .clone()
+ .map_or(false, |mandate_details| {
+ mandate_details.customer_acceptance.is_some()
+ })) {
+ (
+ Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails {
+ create_profile: true,
+ })),
+ Some(CustomerDetails {
+ id: item
+ .router_data
+ .customer_id
+ .clone()
+ .ok_or_else(missing_field_err("customer_id"))?,
+ }),
+ )
+ } else {
+ (None, None)
};
- let bill_to = match profile {
- Some(_) => None,
- None => item
+ Ok(Self {
+ transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
+ amount: item.amount,
+ currency_code: item.router_data.request.currency,
+ payment: Some(PaymentDetails::CreditCard(CreditCardDetails {
+ card_number: (*ccard.card_number).clone(),
+ expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
+ card_code: Some(ccard.card_cvc.clone()),
+ })),
+ profile,
+ order: Order {
+ description: item.router_data.connector_request_reference_id.clone(),
+ },
+ customer,
+ bill_to: item
.router_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
@@ -602,34 +746,64 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
zip: address.zip.clone(),
country: address.country,
}),
- };
- let transaction_request = TransactionRequest {
+ processing_options: None,
+ subsequent_auth_information: None,
+ authorization_indicator_type: match item.router_data.request.capture_method {
+ Some(capture_method) => Some(AuthorizationIndicator {
+ authorization_indicator: capture_method.try_into()?,
+ }),
+ None => None,
+ },
+ })
+ }
+}
+
+impl
+ TryFrom<(
+ &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ &domain::WalletData,
+ )> for TransactionRequest
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ (item, wallet_data): (
+ &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ &domain::WalletData,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
- currency_code: item.router_data.request.currency.to_string(),
- profile,
- payment: payment_details,
+ currency_code: item.router_data.request.currency,
+ payment: Some(get_wallet_data(
+ wallet_data,
+ &item.router_data.request.complete_authorize_url,
+ )?),
+ profile: None,
order: Order {
description: item.router_data.connector_request_reference_id.clone(),
},
- bill_to,
- processing_options,
- subsequent_auth_information,
- authorization_indicator_type,
- };
-
- let merchant_authentication =
- AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
- let ref_id = if item.router_data.connector_request_reference_id.len() <= 20 {
- Some(item.router_data.connector_request_reference_id.clone())
- } else {
- None
- };
- Ok(Self {
- create_transaction_request: AuthorizedotnetPaymentsRequest {
- merchant_authentication,
- ref_id,
- transaction_request,
+ customer: None,
+ bill_to: item
+ .router_data
+ .get_optional_billing()
+ .and_then(|billing_address| billing_address.address.as_ref())
+ .map(|address| BillTo {
+ first_name: address.first_name.clone(),
+ last_name: address.last_name.clone(),
+ address: address.line1.clone(),
+ city: address.city.clone(),
+ state: address.state.clone(),
+ zip: address.zip.clone(),
+ country: address.country,
+ }),
+ processing_options: None,
+ subsequent_auth_information: None,
+ authorization_indicator_type: match item.router_data.request.capture_method {
+ Some(capture_method) => Some(AuthorizationIndicator {
+ authorization_indicator: capture_method.try_into()?,
+ }),
+ None => None,
},
})
}
@@ -804,6 +978,15 @@ pub struct SecureAcceptance {
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsResponse {
pub transaction_response: Option<TransactionResponse>,
+ pub profile_response: Option<AuthorizedotnetNonZeroMandateResponse>,
+ pub messages: ResponseMessages,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AuthorizedotnetNonZeroMandateResponse {
+ customer_profile_id: Option<String>,
+ customer_payment_profile_id_list: Option<Vec<String>>,
pub messages: ResponseMessages,
}
@@ -913,7 +1096,16 @@ impl<F, T>
transaction_response.transaction_id.clone(),
),
redirection_data,
- mandate_reference: None,
+ mandate_reference: item.response.profile_response.map(
+ |profile_response| types::MandateReference {
+ connector_mandate_id: profile_response.customer_profile_id,
+ payment_method_id: profile_response
+ .customer_payment_profile_id_list
+ .and_then(|customer_payment_profile_id_list| {
+ customer_payment_profile_id_list.first().cloned()
+ }),
+ },
+ ),
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
|
2024-05-24T09:28:49Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Non-zero dollar mandates are implemented for connector Authorizedotnet.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4703
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Payment Intent Create (Non-Zero Mandate):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 370,
"currency": "USD",
"confirm": false,
"customer_id": "cust6",
"email": "something2@gmail.com",
"name": "Joseph Doe",
"description": "Its my first payment request",
"setup_future_usage":"off_session"
}'
```
Response:
```
{
"payment_id": "pay_lx2DcRsYllb2QenBQfze",
"merchant_id": "merchant_1716370796",
"status": "requires_payment_method",
"amount": 370,
"net_amount": 370,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_lx2DcRsYllb2QenBQfze_secret_X1riA15AgjzqEahbR8mv",
"created": "2024-05-27T11:07:15.600Z",
"currency": "USD",
"customer_id": "cust6",
"customer": {
"id": "cust6",
"name": "Joseph Doe",
"email": "something2@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "something2@gmail.com",
"name": "Joseph Doe",
"phone": null,
"return_url": null,
"authentication_type": null,
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cust6",
"created_at": 1716808035,
"expires": 1716811635,
"secret": "epk_339c8ebb1d9f430796cf8273ef72f78f"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_ZjmEyV32O7pOQkBlB510",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-27T11:22:15.600Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-27T11:07:15.690Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Confirm:
Request:
```
curl --location 'http://localhost:8080/payments/pay_lx2DcRsYllb2QenBQfze/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"card_cvc": "123"
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 68607706,
"currency": "USD",
"start_date": "2023-04-21T00:00:00Z",
"end_date": "2023-05-21T00:00:00Z",
"metadata": {
"frequency": "13"
}
}
}
}
}'
```
Response:
```
{
"payment_id": "pay_lx2DcRsYllb2QenBQfze",
"merchant_id": "merchant_1716370796",
"status": "succeeded",
"amount": 370,
"net_amount": 370,
"amount_capturable": 0,
"amount_received": 370,
"connector": "authorizedotnet",
"client_secret": "pay_lx2DcRsYllb2QenBQfze_secret_X1riA15AgjzqEahbR8mv",
"created": "2024-05-27T11:07:15.600Z",
"currency": "USD",
"customer_id": "cust6",
"customer": {
"id": "cust6",
"name": "Joseph Doe",
"email": "something2@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm",
"mandate_data": {
"update_mandate_id": null,
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 68607706,
"currency": "USD",
"start_date": "2023-04-21T00:00:00.000Z",
"end_date": "2023-05-21T00:00:00.000Z",
"metadata": {
"frequency": "13"
}
}
}
},
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "something2@gmail.com",
"name": "Joseph Doe",
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "80019080368",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80019080368",
"payment_link": null,
"profile_id": "pro_ZjmEyV32O7pOQkBlB510",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_6wtrG4tIah8tNezhNkT9",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-27T11:22:15.600Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_ZN7bB0d33KWNWIUgVWod",
"payment_method_status": null,
"updated": "2024-05-27T11:07:32.165Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Create (Using Mandate ID):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 141,
"currency": "USD",
"confirm": true,
"customer_id": "cust6",
"capture_method": "automatic",
"mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm",
"off_session": true
}'
```
Response:
```
{
"payment_id": "pay_8aI2C6oCZosMy1CQf2X9",
"merchant_id": "merchant_1716370796",
"status": "succeeded",
"amount": 141,
"net_amount": 141,
"amount_capturable": 0,
"amount_received": 141,
"connector": "authorizedotnet",
"client_secret": "pay_8aI2C6oCZosMy1CQf2X9_secret_gnro3S1Hlru3sUsAcdik",
"created": "2024-05-27T11:07:53.638Z",
"currency": "USD",
"customer_id": "cust6",
"customer": {
"id": "cust6",
"name": "Joseph Doe",
"email": "something2@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm",
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": "fa0a6a44-2e80-4953-971d-c70702e889d7",
"shipping": null,
"billing": null,
"order_details": null,
"email": "something2@gmail.com",
"name": "Joseph Doe",
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cust6",
"created_at": 1716808073,
"expires": 1716811673,
"secret": "epk_95141b60e629482ea657f64053afa3d2"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80019080384",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80019080384",
"payment_link": null,
"profile_id": "pro_ZjmEyV32O7pOQkBlB510",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_6wtrG4tIah8tNezhNkT9",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-27T11:22:53.638Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_ZN7bB0d33KWNWIUgVWod",
"payment_method_status": "active",
"updated": "2024-05-27T11:07:54.663Z",
"charges": null,
"frm_metadata": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8d9c7bc45ce2515759b9e2a36eb2d8a8a2c813ad
|
- Payment Intent Create (Non-Zero Mandate):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 370,
"currency": "USD",
"confirm": false,
"customer_id": "cust6",
"email": "something2@gmail.com",
"name": "Joseph Doe",
"description": "Its my first payment request",
"setup_future_usage":"off_session"
}'
```
Response:
```
{
"payment_id": "pay_lx2DcRsYllb2QenBQfze",
"merchant_id": "merchant_1716370796",
"status": "requires_payment_method",
"amount": 370,
"net_amount": 370,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_lx2DcRsYllb2QenBQfze_secret_X1riA15AgjzqEahbR8mv",
"created": "2024-05-27T11:07:15.600Z",
"currency": "USD",
"customer_id": "cust6",
"customer": {
"id": "cust6",
"name": "Joseph Doe",
"email": "something2@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": null,
"payment_method_data": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "something2@gmail.com",
"name": "Joseph Doe",
"phone": null,
"return_url": null,
"authentication_type": null,
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": null,
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cust6",
"created_at": 1716808035,
"expires": 1716811635,
"secret": "epk_339c8ebb1d9f430796cf8273ef72f78f"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_ZjmEyV32O7pOQkBlB510",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-27T11:22:15.600Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-27T11:07:15.690Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Confirm:
Request:
```
curl --location 'http://localhost:8080/payments/pay_lx2DcRsYllb2QenBQfze/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"card_cvc": "123"
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 68607706,
"currency": "USD",
"start_date": "2023-04-21T00:00:00Z",
"end_date": "2023-05-21T00:00:00Z",
"metadata": {
"frequency": "13"
}
}
}
}
}'
```
Response:
```
{
"payment_id": "pay_lx2DcRsYllb2QenBQfze",
"merchant_id": "merchant_1716370796",
"status": "succeeded",
"amount": 370,
"net_amount": 370,
"amount_capturable": 0,
"amount_received": 370,
"connector": "authorizedotnet",
"client_secret": "pay_lx2DcRsYllb2QenBQfze_secret_X1riA15AgjzqEahbR8mv",
"created": "2024-05-27T11:07:15.600Z",
"currency": "USD",
"customer_id": "cust6",
"customer": {
"id": "cust6",
"name": "Joseph Doe",
"email": "something2@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm",
"mandate_data": {
"update_mandate_id": null,
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 68607706,
"currency": "USD",
"start_date": "2023-04-21T00:00:00.000Z",
"end_date": "2023-05-21T00:00:00.000Z",
"metadata": {
"frequency": "13"
}
}
}
},
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "something2@gmail.com",
"name": "Joseph Doe",
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "80019080368",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80019080368",
"payment_link": null,
"profile_id": "pro_ZjmEyV32O7pOQkBlB510",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_6wtrG4tIah8tNezhNkT9",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-27T11:22:15.600Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": "pm_ZN7bB0d33KWNWIUgVWod",
"payment_method_status": null,
"updated": "2024-05-27T11:07:32.165Z",
"charges": null,
"frm_metadata": null
}
```
- Payment Create (Using Mandate ID):
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 141,
"currency": "USD",
"confirm": true,
"customer_id": "cust6",
"capture_method": "automatic",
"mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm",
"off_session": true
}'
```
Response:
```
{
"payment_id": "pay_8aI2C6oCZosMy1CQf2X9",
"merchant_id": "merchant_1716370796",
"status": "succeeded",
"amount": 141,
"net_amount": 141,
"amount_capturable": 0,
"amount_received": 141,
"connector": "authorizedotnet",
"client_secret": "pay_8aI2C6oCZosMy1CQf2X9_secret_gnro3S1Hlru3sUsAcdik",
"created": "2024-05-27T11:07:53.638Z",
"currency": "USD",
"customer_id": "cust6",
"customer": {
"id": "cust6",
"name": "Joseph Doe",
"email": "something2@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": "man_wxTMvSxaQPFC5uvg7Qmm",
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": "fa0a6a44-2e80-4953-971d-c70702e889d7",
"shipping": null,
"billing": null,
"order_details": null,
"email": "something2@gmail.com",
"name": "Joseph Doe",
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "cust6",
"created_at": 1716808073,
"expires": 1716811673,
"secret": "epk_95141b60e629482ea657f64053afa3d2"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80019080384",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80019080384",
"payment_link": null,
"profile_id": "pro_ZjmEyV32O7pOQkBlB510",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_6wtrG4tIah8tNezhNkT9",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-27T11:22:53.638Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_ZN7bB0d33KWNWIUgVWod",
"payment_method_status": "active",
"updated": "2024-05-27T11:07:54.663Z",
"charges": null,
"frm_metadata": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4702
|
Bug: [FEATURE] [AUTHORIZEDOTNET] Implement zero mandates
### Feature Description
Zero dollar mandates need to be implemented for connector Authorizedotnet.
### Possible Implementation
Zero dollar mandates need to be implemented for connector Authorizedotnet.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 0eb4297a414..a9e000b82b9 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -121,20 +121,84 @@ impl
types::PaymentsResponseData,
> for Authorizedotnet
{
- // Issue: #173
- fn build_request(
+ fn get_headers(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
+ req: &types::SetupMandateRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ // This connector does not require an auth header, the authentication details are sent in the request body
+ self.build_headers(req, connectors)
+ }
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+ fn get_url(
+ &self,
+ _req: &types::SetupMandateRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(self.base_url(connectors).to_string())
+ }
+ fn get_request_body(
+ &self,
+ req: &types::SetupMandateRouterData,
_connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented(
- "Setup Mandate flow for Authorizedotnet".to_string(),
- )
- .into())
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = authorizedotnet::CreateCustomerProfileRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::SetupMandateRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<common_utils::request::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::SetupMandateType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::SetupMandateType::get_headers(self, req, connectors)?)
+ .set_body(types::SetupMandateType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::SetupMandateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: types::Response,
+ ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> {
+ use bytes::Buf;
+
+ // Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
+ let encoding = encoding_rs::UTF_8;
+ let intermediate_response = encoding.decode_with_bom_removal(res.response.chunk());
+ let intermediate_response =
+ bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
+ let response: authorizedotnet::AuthorizedotnetSetupMandateResponse = intermediate_response
+ .parse_struct("AuthorizedotnetPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ get_error_response(res, event_builder)
}
}
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index ddcfdfacad2..8069b925d44 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -1,6 +1,7 @@
use common_utils::{
errors::CustomResult,
ext_traits::{Encode, ValueExt},
+ pii,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret};
@@ -8,7 +9,8 @@ use serde::{Deserialize, Serialize};
use crate::{
connector::utils::{
- self, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, WalletData,
+ self, missing_field_err, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData,
+ WalletData,
},
core::errors,
services,
@@ -126,112 +128,18 @@ pub enum WalletMethod {
Applepay,
}
-fn get_pm_and_subsequent_auth_detail(
- item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
-) -> Result<
- (
- PaymentDetails,
- Option<ProcessingOptions>,
- Option<SubsequentAuthInformation>,
- ),
- error_stack::Report<errors::ConnectorError>,
-> {
- match item
- .router_data
- .request
- .mandate_id
- .to_owned()
- .and_then(|mandate_ids| mandate_ids.mandate_reference_id)
- {
- Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => {
- let processing_options = Some(ProcessingOptions {
- is_subsequent_auth: true,
- });
- let subseuent_auth_info = Some(SubsequentAuthInformation {
- original_network_trans_id: Secret::new(network_trans_id),
- reason: Reason::Resubmission,
- });
- match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ref ccard) => {
- let payment_details = PaymentDetails::CreditCard(CreditCardDetails {
- card_number: (*ccard.card_number).clone(),
- expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
- card_code: None,
- });
- Ok((payment_details, processing_options, subseuent_auth_info))
- }
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
- ))?
- }
- }
- }
- Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => {
- match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ref ccard) => {
- Ok((
- PaymentDetails::CreditCard(CreditCardDetails {
- card_number: (*ccard.card_number).clone(),
- // expiration_date: format!("{expiry_year}-{expiry_month}").into(),
- expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
- card_code: Some(ccard.card_cvc.clone()),
- }),
- Some(ProcessingOptions {
- is_subsequent_auth: true,
- }),
- None,
- ))
- }
- domain::PaymentMethodData::Wallet(ref wallet_data) => Ok((
- get_wallet_data(
- wallet_data,
- &item.router_data.request.complete_authorize_url,
- )?,
- None,
- None,
- )),
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
- ))?
- }
- }
- }
- }
-}
-
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct TransactionRequest {
transaction_type: TransactionType,
amount: f64,
currency_code: String,
- payment: PaymentDetails,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ profile: Option<CustomerProfileDetails>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ payment: Option<PaymentDetails>,
order: Order,
+ #[serde(skip_serializing_if = "Option::is_none")]
bill_to: Option<BillTo>,
processing_options: Option<ProcessingOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -239,6 +147,19 @@ struct TransactionRequest {
authorization_indicator_type: Option<AuthorizationIndicator>,
}
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct CustomerProfileDetails {
+ customer_profile_id: Secret<String>,
+ payment_profile: PaymentProfileDetails,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+struct PaymentProfileDetails {
+ payment_profile_id: Secret<String>,
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingOptions {
@@ -312,6 +233,192 @@ pub struct AuthorizedotnetPaymentCancelOrCaptureRequest {
transaction_request: TransactionVoidOrCaptureRequest,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
+pub struct CreateCustomerProfileRequest {
+ create_customer_profile_request: AuthorizedotnetZeroMandateRequest,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AuthorizedotnetZeroMandateRequest {
+ merchant_authentication: AuthorizedotnetAuthType,
+ profile: Profile,
+ validation_mode: ValidationMode,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct Profile {
+ merchant_customer_id: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ description: Option<String>,
+ email: Option<pii::Email>,
+ payment_profiles: PaymentProfiles,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PaymentProfiles {
+ customer_type: CustomerType,
+ payment: PaymentDetails,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum CustomerType {
+ Individual,
+ Business,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ValidationMode {
+ // testMode performs a Luhn mod-10 check on the card number, without further validation at connector.
+ TestMode,
+ // liveMode submits a zero-dollar or one-cent transaction (depending on card type and processor support) to confirm that the card number belongs to an active credit or debit account.
+ LiveMode,
+}
+
+impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
+ match item.request.payment_method_data.clone() {
+ domain::PaymentMethodData::Card(ccard) => {
+ let merchant_authentication =
+ AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
+ let validation_mode = match item.test_mode {
+ Some(true) | None => ValidationMode::TestMode,
+ Some(false) => ValidationMode::LiveMode,
+ };
+ Ok(Self {
+ create_customer_profile_request: AuthorizedotnetZeroMandateRequest {
+ merchant_authentication,
+ profile: Profile {
+ merchant_customer_id: item
+ .customer_id
+ .clone()
+ .ok_or_else(missing_field_err("customer_id"))?,
+ description: item.description.clone(),
+ email: item.request.email.clone(),
+ payment_profiles: PaymentProfiles {
+ customer_type: CustomerType::Individual,
+ payment: PaymentDetails::CreditCard(CreditCardDetails {
+ card_number: (*ccard.card_number).clone(),
+ expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
+ card_code: Some(ccard.card_cvc.clone()),
+ }),
+ },
+ },
+ validation_mode,
+ },
+ })
+ }
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::Upi(_)
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
+ ))?
+ }
+ }
+ }
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AuthorizedotnetSetupMandateResponse {
+ customer_profile_id: Option<String>,
+ customer_payment_profile_id_list: Vec<String>,
+ validation_direct_response_list: Option<Vec<Secret<String>>>,
+ pub messages: ResponseMessages,
+}
+
+// zero dollar response
+impl<F, T>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ AuthorizedotnetSetupMandateResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ AuthorizedotnetSetupMandateResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ match item.response.messages.result_code {
+ ResultCode::Ok => Ok(Self {
+ status: enums::AttemptStatus::Charged,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::NoResponseId,
+ redirection_data: None,
+ mandate_reference: item.response.customer_profile_id.map(|mandate_id| {
+ types::MandateReference {
+ connector_mandate_id: Some(mandate_id),
+ payment_method_id: item
+ .response
+ .customer_payment_profile_id_list
+ .first()
+ .cloned(),
+ }
+ }),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ }),
+ ..item.data
+ }),
+ ResultCode::Error => {
+ let error_code = match item.response.messages.message.first() {
+ Some(first_error_message) => first_error_message.code.clone(),
+ None => crate::consts::NO_ERROR_CODE.to_string(),
+ };
+ let error_reason = item
+ .response
+ .messages
+ .message
+ .iter()
+ .map(|error: &ResponseMessage| error.text.clone())
+ .collect::<Vec<String>>()
+ .join(" ");
+ let response = Err(types::ErrorResponse {
+ code: error_code,
+ message: item.response.messages.result_code.to_string(),
+ reason: Some(error_reason),
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: None,
+ });
+ Ok(Self {
+ response,
+ status: enums::AttemptStatus::Failure,
+ ..item.data
+ })
+ }
+ }
+ }
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
@@ -353,31 +460,153 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
fn try_from(
item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
- let (payment_details, processing_options, subsequent_auth_information) =
- get_pm_and_subsequent_auth_detail(item)?;
+ let (payment_details, processing_options, subsequent_auth_information, profile) = match item
+ .router_data
+ .request
+ .mandate_id
+ .to_owned()
+ .and_then(|mandate_ids| mandate_ids.mandate_reference_id)
+ {
+ Some(api_models::payments::MandateReferenceId::NetworkMandateId(network_trans_id)) => {
+ let processing_options = Some(ProcessingOptions {
+ is_subsequent_auth: true,
+ });
+ let subsequent_auth_info = Some(SubsequentAuthInformation {
+ original_network_trans_id: Secret::new(network_trans_id),
+ reason: Reason::Resubmission,
+ });
+ match item.router_data.request.payment_method_data {
+ domain::PaymentMethodData::Card(ref ccard) => {
+ let payment_details = PaymentDetails::CreditCard(CreditCardDetails {
+ card_number: (*ccard.card_number).clone(),
+ expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
+ card_code: None,
+ });
+ (
+ Some(payment_details),
+ processing_options,
+ subsequent_auth_info,
+ None,
+ )
+ }
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::Upi(_)
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message(
+ "authorizedotnet",
+ ),
+ ))?
+ }
+ }
+ }
+ Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
+ connector_mandate_id,
+ )) => (
+ None,
+ Some(ProcessingOptions {
+ is_subsequent_auth: true,
+ }),
+ None,
+ Some(CustomerProfileDetails {
+ customer_profile_id: Secret::from(
+ connector_mandate_id
+ .connector_mandate_id
+ .ok_or(errors::ConnectorError::MissingConnectorMandateID)?,
+ ),
+ payment_profile: PaymentProfileDetails {
+ payment_profile_id: Secret::from(
+ connector_mandate_id
+ .payment_method_id
+ .ok_or(errors::ConnectorError::MissingConnectorMandateID)?,
+ ),
+ },
+ }),
+ ),
+ None => {
+ match item.router_data.request.payment_method_data {
+ domain::PaymentMethodData::Card(ref ccard) => {
+ (
+ Some(PaymentDetails::CreditCard(CreditCardDetails {
+ card_number: (*ccard.card_number).clone(),
+ // expiration_date: format!("{expiry_year}-{expiry_month}").into(),
+ expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
+ card_code: Some(ccard.card_cvc.clone()),
+ })),
+ Some(ProcessingOptions {
+ is_subsequent_auth: true,
+ }),
+ None,
+ None,
+ )
+ }
+ domain::PaymentMethodData::Wallet(ref wallet_data) => (
+ Some(get_wallet_data(
+ wallet_data,
+ &item.router_data.request.complete_authorize_url,
+ )?),
+ None,
+ None,
+ None,
+ ),
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::Upi(_)
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message(
+ "authorizedotnet",
+ ),
+ ))?
+ }
+ }
+ }
+ };
let authorization_indicator_type = match item.router_data.request.capture_method {
Some(capture_method) => Some(AuthorizationIndicator {
authorization_indicator: capture_method.try_into()?,
}),
None => None,
};
- let bill_to = item
- .router_data
- .get_optional_billing()
- .and_then(|billing_address| billing_address.address.as_ref())
- .map(|address| BillTo {
- first_name: address.first_name.clone(),
- last_name: address.last_name.clone(),
- address: address.line1.clone(),
- city: address.city.clone(),
- state: address.state.clone(),
- zip: address.zip.clone(),
- country: address.country,
- });
+ let bill_to = match profile {
+ Some(_) => None,
+ None => item
+ .router_data
+ .get_optional_billing()
+ .and_then(|billing_address| billing_address.address.as_ref())
+ .map(|address| BillTo {
+ first_name: address.first_name.clone(),
+ last_name: address.last_name.clone(),
+ address: address.line1.clone(),
+ city: address.city.clone(),
+ state: address.state.clone(),
+ zip: address.zip.clone(),
+ country: address.country,
+ }),
+ };
let transaction_request = TransactionRequest {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency.to_string(),
+ profile,
payment: payment_details,
order: Order {
description: item.router_data.connector_request_reference_id.clone(),
@@ -506,7 +735,7 @@ pub struct ResponseMessage {
pub text: String,
}
-#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)]
+#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize, strum::Display)]
enum ResultCode {
#[default]
Ok,
|
2024-05-20T10:00:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Zero dollar mandates are implemented for connector Authorizedotnet.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4702
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
_Note: `test_mode` should be set to `true` while testing._
- Create Zero Amount Mandate:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 0,
"currency": "USD",
"confirm": true,
"customer_id": "tester123",
"email": "johndoe@gmail.com",
"setup_future_usage": "off_session",
"payment_type": "setup_mandate",
"off_session": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"card_cvc": "123"
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 1000,
"currency": "USD",
"start_date": "2023-04-21T00:00:00Z",
"end_date": "2023-05-21T00:00:00Z",
"metadata": {
"frequency": "13"
}
}
}
}
}'
```
Response:
```
{
"payment_id": "pay_BUTzOloWgy5ZjPUjOhDR",
"merchant_id": "merchant_1709720492",
"status": "succeeded",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "pay_BUTzOloWgy5ZjPUjOhDR_secret_aQaDNrV3HKhGHZnLcWet",
"created": "2024-05-21T13:43:09.180Z",
"currency": "USD",
"customer_id": "tester123",
"customer": {
"id": "tester123",
"name": null,
"email": "johndoe@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8",
"mandate_data": {
"update_mandate_id": null,
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 1000,
"currency": "USD",
"start_date": "2023-04-21T00:00:00.000Z",
"end_date": "2023-05-21T00:00:00.000Z",
"metadata": {
"frequency": "13"
}
}
}
},
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "johndoe@gmail.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester123",
"created_at": 1716298989,
"expires": 1716302589,
"secret": "epk_1cdb048e685f43f9ad8b1f1c20b5142b"
},
"manual_retry_allowed": false,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_4aXJeUeyy9BzdhcV9Xue",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-21T13:58:09.180Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_eAcvFw4WhUlfAGyeya52",
"payment_method_status": null,
"updated": "2024-05-21T13:43:09.865Z",
"frm_metadata": null
}
```
- Create Payment Using Mandate:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 400,
"currency": "USD",
"confirm": true,
"customer_id": "tester123",
"mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8",
"off_session": true
}'
```
Response:
```
{
"payment_id": "pay_BYA7GLOyizx2lXr7HY8l",
"merchant_id": "merchant_1709720492",
"status": "succeeded",
"amount": 400,
"net_amount": 400,
"amount_capturable": 0,
"amount_received": 400,
"connector": "authorizedotnet",
"client_secret": "pay_BYA7GLOyizx2lXr7HY8l_secret_eyykmbXcMfPnc4m9Vbid",
"created": "2024-05-21T13:47:00.958Z",
"currency": "USD",
"customer_id": "tester123",
"customer": {
"id": "tester123",
"name": null,
"email": "johndoe@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8",
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": "3906c467-f517-40a1-bb0f-a10c4e6f9878",
"shipping": null,
"billing": null,
"order_details": null,
"email": "johndoe@gmail.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester123",
"created_at": 1716299220,
"expires": 1716302820,
"secret": "epk_866be4c4a3de481b808853b80a5c5198"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80018772612",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80018772612",
"payment_link": null,
"profile_id": "pro_4aXJeUeyy9BzdhcV9Xue",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-21T14:02:00.957Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_eAcvFw4WhUlfAGyeya52",
"payment_method_status": "active",
"updated": "2024-05-21T13:47:03.437Z",
"frm_metadata": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
0f53f74d26e829602519998c41a460dc9a4809af
|
_Note: `test_mode` should be set to `true` while testing._
- Create Zero Amount Mandate:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 0,
"currency": "USD",
"confirm": true,
"customer_id": "tester123",
"email": "johndoe@gmail.com",
"setup_future_usage": "off_session",
"payment_type": "setup_mandate",
"off_session": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"card_cvc": "123"
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 1000,
"currency": "USD",
"start_date": "2023-04-21T00:00:00Z",
"end_date": "2023-05-21T00:00:00Z",
"metadata": {
"frequency": "13"
}
}
}
}
}'
```
Response:
```
{
"payment_id": "pay_BUTzOloWgy5ZjPUjOhDR",
"merchant_id": "merchant_1709720492",
"status": "succeeded",
"amount": 0,
"net_amount": 0,
"amount_capturable": 0,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "pay_BUTzOloWgy5ZjPUjOhDR_secret_aQaDNrV3HKhGHZnLcWet",
"created": "2024-05-21T13:43:09.180Z",
"currency": "USD",
"customer_id": "tester123",
"customer": {
"id": "tester123",
"name": null,
"email": "johndoe@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8",
"mandate_data": {
"update_mandate_id": null,
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 1000,
"currency": "USD",
"start_date": "2023-04-21T00:00:00.000Z",
"end_date": "2023-05-21T00:00:00.000Z",
"metadata": {
"frequency": "13"
}
}
}
},
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "johndoe@gmail.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester123",
"created_at": 1716298989,
"expires": 1716302589,
"secret": "epk_1cdb048e685f43f9ad8b1f1c20b5142b"
},
"manual_retry_allowed": false,
"connector_transaction_id": null,
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_4aXJeUeyy9BzdhcV9Xue",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-21T13:58:09.180Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_eAcvFw4WhUlfAGyeya52",
"payment_method_status": null,
"updated": "2024-05-21T13:43:09.865Z",
"frm_metadata": null
}
```
- Create Payment Using Mandate:
Request:
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 400,
"currency": "USD",
"confirm": true,
"customer_id": "tester123",
"mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8",
"off_session": true
}'
```
Response:
```
{
"payment_id": "pay_BYA7GLOyizx2lXr7HY8l",
"merchant_id": "merchant_1709720492",
"status": "succeeded",
"amount": 400,
"net_amount": 400,
"amount_capturable": 0,
"amount_received": 400,
"connector": "authorizedotnet",
"client_secret": "pay_BYA7GLOyizx2lXr7HY8l_secret_eyykmbXcMfPnc4m9Vbid",
"created": "2024-05-21T13:47:00.958Z",
"currency": "USD",
"customer_id": "tester123",
"customer": {
"id": "tester123",
"name": null,
"email": "johndoe@gmail.com",
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": "man_SJ0R3Dx1krNV2OYYXqK8",
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1111",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411111",
"card_extended_bin": null,
"card_exp_month": "07",
"card_exp_year": "26",
"card_holder_name": "Joseph Does",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": "3906c467-f517-40a1-bb0f-a10c4e6f9878",
"shipping": null,
"billing": null,
"order_details": null,
"email": "johndoe@gmail.com",
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "tester123",
"created_at": 1716299220,
"expires": 1716302820,
"secret": "epk_866be4c4a3de481b808853b80a5c5198"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80018772612",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80018772612",
"payment_link": null,
"profile_id": "pro_4aXJeUeyy9BzdhcV9Xue",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_3mX9fbzXfxIkG0uwmy2D",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-21T14:02:00.957Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": "pm_eAcvFw4WhUlfAGyeya52",
"payment_method_status": "active",
"updated": "2024-05-21T13:47:03.437Z",
"frm_metadata": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4700
|
Bug: [FEATURE] Constraint Graph visualization (via GraphViz) functionality
### Feature Description
It would be good for developers to be able to visualize constraint graphs for intuition and debugging purposes. This can be done by allowing the constraint graph to describe its structure in the form of a DOT program, which can then be visualized using GraphViz.
### Possible Implementation
The idea is to use a Rust crate that allows us to take any constraint graph and convert its edges and nodes into a GraphViz Digraph in the DOT DSL which can then be used to generate a diagram using any DOT-compatible CLI/UI tool.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/Cargo.lock b/Cargo.lock
index abc265ad692..3f9bd9a6303 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2617,6 +2617,21 @@ dependencies = [
"const-random",
]
+[[package]]
+name = "dot-generator"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0aaac7ada45f71873ebce336491d1c1bc4a7c8042c7cea978168ad59e805b871"
+dependencies = [
+ "dot-structures",
+]
+
+[[package]]
+name = "dot-structures"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "675e35c02a51bb4d4618cb4885b3839ce6d1787c97b664474d9208d074742e20"
+
[[package]]
name = "dotenvy"
version = "0.15.7"
@@ -3252,6 +3267,22 @@ dependencies = [
"walkdir",
]
+[[package]]
+name = "graphviz-rust"
+version = "0.6.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27dafd1ac303e0dfb347a3861d9ac440859bab26ec2f534bbceb262ea492a1e0"
+dependencies = [
+ "dot-generator",
+ "dot-structures",
+ "into-attr",
+ "into-attr-derive",
+ "pest",
+ "pest_derive",
+ "rand",
+ "tempfile",
+]
+
[[package]]
name = "h2"
version = "0.3.25"
@@ -3623,6 +3654,7 @@ name = "hyperswitch_constraint_graph"
version = "0.1.0"
dependencies = [
"erased-serde 0.3.31",
+ "graphviz-rust",
"rustc-hash",
"serde",
"serde_json",
@@ -3773,6 +3805,28 @@ dependencies = [
"cfg-if 1.0.0",
]
+[[package]]
+name = "into-attr"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "18b48c537e49a709e678caec3753a7dba6854661a1eaa27675024283b3f8b376"
+dependencies = [
+ "dot-structures",
+]
+
+[[package]]
+name = "into-attr-derive"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecac7c1ae6cd2c6a3a64d1061a8bdc7f52ff62c26a831a2301e54c1b5d70d5b1"
+dependencies = [
+ "dot-generator",
+ "dot-structures",
+ "into-attr",
+ "quote",
+ "syn 1.0.109",
+]
+
[[package]]
name = "iovec"
version = "0.1.4"
diff --git a/crates/euclid/Cargo.toml b/crates/euclid/Cargo.toml
index 3341746ab74..b408c013572 100644
--- a/crates/euclid/Cargo.toml
+++ b/crates/euclid/Cargo.toml
@@ -21,7 +21,7 @@ utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order
# First party dependencies
common_enums = { version = "0.1.0", path = "../common_enums" }
-hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" }
+hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] }
euclid_macros = { version = "0.1.0", path = "../euclid_macros" }
[features]
diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs
index 0ffafe4d48b..1c476ee81b2 100644
--- a/crates/euclid/src/dssa/graph.rs
+++ b/crates/euclid/src/dssa/graph.rs
@@ -22,6 +22,12 @@ pub mod euclid_graph_prelude {
impl cgraph::KeyNode for dir::DirKey {}
+impl cgraph::NodeViz for dir::DirKey {
+ fn viz(&self) -> String {
+ self.kind.to_string()
+ }
+}
+
impl cgraph::ValueNode for dir::DirValue {
type Key = dir::DirKey;
@@ -30,6 +36,41 @@ impl cgraph::ValueNode for dir::DirValue {
}
}
+impl cgraph::NodeViz for dir::DirValue {
+ fn viz(&self) -> String {
+ match self {
+ Self::PaymentMethod(pm) => pm.to_string(),
+ Self::CardBin(bin) => bin.value.clone(),
+ Self::CardType(ct) => ct.to_string(),
+ Self::CardNetwork(cn) => cn.to_string(),
+ Self::PayLaterType(plt) => plt.to_string(),
+ Self::WalletType(wt) => wt.to_string(),
+ Self::UpiType(ut) => ut.to_string(),
+ Self::BankTransferType(btt) => btt.to_string(),
+ Self::BankRedirectType(brt) => brt.to_string(),
+ Self::BankDebitType(bdt) => bdt.to_string(),
+ Self::CryptoType(ct) => ct.to_string(),
+ Self::RewardType(rt) => rt.to_string(),
+ Self::PaymentAmount(amt) => amt.number.to_string(),
+ Self::PaymentCurrency(curr) => curr.to_string(),
+ Self::AuthenticationType(at) => at.to_string(),
+ Self::CaptureMethod(cm) => cm.to_string(),
+ Self::BusinessCountry(bc) => bc.to_string(),
+ Self::BillingCountry(bc) => bc.to_string(),
+ Self::Connector(conn) => conn.connector.to_string(),
+ Self::MetaData(mv) => format!("[{} = {}]", mv.key, mv.value),
+ Self::MandateAcceptanceType(mat) => mat.to_string(),
+ Self::MandateType(mt) => mt.to_string(),
+ Self::PaymentType(pt) => pt.to_string(),
+ Self::VoucherType(vt) => vt.to_string(),
+ Self::GiftCardType(gct) => gct.to_string(),
+ Self::BusinessLabel(bl) => bl.value.to_string(),
+ Self::SetupFutureUsage(sfu) => sfu.to_string(),
+ Self::CardRedirectType(crt) => crt.to_string(),
+ }
+ }
+}
+
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", content = "details", rename_all = "snake_case")]
pub enum AnalysisError<V: cgraph::ValueNode> {
diff --git a/crates/euclid/src/frontend/dir.rs b/crates/euclid/src/frontend/dir.rs
index 455330fcf76..bc16057fbb5 100644
--- a/crates/euclid/src/frontend/dir.rs
+++ b/crates/euclid/src/frontend/dir.rs
@@ -289,7 +289,6 @@ pub enum DirKeyKind {
#[serde(rename = "billing_country")]
BillingCountry,
#[serde(skip_deserializing, rename = "connector")]
- #[strum(disabled)]
Connector,
#[strum(
serialize = "business_label",
diff --git a/crates/hyperswitch_constraint_graph/Cargo.toml b/crates/hyperswitch_constraint_graph/Cargo.toml
index 425855a05b0..4fe97b2b1ac 100644
--- a/crates/hyperswitch_constraint_graph/Cargo.toml
+++ b/crates/hyperswitch_constraint_graph/Cargo.toml
@@ -7,8 +7,12 @@ rust-version.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+[features]
+viz = ["dep:graphviz-rust"]
+
[dependencies]
erased-serde = "0.3.28"
+graphviz-rust = { version = "0.6.2", optional = true }
rustc-hash = "1.1.0"
serde = { version = "1.0.163", features = ["derive", "rc"] }
serde_json = "1.0.96"
diff --git a/crates/hyperswitch_constraint_graph/src/graph.rs b/crates/hyperswitch_constraint_graph/src/graph.rs
index d0a98e19520..6aed505728e 100644
--- a/crates/hyperswitch_constraint_graph/src/graph.rs
+++ b/crates/hyperswitch_constraint_graph/src/graph.rs
@@ -585,3 +585,92 @@ where
Ok(node_builder.build())
}
}
+
+#[cfg(feature = "viz")]
+mod viz {
+ use graphviz_rust::{
+ dot_generator::*,
+ dot_structures::*,
+ printer::{DotPrinter, PrinterContext},
+ };
+
+ use crate::{dense_map::EntityId, types, ConstraintGraph, NodeViz, ValueNode};
+
+ fn get_node_id(node_id: types::NodeId) -> String {
+ format!("N{}", node_id.get_id())
+ }
+
+ impl<'a, V> ConstraintGraph<'a, V>
+ where
+ V: ValueNode + NodeViz,
+ <V as ValueNode>::Key: NodeViz,
+ {
+ fn get_node_label(node: &types::Node<V>) -> String {
+ let label = match &node.node_type {
+ types::NodeType::Value(types::NodeValue::Key(key)) => format!("any {}", key.viz()),
+ types::NodeType::Value(types::NodeValue::Value(val)) => {
+ format!("{} = {}", val.get_key().viz(), val.viz())
+ }
+ types::NodeType::AllAggregator => "&&".to_string(),
+ types::NodeType::AnyAggregator => "| |".to_string(),
+ types::NodeType::InAggregator(agg) => {
+ let key = if let Some(val) = agg.iter().next() {
+ val.get_key().viz()
+ } else {
+ return "empty in".to_string();
+ };
+
+ let nodes = agg.iter().map(NodeViz::viz).collect::<Vec<_>>();
+ format!("{key} in [{}]", nodes.join(", "))
+ }
+ };
+
+ format!("\"{label}\"")
+ }
+
+ fn build_node(cg_node_id: types::NodeId, cg_node: &types::Node<V>) -> Node {
+ let viz_node_id = get_node_id(cg_node_id);
+ let viz_node_label = Self::get_node_label(cg_node);
+
+ node!(viz_node_id; attr!("label", viz_node_label))
+ }
+
+ fn build_edge(cg_edge: &types::Edge) -> Edge {
+ let pred_vertex = get_node_id(cg_edge.pred);
+ let succ_vertex = get_node_id(cg_edge.succ);
+ let arrowhead = match cg_edge.strength {
+ types::Strength::Weak => "onormal",
+ types::Strength::Normal => "normal",
+ types::Strength::Strong => "normalnormal",
+ };
+ let color = match cg_edge.relation {
+ types::Relation::Positive => "blue",
+ types::Relation::Negative => "red",
+ };
+
+ edge!(
+ node_id!(pred_vertex) => node_id!(succ_vertex);
+ attr!("arrowhead", arrowhead),
+ attr!("color", color)
+ )
+ }
+
+ pub fn get_viz_digraph(&self) -> Graph {
+ graph!(
+ strict di id!("constraint_graph"),
+ self.nodes
+ .iter()
+ .map(|(node_id, node)| Self::build_node(node_id, node))
+ .map(Stmt::Node)
+ .chain(self.edges.values().map(Self::build_edge).map(Stmt::Edge))
+ .collect::<Vec<_>>()
+ )
+ }
+
+ pub fn get_viz_digraph_string(&self) -> String {
+ let mut ctx = PrinterContext::default();
+ let digraph = self.get_viz_digraph();
+ digraph.print(&mut ctx)
+ }
+ }
+}
diff --git a/crates/hyperswitch_constraint_graph/src/lib.rs b/crates/hyperswitch_constraint_graph/src/lib.rs
index ade9a64272f..6877169732c 100644
--- a/crates/hyperswitch_constraint_graph/src/lib.rs
+++ b/crates/hyperswitch_constraint_graph/src/lib.rs
@@ -7,6 +7,8 @@ pub mod types;
pub use builder::ConstraintGraphBuilder;
pub use error::{AnalysisTrace, GraphError};
pub use graph::ConstraintGraph;
+#[cfg(feature = "viz")]
+pub use types::NodeViz;
pub use types::{
CheckingContext, CycleCheck, DomainId, DomainIdentifier, Edge, EdgeId, KeyNode, Memoization,
Node, NodeId, NodeValue, Relation, Strength, ValueNode,
diff --git a/crates/hyperswitch_constraint_graph/src/types.rs b/crates/hyperswitch_constraint_graph/src/types.rs
index d1d14bd7e5c..51818f2fee5 100644
--- a/crates/hyperswitch_constraint_graph/src/types.rs
+++ b/crates/hyperswitch_constraint_graph/src/types.rs
@@ -17,6 +17,11 @@ pub trait ValueNode: fmt::Debug + Clone + hash::Hash + serde::Serialize + Partia
fn get_key(&self) -> Self::Key;
}
+#[cfg(feature = "viz")]
+pub trait NodeViz {
+ fn viz(&self) -> String;
+}
+
#[derive(Debug, Clone, Copy, serde::Serialize, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct NodeId(usize);
diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml
index 86de6002c32..2f570fcac57 100644
--- a/crates/kgraph_utils/Cargo.toml
+++ b/crates/kgraph_utils/Cargo.toml
@@ -13,7 +13,7 @@ connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connect
[dependencies]
api_models = { version = "0.1.0", path = "../api_models", package = "api_models" }
common_enums = { version = "0.1.0", path = "../common_enums" }
-hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph" }
+hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] }
euclid = { version = "0.1.0", path = "../euclid" }
masking = { version = "0.1.0", path = "../masking/" }
|
2024-05-20T09:56:07Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR adds functionality to the constraint graph that allows the graph to describe its structure by generating a DOT program, which can then be visualized by the user through GraphViz.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Being able to visualize a constraint graph would aid with intuition and debugging.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
compiler guided. No API tests required since this is purely a developer-focused feature and does not touch any business logic code.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
be9343affeb178e646d4046785a105a9c6040037
|
compiler guided. No API tests required since this is purely a developer-focused feature and does not touch any business logic code.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4682
|
Bug: Add audit events for PaymentUpdate update
Created from #4525
This covers adding events for PaymentUpdate operation
This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166)
It should also include any metadata for the event
e.g reason for payment rejection, error codes, rejection source etc
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
|
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 9005e94c962..2f1a0c333fa 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -25,6 +25,7 @@ use crate::{
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -694,7 +695,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut _payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: storage_enums::MerchantStorageScheme,
@@ -714,7 +715,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -925,6 +926,12 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let amount = payment_data.amount;
+ req_state
+ .event_context
+ .event(AuditEvent::new(AuditEventType::PaymentUpdate { amount }))
+ .with(payment_data.to_event())
+ .emit();
Ok((
payments::is_confirm(self, payment_data.confirm),
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index 9fbd754b43c..a6b0884d21d 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -1,3 +1,4 @@
+use api_models::payments::Amount;
use common_utils::types::MinorUnit;
use diesel_models::fraud_check::FraudCheck;
use events::{Event, EventInfo};
@@ -27,6 +28,9 @@ pub enum AuditEventType {
capture_amount: Option<MinorUnit>,
multiple_capture_count: Option<i16>,
},
+ PaymentUpdate {
+ amount: Amount,
+ },
PaymentApprove,
PaymentCreate,
}
@@ -67,6 +71,7 @@ impl Event for AuditEvent {
AuditEventType::RefundSuccess => "refund_success",
AuditEventType::RefundFail => "refund_fail",
AuditEventType::PaymentCancelled { .. } => "payment_cancelled",
+ AuditEventType::PaymentUpdate { .. } => "payment_update",
AuditEventType::PaymentApprove { .. } => "payment_approve",
AuditEventType::PaymentCreate { .. } => "payment_create",
};
|
2024-10-24T11:03:29Z
|
## Type of Change
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR adds an Audit event for the PaymentUpdate operation.
### Additional Changes
- [x] This PR modifies the files below
- `crates/router/src/core/payments/operations/payment_update.rs`
- `crates/router/src/events/audit_events.rs`
## Motivation and Context
This PR fixes #4682
## How did you test it
- Hit the `Payments - Create` endpoint.
Make a payment with `"confirm": false`
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"profile_id": "pro_v5sFoHe80OeiUlIonocM"
}'
```
- Now hit the `Payments - Update` endpoint.
```bash
{
"amount": 20000,
"currency": "SGD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 20000,
"email": "joseph@example.com",
"name": "joseph Doe",
"phone": "8888888888",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"payment_method": "card",
"return_url": "https://google.com",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
Audit log will get generated and can be viewed in hyperswitch-audit-events topic in kafka with `PaymentUpdate` event-type.
Amount parameter can be verified in the event.
<img width="1424" alt="Screenshot 2024-11-07 at 12 42 34 PM" src="https://github.com/user-attachments/assets/e4dfdef5-495b-48ad-938a-8053d0271408">
<img width="1458" alt="Screenshot 2024-11-07 at 12 42 42 PM" src="https://github.com/user-attachments/assets/2b39e2bb-6200-4184-84ed-0b913d0f437f">
Now payment can be completed by hitting the `Payments - Confirm` endpoint.
## Checklist
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
fe4931a37e6030ea03ca83540f9a21877c7b6b34
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4699
|
Bug: [FEATURE]: Add a new endpoint Complete Authorize
### Feature Description
Add a new endpoint Complete Authorize
### Possible Implementation
- This will be used in the cases where we get shipping after confirm call and we need to call the connector 2nd time.
- Collect shipping address in complete authorize call
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index 59e65c0605f..cd1671b2b8e 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -11,10 +11,10 @@ use crate::{
ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints,
PaymentListFilterConstraints, PaymentListFilters, PaymentListFiltersV2,
PaymentListResponse, PaymentListResponseV2, PaymentsApproveRequest, PaymentsCancelRequest,
- PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest,
- PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest,
- PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest,
- PaymentsStartRequest, RedirectionResponse,
+ PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,
+ PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse,
+ PaymentsIncrementalAuthorizationRequest, PaymentsRejectRequest, PaymentsRequest,
+ PaymentsResponse, PaymentsRetrieveRequest, PaymentsStartRequest, RedirectionResponse,
},
};
impl ApiEventMetric for PaymentsRetrieveRequest {
@@ -44,6 +44,14 @@ impl ApiEventMetric for PaymentsCaptureRequest {
}
}
+impl ApiEventMetric for PaymentsCompleteAuthorizeRequest {
+ fn get_api_event_type(&self) -> Option<ApiEventsType> {
+ Some(ApiEventsType::Payment {
+ payment_id: self.payment_id.clone(),
+ })
+ }
+}
+
impl ApiEventMetric for PaymentsCancelRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index f00be78a039..8f4fca59d26 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4343,6 +4343,18 @@ pub struct PaymentRetrieveBodyWithCredentials {
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
}
+#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+pub struct PaymentsCompleteAuthorizeRequest {
+ /// The unique identifier for the payment
+ #[serde(skip_deserializing)]
+ pub payment_id: String,
+ /// The shipping address for the payment
+ pub shipping: Option<Address>,
+ /// Client Secret
+ #[schema(value_type = String)]
+ pub client_secret: Secret<String>,
+}
+
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentsCancelRequest {
/// The identifier for the payment
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index d65fa6868b9..660db4d8b8b 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -202,6 +202,9 @@ pub enum PaymentIntentUpdate {
AuthorizationCountUpdate {
authorization_count: i32,
},
+ CompleteAuthorizeUpdate {
+ shipping_address_id: Option<String>,
+ },
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -503,6 +506,12 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
authorization_count: Some(authorization_count),
..Default::default()
},
+ PaymentIntentUpdate::CompleteAuthorizeUpdate {
+ shipping_address_id,
+ } => Self {
+ shipping_address_id,
+ ..Default::default()
+ },
}
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 84dc56403c6..1322e66a149 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -203,6 +203,9 @@ pub enum PaymentIntentUpdate {
AuthorizationCountUpdate {
authorization_count: i32,
},
+ CompleteAuthorizeUpdate {
+ shipping_address_id: Option<String>,
+ },
}
#[derive(Clone, Debug, Default)]
@@ -425,6 +428,12 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
authorization_count: Some(authorization_count),
..Default::default()
},
+ PaymentIntentUpdate::CompleteAuthorizeUpdate {
+ shipping_address_id,
+ } => Self {
+ shipping_address_id,
+ ..Default::default()
+ },
}
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 5f5597387b1..018ea342099 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -81,6 +81,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::payments::payments_incremental_authorization,
routes::payment_link::payment_link_retrieve,
routes::payments::payments_external_authentication,
+ routes::payments::payments_complete_authorize,
// Routes for refunds
routes::refunds::refunds_create,
@@ -402,6 +403,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::CaptureResponse,
api_models::payments::PaymentsIncrementalAuthorizationRequest,
api_models::payments::IncrementalAuthorizationResponse,
+ api_models::payments::PaymentsCompleteAuthorizeRequest,
api_models::payments::PaymentsExternalAuthenticationRequest,
api_models::payments::PaymentsExternalAuthenticationResponse,
api_models::payments::SdkInformation,
diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs
index 20d87b91e79..1273bde7a36 100644
--- a/crates/openapi/src/routes/payments.rs
+++ b/crates/openapi/src/routes/payments.rs
@@ -486,3 +486,23 @@ pub fn payments_incremental_authorization() {}
security(("publishable_key" = []))
)]
pub fn payments_external_authentication() {}
+
+/// Payments - Complete Authorize
+///
+///
+#[utoipa::path(
+ post,
+ path = "/{payment_id}/complete_authorize",
+ request_body=PaymentsCompleteAuthorizeRequest,
+ params(
+ ("payment_id" =String, Path, description = "The identifier for payment")
+ ),
+ responses(
+ (status = 200, description = "Payments Complete Authorize Success", body = PaymentsResponse),
+ (status = 400, description = "Missing mandatory fields")
+ ),
+ tag = "Payments",
+ operation_id = "Complete Authorize a Payment",
+ security(("publishable_key" = []))
+)]
+pub fn payments_complete_authorize() {}
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index a9736516725..3f57ba2830f 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -59,6 +59,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
.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,
&[
@@ -173,16 +175,22 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
.or_else(|| request.customer_id.clone()),
)?;
- let shipping_address = helpers::get_address_by_id(
+ let shipping_address = helpers::create_or_update_address_for_payment_by_request(
db,
- payment_intent.shipping_address_id.clone(),
+ request.shipping.as_ref(),
+ payment_intent.shipping_address_id.clone().as_deref(),
+ merchant_id.as_ref(),
+ payment_intent.customer_id.as_ref(),
key_store,
- &payment_intent.payment_id,
- merchant_id,
- merchant_account.storage_scheme,
+ payment_id.as_ref(),
+ 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(
db,
payment_intent.billing_address_id.clone(),
@@ -421,11 +429,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
- _state: &'b AppState,
+ state: &'b AppState,
_req_state: ReqState,
- payment_data: PaymentData<F>,
+ mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
- _storage_scheme: storage_enums::MerchantStorageScheme,
+ storage_scheme: storage_enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
_merchant_key_store: &domain::MerchantKeyStore,
_frm_suggestion: Option<FrmSuggestion>,
@@ -434,6 +442,19 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple
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(payment_intent, payment_intent_update, storage_scheme)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ payment_data.payment_intent = updated_payment_intent;
Ok((Box::new(self), payment_data))
}
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 21cc994381e..ba8dd94b332 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -386,7 +386,11 @@ impl Payments {
)
.service(
web::resource("/{payment_id}/{merchant_id}/redirect/complete/{connector}")
- .route(web::get().to(payments_complete_authorize))
+ .route(web::get().to(payments_complete_authorize_redirect))
+ .route(web::post().to(payments_complete_authorize_redirect)),
+ )
+ .service(
+ web::resource("/{payment_id}/complete_authorize")
.route(web::post().to(payments_complete_authorize)),
)
.service(
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 30b582079e3..6a73643ce68 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -121,7 +121,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentsIncrementalAuthorization
| Flow::PaymentsExternalAuthentication
| Flow::PaymentsAuthorize
- | Flow::GetExtendedCardInfo => Self::Payments,
+ | Flow::GetExtendedCardInfo
+ | Flow::PaymentsCompleteAuthorize => Self::Payments,
Flow::PayoutsCreate
| Flow::PayoutsRetrieve
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 06bdd3ed05a..f28cad89004 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -7,6 +7,7 @@ pub mod helpers;
use actix_web::{web, Responder};
use api_models::payments::HeaderPayload;
use error_stack::report;
+use masking::PeekInterface;
use router_env::{env, instrument, tracing, types, Flow};
use super::app::ReqState;
@@ -749,7 +750,7 @@ pub async fn payments_redirect_response_with_creds_identifier(
.await
}
#[instrument(skip_all, fields(flow =? Flow::PaymentsRedirect, payment_id))]
-pub async fn payments_complete_authorize(
+pub async fn payments_complete_authorize_redirect(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
@@ -792,6 +793,70 @@ pub async fn payments_complete_authorize(
)
.await
}
+
+/// Payments - Complete Authorize
+#[instrument(skip_all, fields(flow =? Flow::PaymentsCompleteAuthorize, payment_id))]
+pub async fn payments_complete_authorize(
+ state: web::Data<app::AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<payment_types::PaymentsCompleteAuthorizeRequest>,
+ path: web::Path<String>,
+) -> impl Responder {
+ let flow = Flow::PaymentsCompleteAuthorize;
+ let mut payload = json_payload.into_inner();
+
+ let payment_id = path.into_inner();
+ payload.payment_id.clone_from(&payment_id);
+
+ tracing::Span::current().record("payment_id", &payment_id);
+
+ let payment_confirm_req = payment_types::PaymentsRequest {
+ payment_id: Some(payment_types::PaymentIdType::PaymentIntentId(
+ payment_id.clone(),
+ )),
+ shipping: payload.shipping.clone(),
+ client_secret: Some(payload.client_secret.peek().clone()),
+ ..Default::default()
+ };
+
+ let (auth_type, auth_flow) =
+ match auth::check_client_secret_and_get_auth(req.headers(), &payment_confirm_req) {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(report!(err)),
+ };
+
+ let locking_action = payload.get_locking_input(flow.clone());
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, _req, req_state| {
+ payments::payments_core::<
+ api_types::CompleteAuthorize,
+ payment_types::PaymentsResponse,
+ _,
+ _,
+ _,
+ >(
+ state.clone(),
+ req_state,
+ auth.merchant_account,
+ auth.key_store,
+ payments::operations::payment_complete_authorize::CompleteAuthorize,
+ payment_confirm_req.clone(),
+ auth_flow,
+ payments::CallConnectorAction::Trigger,
+ None,
+ HeaderPayload::default(),
+ )
+ },
+ &*auth_type,
+ locking_action,
+ ))
+ .await
+}
+
/// Payments - Cancel
///
/// A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action
@@ -1465,6 +1530,22 @@ impl GetLockingInput for payments::PaymentsRedirectResponseData {
}
}
+impl GetLockingInput for payment_types::PaymentsCompleteAuthorizeRequest {
+ fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
+ where
+ F: types::FlowMetric,
+ lock_utils::ApiIdentifier: From<F>,
+ {
+ api_locking::LockAction::Hold {
+ input: api_locking::LockingInput {
+ unique_locking_key: self.payment_id.to_owned(),
+ api_identifier: lock_utils::ApiIdentifier::from(flow),
+ override_lock_retries: None,
+ },
+ }
+ }
+}
+
impl GetLockingInput for payment_types::PaymentsCancelRequest {
fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction
where
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 9f68cac98c9..a2201936299 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -6,12 +6,13 @@ pub use api_models::payments::{
PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, PaymentListResponseV2,
PaymentMethodData, PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp,
PaymentRetrieveBody, PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest,
- PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest,
- PaymentsIncrementalAuthorizationRequest, PaymentsRedirectRequest, PaymentsRedirectionResponse,
- PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm,
- PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest,
- PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, TimeRange, UrlDetails,
- VerifyRequest, VerifyResponse, WalletData,
+ PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest,
+ PaymentsExternalAuthenticationRequest, PaymentsIncrementalAuthorizationRequest,
+ PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest,
+ PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest,
+ PaymentsSessionResponse, PaymentsStartRequest, PgRedirectResponse, PhoneDetails,
+ RedirectionResponse, SessionToken, TimeRange, UrlDetails, VerifyRequest, VerifyResponse,
+ WalletData,
};
use error_stack::ResultExt;
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index ffa492bc60d..07a45f5cdbc 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -180,6 +180,8 @@ pub enum Flow {
PayoutsAccounts,
/// Payments Redirect flow.
PaymentsRedirect,
+ /// Payemnts Complete Authorize Flow
+ PaymentsCompleteAuthorize,
/// Refunds create flow.
RefundsCreate,
/// Refunds retrieve flow.
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index c7592e48211..720a3b6d024 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -1152,6 +1152,11 @@ impl DataModelExt for PaymentIntentUpdate {
} => DieselPaymentIntentUpdate::AuthorizationCountUpdate {
authorization_count,
},
+ Self::CompleteAuthorizeUpdate {
+ shipping_address_id,
+ } => DieselPaymentIntentUpdate::CompleteAuthorizeUpdate {
+ shipping_address_id,
+ },
}
}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index a3cd88d2ee9..2365f165d65 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -853,6 +853,57 @@
]
}
},
+ "/{payment_id}/complete_authorize": {
+ "post": {
+ "tags": [
+ "Payments"
+ ],
+ "summary": "Payments - Complete Authorize",
+ "description": "Payments - Complete Authorize\n\n",
+ "operationId": "Complete Authorize a Payment",
+ "parameters": [
+ {
+ "name": "payment_id",
+ "in": "path",
+ "description": "The identifier for payment",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentsCompleteAuthorizeRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Payments Complete Authorize Success",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentsResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Missing mandatory fields"
+ }
+ },
+ "security": [
+ {
+ "publishable_key": []
+ }
+ ]
+ }
+ },
"/refunds": {
"post": {
"tags": [
@@ -13522,6 +13573,26 @@
}
}
},
+ "PaymentsCompleteAuthorizeRequest": {
+ "type": "object",
+ "required": [
+ "client_secret"
+ ],
+ "properties": {
+ "shipping": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Address"
+ }
+ ],
+ "nullable": true
+ },
+ "client_secret": {
+ "type": "string",
+ "description": "Client Secret"
+ }
+ }
+ },
"PaymentsConfirmRequest": {
"type": "object",
"properties": {
|
2024-05-17T12:56:33Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
- Add a new end point `/{payment_id}/complete_authorize`.
- This will be used in the cases where we get shipping after confirm call and we need to call the connector 2nd time.
- Collect shipping address in complete authorize call
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
1. Create a Paypal Payment request via Paypal (without adding shipping in request)
```
{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer223",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"setup_future_usage": "off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "wallet",
"payment_method_type": "paypal",
"payment_method_data": {
"wallet": {
"paypal_redirect": {}
}
}
}
```
Response
```
{
"payment_id": "pay_kgDXnhkYLQ19FfXW5HlC",
"merchant_id": "merchant_1715932962",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "paypal",
"client_secret": "pay_kgDXnhkYLQ19FfXW5HlC_secret_cCq0P0y8hP1rOwjjSXQW",
"created": "2024-05-17T11:54:56.365Z",
"currency": "USD",
"customer_id": "StripeCustomer223",
"customer": {
"id": "StripeCustomer223",
"name": "John Doe",
"email": "abcdef123@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": null,
"last_name": null
},
"phone": null,
"email": null
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_kgDXnhkYLQ19FfXW5HlC/merchant_1715932962/pay_kgDXnhkYLQ19FfXW5HlC_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer223",
"created_at": 1715946896,
"expires": 1715950496,
"secret": "epk_1612889c945d4948b4ea7df75aa819ec"
},
"manual_retry_allowed": null,
"connector_transaction_id": "9LY92988UP8943014",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_kgDXnhkYLQ19FfXW5HlC_1",
"payment_link": null,
"profile_id": "pro_o6Rw573Vwz3izj70A7ua",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_hmRahHIqSmAlgOR6UQAu",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-17T12:09:56.365Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-17T11:54:58.187Z"
}
```
______________________________________________________________
2. Hit Complete Authorize end point
```
curl --location '{{baseUrl}}/payments/:id/complete_authorize' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_e41911bdeff647c1bb6e3276e5bc621d' \
--data-raw '{
"shipping": {
"address": {
"line1": "1467",
"line2": "Kormangala",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"client_secret": "{{client_secret}}"
}'
```
Response
In Response we should shipping details.
```
{
"payment_id": "pay_lxZFT0OfS55HekMEdeJ5",
"merchant_id": "merchant_1716021280",
"status": "failed",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": null,
"connector": "paypal",
"client_secret": "pay_lxZFT0OfS55HekMEdeJ5_secret_oHIG40VJWaJv206oQQmV",
"created": "2024-05-18T08:34:52.094Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Kormangala",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": "ORDER_NOT_APPROVED",
"error_message": "description - Payer has not yet approved the Order for payment. Please redirect the payer to the 'rel':'approve' url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request. ;",
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": true,
"connector_transaction_id": "4Y3612593C2698259",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_lxZFT0OfS55HekMEdeJ5_1",
"payment_link": null,
"profile_id": "pro_p0FqSgqYAfU1Z93fJXDo",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_bjUetR7rWBdXgCjGLrBa",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-18T08:49:52.094Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-18T08:36:08.387Z",
"frm_metadata": null
}
```
_________________________________________________________
3. Retrieve Payment with same payment_id
In Response we should shipping details.
```
{
"payment_id": "pay_lxZFT0OfS55HekMEdeJ5",
"merchant_id": "merchant_1716021280",
"status": "failed",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": null,
"connector": "paypal",
"client_secret": "pay_lxZFT0OfS55HekMEdeJ5_secret_oHIG40VJWaJv206oQQmV",
"created": "2024-05-18T08:34:52.094Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Kormangala",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": "ORDER_NOT_APPROVED",
"error_message": "description - Payer has not yet approved the Order for payment. Please redirect the payer to the 'rel':'approve' url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request. ;",
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": true,
"connector_transaction_id": "4Y3612593C2698259",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_lxZFT0OfS55HekMEdeJ5_1",
"payment_link": null,
"profile_id": "pro_p0FqSgqYAfU1Z93fJXDo",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_bjUetR7rWBdXgCjGLrBa",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-18T08:49:52.094Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-18T08:36:08.387Z",
"frm_metadata": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7e44bbca63c1818c0fabdf2734d9b0ae5d639fe1
|
1. Create a Paypal Payment request via Paypal (without adding shipping in request)
```
{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer223",
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"setup_future_usage": "off_session",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US"
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "127.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"payment_method": "wallet",
"payment_method_type": "paypal",
"payment_method_data": {
"wallet": {
"paypal_redirect": {}
}
}
}
```
Response
```
{
"payment_id": "pay_kgDXnhkYLQ19FfXW5HlC",
"merchant_id": "merchant_1715932962",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "paypal",
"client_secret": "pay_kgDXnhkYLQ19FfXW5HlC_secret_cCq0P0y8hP1rOwjjSXQW",
"created": "2024-05-17T11:54:56.365Z",
"currency": "USD",
"customer_id": "StripeCustomer223",
"customer": {
"id": "StripeCustomer223",
"name": "John Doe",
"email": "abcdef123@gmail.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "off_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": null,
"last_name": null
},
"phone": null,
"email": null
},
"order_details": null,
"email": "abcdef123@gmail.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_kgDXnhkYLQ19FfXW5HlC/merchant_1715932962/pay_kgDXnhkYLQ19FfXW5HlC_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer223",
"created_at": 1715946896,
"expires": 1715950496,
"secret": "epk_1612889c945d4948b4ea7df75aa819ec"
},
"manual_retry_allowed": null,
"connector_transaction_id": "9LY92988UP8943014",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_kgDXnhkYLQ19FfXW5HlC_1",
"payment_link": null,
"profile_id": "pro_o6Rw573Vwz3izj70A7ua",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_hmRahHIqSmAlgOR6UQAu",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-17T12:09:56.365Z",
"fingerprint": null,
"browser_info": {
"language": "nl-NL",
"time_zone": 0,
"ip_address": "127.0.0.1",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"color_depth": 24,
"java_enabled": true,
"screen_width": 1536,
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"screen_height": 723,
"java_script_enabled": true
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-17T11:54:58.187Z"
}
```
______________________________________________________________
2. Hit Complete Authorize end point
```
curl --location '{{baseUrl}}/payments/:id/complete_authorize' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_e41911bdeff647c1bb6e3276e5bc621d' \
--data-raw '{
"shipping": {
"address": {
"line1": "1467",
"line2": "Kormangala",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"client_secret": "{{client_secret}}"
}'
```
Response
In Response we should shipping details.
```
{
"payment_id": "pay_lxZFT0OfS55HekMEdeJ5",
"merchant_id": "merchant_1716021280",
"status": "failed",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": null,
"connector": "paypal",
"client_secret": "pay_lxZFT0OfS55HekMEdeJ5_secret_oHIG40VJWaJv206oQQmV",
"created": "2024-05-18T08:34:52.094Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Kormangala",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": "ORDER_NOT_APPROVED",
"error_message": "description - Payer has not yet approved the Order for payment. Please redirect the payer to the 'rel':'approve' url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request. ;",
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": true,
"connector_transaction_id": "4Y3612593C2698259",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_lxZFT0OfS55HekMEdeJ5_1",
"payment_link": null,
"profile_id": "pro_p0FqSgqYAfU1Z93fJXDo",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_bjUetR7rWBdXgCjGLrBa",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-18T08:49:52.094Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-18T08:36:08.387Z",
"frm_metadata": null
}
```
_________________________________________________________
3. Retrieve Payment with same payment_id
In Response we should shipping details.
```
{
"payment_id": "pay_lxZFT0OfS55HekMEdeJ5",
"merchant_id": "merchant_1716021280",
"status": "failed",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": null,
"connector": "paypal",
"client_secret": "pay_lxZFT0OfS55HekMEdeJ5_secret_oHIG40VJWaJv206oQQmV",
"created": "2024-05-18T08:34:52.094Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Kormangala",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "PiX",
"last_name": null
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": "ORDER_NOT_APPROVED",
"error_message": "description - Payer has not yet approved the Order for payment. Please redirect the payer to the 'rel':'approve' url returned as part of the HATEOAS links within the Create Order call or provide a valid payment_source in the request. ;",
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": true,
"connector_transaction_id": "4Y3612593C2698259",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_lxZFT0OfS55HekMEdeJ5_1",
"payment_link": null,
"profile_id": "pro_p0FqSgqYAfU1Z93fJXDo",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_bjUetR7rWBdXgCjGLrBa",
"incremental_authorization_allowed": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-18T08:49:52.094Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-18T08:36:08.387Z",
"frm_metadata": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4689
|
Bug: [REFACTOR] add support for passing ttl to locker entries
Add config support for passing ttl to locker entries. By default keep the ttl to 7 years
|
diff --git a/config/config.example.toml b/config/config.example.toml
index d5bdfb5a6a7..d10e8216e9f 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -124,11 +124,12 @@ recon_admin_api_key = "recon_test_admin" # recon_admin API key for recon authent
# PCI Compliant storage entity which stores payment method information
# like card details
[locker]
-host = "" # Locker host
-host_rs = "" # Rust Locker host
-mock_locker = true # Emulate a locker locally using Postgres
-locker_signing_key_id = "1" # Key_id to sign basilisk hs locker
-locker_enabled = true # Boolean to enable or disable saving cards in locker
+host = "" # Locker host
+host_rs = "" # Rust Locker host
+mock_locker = true # Emulate a locker locally using Postgres
+locker_signing_key_id = "1" # Key_id to sign basilisk hs locker
+locker_enabled = true # Boolean to enable or disable saving cards in locker
+ttl_for_storage_in_secs = 220752000 # Time to live for storage entries in locker
[delayed_session_response]
connectors_with_delayed_session_response = "trustpay,payme" # List of connectors which has delayed session response
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index c725a8bd69d..fc02335dcf5 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -115,6 +115,8 @@ mock_locker = true # Emulate
locker_signing_key_id = "1" # Key_id to sign basilisk hs locker
locker_enabled = true # Boolean to enable or disable saving cards in locker
redis_temp_locker_encryption_key = "redis_temp_locker_encryption_key" # Encryption key for redis temp locker
+ttl_for_storage_in_secs = 220752000 # Time to live for storage entries in locker
+
[log.console]
enabled = true
diff --git a/config/development.toml b/config/development.toml
index a9f7f4d7b4d..dfba91b514d 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -71,6 +71,7 @@ host_rs = ""
mock_locker = true
basilisk_host = ""
locker_enabled = true
+ttl_for_storage_in_secs = 220752000
[forex_api]
call_delay = 21600
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 6661d164032..d371d08148a 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -61,6 +61,7 @@ host_rs = ""
mock_locker = true
basilisk_host = ""
locker_enabled = true
+ttl_for_storage_in_secs = 220752000
[jwekey]
vault_encryption_key = ""
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 1fe86a209e3..d3be5cd5248 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -68,6 +68,8 @@ impl Default for super::settings::Locker {
locker_signing_key_id: "1".into(),
//true or false
locker_enabled: true,
+ //Time to live for storage entries in locker
+ ttl_for_storage_in_secs: 60 * 60 * 24 * 365 * 7,
}
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index b8a315f944b..8ac27cce318 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -407,6 +407,7 @@ pub struct Locker {
pub basilisk_host: String,
pub locker_signing_key_id: String,
pub locker_enabled: bool,
+ pub ttl_for_storage_in_secs: i64,
}
#[derive(Debug, Deserialize, Clone)]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 379050ba73e..cd51face62d 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1070,6 +1070,7 @@ pub async fn add_bank_to_locker(
merchant_id: &merchant_account.merchant_id,
merchant_customer_id: customer_id.to_owned(),
enc_data,
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
});
let store_resp = call_to_locker_hs(
state,
@@ -1229,6 +1230,7 @@ pub async fn add_card_hs(
card_isin: None,
nick_name: card.nick_name.as_ref().map(Secret::peek).cloned(),
},
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
});
let store_card_payload =
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 08e87b47f91..86b41d1d0fe 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -43,6 +43,7 @@ pub struct StoreCardReq<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
pub requestor_card_reference: Option<String>,
pub card: Card,
+ pub ttl: i64,
}
#[derive(Debug, Deserialize, Serialize)]
@@ -51,6 +52,7 @@ pub struct StoreGenericReq<'a> {
pub merchant_customer_id: String,
#[serde(rename = "enc_card_data")]
pub enc_data: String,
+ pub ttl: i64,
}
#[derive(Debug, Deserialize, Serialize)]
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index dad0739879f..9c6cdbd8881 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -220,6 +220,7 @@ pub async fn save_payout_data_to_locker(
nick_name: None,
},
requestor_card_reference: None,
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
});
(
payload,
@@ -255,6 +256,7 @@ pub async fn save_payout_data_to_locker(
merchant_id: merchant_account.merchant_id.as_ref(),
merchant_customer_id: payout_attempt.customer_id.to_owned(),
enc_data,
+ ttl: state.conf.locker.ttl_for_storage_in_secs,
});
match payout_method_data {
payouts::PayoutMethodData::Bank(bank) => (
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 2c3e83ad2ba..878451080e3 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -38,6 +38,7 @@ host_rs = ""
mock_locker = true
basilisk_host = ""
locker_enabled = true
+ttl_for_storage_in_secs = 220752000
[forex_api]
call_delay = 21600
@@ -320,4 +321,4 @@ client_secret = ""
partner_id = ""
[unmasked_headers]
-keys = "user-agent"
\ No newline at end of file
+keys = "user-agent"
|
2024-05-17T13:43:49Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR adds config support for passing ttl to locker entries as application config. By default ttl is kept to 7 years.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
TTL assignment in locker cannot be known (unless we access the locker db). Hyperswitch just sends the TTL as 7 years to locker. Hyperswitch doesn't store the TTL. Even during payment methods retrieve in Hyperswitch, the TTL is not fetched from locker.
So basic card saving flow has to be tested
Local testing -
1. Save card in locker
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sQtjddP5dtSitN2ZB01xgmzYnQboxyx4u3m9nWjMSRCZlApGGjqAnXyVGAPl8OlI' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4111111111111111",
"card_exp_month": "04",
"card_exp_year": "25",
"card_holder_name": "John",
"card_network": "Visa"
},
"customer_id": "cus_kr9m9hY3ZpS7oJLtJ4mo",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

2. Locker DB (ttl is 7 years from created time)

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
8d9c7bc45ce2515759b9e2a36eb2d8a8a2c813ad
|
TTL assignment in locker cannot be known (unless we access the locker db). Hyperswitch just sends the TTL as 7 years to locker. Hyperswitch doesn't store the TTL. Even during payment methods retrieve in Hyperswitch, the TTL is not fetched from locker.
So basic card saving flow has to be tested
Local testing -
1. Save card in locker
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sQtjddP5dtSitN2ZB01xgmzYnQboxyx4u3m9nWjMSRCZlApGGjqAnXyVGAPl8OlI' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4111111111111111",
"card_exp_month": "04",
"card_exp_year": "25",
"card_holder_name": "John",
"card_network": "Visa"
},
"customer_id": "cus_kr9m9hY3ZpS7oJLtJ4mo",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

2. Locker DB (ttl is 7 years from created time)

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4680
|
Bug: Add audit events for PaymentApprove update
Created from #4525
This covers adding events for PaymentApprove operation
This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166)
It should also include any metadata for the event
e.g reason for payment rejection, error codes, rejection source etc
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
|
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index fe5e7a7e72f..2bc18122b22 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -12,6 +12,7 @@ use crate::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentData},
},
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -213,7 +214,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -257,6 +258,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCaptureRequest> for
)
.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))
}
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index 54c1934e36f..9fbd754b43c 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -27,6 +27,7 @@ pub enum AuditEventType {
capture_amount: Option<MinorUnit>,
multiple_capture_count: Option<i16>,
},
+ PaymentApprove,
PaymentCreate,
}
@@ -66,6 +67,7 @@ impl Event for AuditEvent {
AuditEventType::RefundSuccess => "refund_success",
AuditEventType::RefundFail => "refund_fail",
AuditEventType::PaymentCancelled { .. } => "payment_cancelled",
+ AuditEventType::PaymentApprove { .. } => "payment_approve",
AuditEventType::PaymentCreate { .. } => "payment_create",
};
format!(
|
2024-10-24T18:41:48Z
|
## Type of Change
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR adds an Audit event for the PaymentApprove operation.
### Additional Changes
- [x] This PR modifies the files below
- `crates/router/src/core/payments/operations/payment_approve.rs`
- `crates/router/src/events/audit_events.rs`
## Motivation and Context
This PR fixes #4680
## How did you test it
This requires FRM related flows to be tested, and may not be tested locally.
## Checklist
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
063fe904c66c9af3d7ce0a82ad712eac69e41786
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4677
|
Bug: Add audit events for PaymentStatus update
Created from #4525
This covers adding events for PaymentStatus operation
This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166)
It should also include any metadata for the event
e.g reason for payment rejection, error codes, rejection source etc
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
|
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 69f2d85d6a9..9aa905345c8 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -16,6 +16,7 @@ use crate::{
PaymentData,
},
},
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -141,7 +142,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
@@ -156,6 +157,12 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for
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))
}
}
@@ -167,7 +174,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequ
async fn update_trackers<'b>(
&'b self,
_state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
_storage_scheme: enums::MerchantStorageScheme,
@@ -182,6 +189,12 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequ
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))
}
}
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index c314fa8409f..a0f651b93c3 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -33,6 +33,7 @@ pub enum AuditEventType {
},
PaymentApprove,
PaymentCreate,
+ PaymentStatus,
PaymentCompleteAuthorize,
PaymentReject {
error_code: Option<String>,
@@ -79,6 +80,7 @@ impl Event for AuditEvent {
AuditEventType::PaymentUpdate { .. } => "payment_update",
AuditEventType::PaymentApprove { .. } => "payment_approve",
AuditEventType::PaymentCreate { .. } => "payment_create",
+ AuditEventType::PaymentStatus { .. } => "payment_status",
AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize",
AuditEventType::PaymentReject { .. } => "payment_rejected",
};
|
2024-11-08T12:48:57Z
|
## Type of Change
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR adds an Audit event for the PaymentStatus operation.
### Additional Changes
- [x] This PR modifies the files below
- `crates/router/src/core/payments/operations/payment_status.rs`
- `crates/router/src/events/audit_events.rs`
## Motivation and Context
This PR fixes #4677
## How did you test it
- Hit the `Payments - Create` endpoint
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--data-raw '{
"amount": 10000,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 10000,
"customer_id": "StripeCustomer",
"email": "test@test14.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"feature_metadata": {
"search_tags": ["Bangalore", "Chennai"]
},
"metadata": {
"data2": "camel",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"profile_id": "pro_v5sFoHe80OeiUlIonocM"
}'
```
- Response:
```json
{
"payment_id": "pay_JGFz7HS3yFZMtA7w82db",
"merchant_id": "merchant_1726046328",
"status": "succeeded",
"amount": 10000,
"net_amount": 10000,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": 10000,
"connector": "stripe_test",
"client_secret": "pay_JGFz7HS3yFZMtA7w82db_secret_1zvdrFCjs1ZepqjgS4Vw",
"created": "2024-12-16T07:12:44.627Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "test@test14.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "test@test14.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1734333164,
"expires": 1734336764,
"secret": "epk_44a2e5c540904c0dbd3e3cdff81c9180"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pay_88KleFv1IFJndrZFwEgK",
"frm_message": null,
"metadata": {
"data2": "camel",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": {
"redirect_response": null,
"search_tags": [
"1259195bb05bb44ea78ab60b26a54065183f91b3c5b3c2c074cadcf521305a79",
"9bff7b14d0a57a00d98f5eb742418a50b3bdfe5993f16b4219bfa31989bdf80f"
]
},
"reference_id": null,
"payment_link": null,
"profile_id": "pro_v5sFoHe80OeiUlIonocM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-12-16T07:27:44.627Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-12-16T07:12:45.719Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
- Now hit the `Payments - Retrieve` endpoint.
```bash
curl --location 'http://localhost:8080/payments/pay_JGFz7HS3yFZMtA7w82db' \
--header 'Accept: application/json' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF'
```
- Response:
```bash
{
"payment_id": "pay_JGFz7HS3yFZMtA7w82db",
"merchant_id": "merchant_1726046328",
"status": "succeeded",
"amount": 10000,
"net_amount": 10000,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": 10000,
"connector": "stripe_test",
"client_secret": "pay_JGFz7HS3yFZMtA7w82db_secret_1zvdrFCjs1ZepqjgS4Vw",
"created": "2024-12-16T07:12:44.627Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "test@test14.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "test@test14.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "pay_88KleFv1IFJndrZFwEgK",
"frm_message": null,
"metadata": {
"data2": "camel",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": {
"redirect_response": null,
"search_tags": [
"1259195bb05bb44ea78ab60b26a54065183f91b3c5b3c2c074cadcf521305a79",
"9bff7b14d0a57a00d98f5eb742418a50b3bdfe5993f16b4219bfa31989bdf80f"
]
},
"reference_id": null,
"payment_link": null,
"profile_id": "pro_v5sFoHe80OeiUlIonocM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_NNsdIEb1AjEOkyALerP6",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-12-16T07:27:44.627Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-12-16T07:12:45.719Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
Audit log will get generated and can be viewed in hyperswitch-audit-events topic in kafka with `PaymentStatus` event-type.
<img width="1092" alt="Screenshot 2024-12-16 at 12 44 57 PM" src="https://github.com/user-attachments/assets/964bbd78-93ff-41c1-87d6-3e47d7eb7c56" />
## Checklist
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
ed276ecc0017f7f98b6f8fa3841e6b8971f609f1
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4698
|
Bug: [FEATURE]: Add Session token flow for Paypal Sdk
### Feature Description
Add Session token flow for Paypal Sdk
### Possible Implementation
- Accept data in `metadata` field of the MCA - create call
- Return that data in the sessions call
- Change payment_experience for paypal via paypal to sdk
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index f0ce3839fce..5f9618738b2 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2939,13 +2939,17 @@ pub enum NextActionType {
#[serde(tag = "type", rename_all = "snake_case")]
pub enum NextActionData {
/// Contains the url for redirection flow
- RedirectToUrl { redirect_to_url: String },
+ RedirectToUrl {
+ redirect_to_url: String,
+ },
/// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc)
DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details: BankTransferNextStepsData,
},
/// Contains third party sdk session token response
- ThirdPartySdkSessionToken { session_token: Option<SessionToken> },
+ ThirdPartySdkSessionToken {
+ session_token: Option<SessionToken>,
+ },
/// Contains url for Qr code image, this qr code has to be shown in sdk
QrCodeInformation {
#[schema(value_type = String)]
@@ -2967,7 +2971,12 @@ pub enum NextActionData {
display_to_timestamp: Option<i128>,
},
/// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows
- ThreeDsInvoke { three_ds_data: ThreeDsData },
+ ThreeDsInvoke {
+ three_ds_data: ThreeDsData,
+ },
+ InvokeSdkClient {
+ next_action_data: SdkNextActionData,
+ },
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)]
@@ -3030,6 +3039,12 @@ pub enum QrCodeInformation {
},
}
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct SdkNextActionData {
+ pub next_action: NextActionCall,
+}
+
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct BankTransferNextStepsData {
/// The instructions for performing a bank transfer
@@ -4030,6 +4045,17 @@ pub struct GpaySessionTokenData {
pub data: GpayMetaData,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct PaypalSdkMetaData {
+ pub client_id: String,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct PaypalSdkSessionTokenData {
+ #[serde(rename = "paypal_sdk")]
+ pub data: PaypalSdkMetaData,
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplepaySessionRequest {
@@ -4207,8 +4233,12 @@ pub struct KlarnaSessionTokenResponse {
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
pub struct PaypalSessionTokenResponse {
+ /// Name of the connector
+ pub connector: String,
/// The session token for PayPal
pub session_token: String,
+ /// The next action for the sdk (ex: calling confirm or sync call)
+ pub sdk_next_action: SdkNextAction,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
@@ -4238,13 +4268,15 @@ pub struct SdkNextAction {
pub next_action: NextActionCall,
}
-#[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)]
+#[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum NextActionCall {
/// The next action call is confirm
Confirm,
/// The next action call is sync
Sync,
+ /// The next action call is Complete Authorize
+ CompleteAuthorize,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs
index b11a74a3ca6..fff210b6e4d 100644
--- a/crates/connector_configs/src/common_config.rs
+++ b/crates/connector_configs/src/common_config.rs
@@ -54,6 +54,12 @@ pub enum GooglePayData {
Zen(ZenGooglePay),
}
+#[serde_with::skip_serializing_none]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct PaypalSdkData {
+ pub client_id: Option<String>,
+}
+
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
#[serde(untagged)]
@@ -79,6 +85,7 @@ pub struct ApiModelMetaData {
pub terminal_id: Option<String>,
pub merchant_id: Option<String>,
pub google_pay: Option<GoogleApiModelData>,
+ pub paypal_sdk: Option<PaypalSdkData>,
pub apple_pay: Option<ApplePayData>,
pub apple_pay_combined: Option<ApplePayData>,
pub endpoint_prefix: Option<String>,
@@ -180,6 +187,7 @@ pub struct DashboardMetaData {
pub terminal_id: Option<String>,
pub merchant_id: Option<String>,
pub google_pay: Option<GooglePayData>,
+ pub paypal_sdk: Option<PaypalSdkData>,
pub apple_pay: Option<ApplePayData>,
pub apple_pay_combined: Option<ApplePayData>,
pub endpoint_prefix: Option<String>,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index e1d55e39385..7118c87b092 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -10,7 +10,7 @@ use serde::Deserialize;
#[cfg(any(feature = "sandbox", feature = "development", feature = "production"))]
use toml;
-use crate::common_config::{CardProvider, GooglePayData, Provider, ZenApplePay};
+use crate::common_config::{CardProvider, GooglePayData, PaypalSdkData, Provider, ZenApplePay};
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Classic {
@@ -79,6 +79,7 @@ pub struct ConfigMetadata {
pub account_name: Option<String>,
pub terminal_id: Option<String>,
pub google_pay: Option<GooglePayData>,
+ pub paypal_sdk: Option<PaypalSdkData>,
pub apple_pay: Option<ApplePayTomlConfig>,
pub merchant_id: Option<String>,
pub endpoint_prefix: Option<String>,
diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs
index 8f7da58c4dc..ebf97d83162 100644
--- a/crates/connector_configs/src/response_modifier.rs
+++ b/crates/connector_configs/src/response_modifier.rs
@@ -309,6 +309,7 @@ impl From<ApiModelMetaData> for DashboardMetaData {
terminal_id: api_model.terminal_id,
merchant_id: api_model.merchant_id,
google_pay: get_google_pay_metadata_response(api_model.google_pay),
+ paypal_sdk: api_model.paypal_sdk,
apple_pay: api_model.apple_pay,
apple_pay_combined: api_model.apple_pay_combined,
endpoint_prefix: api_model.endpoint_prefix,
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index 01332c9d29e..ae4b0206767 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -46,7 +46,9 @@ impl DashboardRequestPayload {
(Connector::Zen, GooglePay) | (Connector::Zen, ApplePay) => {
Some(api_models::enums::PaymentExperience::RedirectToUrl)
}
- (Connector::Braintree, Paypal) | (Connector::Klarna, Klarna) => {
+ (Connector::Paypal, Paypal)
+ | (Connector::Braintree, Paypal)
+ | (Connector::Klarna, Klarna) => {
Some(api_models::enums::PaymentExperience::InvokeSdkClient)
}
(Connector::Globepay, AliPay)
@@ -194,6 +196,7 @@ impl DashboardRequestPayload {
three_ds_requestor_name: None,
three_ds_requestor_id: None,
pull_mechanism_for_external_3ds_enabled: None,
+ paypal_sdk: None,
};
let meta_data = match request.metadata {
Some(data) => data,
@@ -205,6 +208,7 @@ impl DashboardRequestPayload {
let merchant_id = meta_data.merchant_id.clone();
let terminal_id = meta_data.terminal_id.clone();
let endpoint_prefix = meta_data.endpoint_prefix.clone();
+ let paypal_sdk = meta_data.paypal_sdk;
let apple_pay = meta_data.apple_pay;
let apple_pay_combined = meta_data.apple_pay_combined;
let merchant_config_currency = meta_data.merchant_config_currency;
@@ -228,6 +232,7 @@ impl DashboardRequestPayload {
merchant_config_currency,
apple_pay_combined,
endpoint_prefix,
+ paypal_sdk,
mcc,
merchant_country_code,
merchant_name,
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index d9e7ec58f75..fcccf9c7e28 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -1645,6 +1645,8 @@ api_key="Client Secret"
key1="Client ID"
[paypal.connector_webhook_details]
merchant_secret="Source verification key"
+[paypal.metadata.paypal_sdk]
+client_id="Client ID"
[paypal_payout]
[[paypal.wallet]]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 202bce64c1f..96fba850e7e 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -1265,6 +1265,8 @@ api_key="Client Secret"
key1="Client ID"
[paypal.connector_webhook_details]
merchant_secret="Source verification key"
+[paypal.metadata.paypal_sdk]
+client_id="Client ID"
[payu]
[[payu.credit]]
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 450e14d1080..932352f20e4 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -1645,6 +1645,8 @@ api_key="Client Secret"
key1="Client ID"
[paypal.connector_webhook_details]
merchant_secret="Source verification key"
+[paypal.metadata.paypal_sdk]
+client_id="Client ID"
[paypal_payout]
[[paypal.wallet]]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 8830c689937..c67ea2d2746 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -367,6 +367,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::SdkNextAction,
api_models::payments::NextActionCall,
+ api_models::payments::SdkNextActionData,
api_models::payments::SamsungPayWalletData,
api_models::payments::WeChatPay,
api_models::payments::GpayTokenizationData,
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index d615acff1ca..5e8c9ea08c0 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -823,6 +823,9 @@ pub enum StripeNextAction {
display_from_timestamp: i128,
display_to_timestamp: Option<i128>,
},
+ InvokeSdkClient {
+ next_action_data: payments::SdkNextActionData,
+ },
}
pub(crate) fn into_stripe_next_action(
@@ -871,6 +874,9 @@ pub(crate) fn into_stripe_next_action(
url: None,
},
},
+ payments::NextActionData::InvokeSdkClient { next_action_data } => {
+ StripeNextAction::InvokeSdkClient { next_action_data }
+ }
})
}
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index 03335d42722..bbcafb65e9f 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -389,6 +389,9 @@ pub enum StripeNextAction {
display_from_timestamp: i128,
display_to_timestamp: Option<i128>,
},
+ InvokeSdkClient {
+ next_action_data: payments::SdkNextActionData,
+ },
}
pub(crate) fn into_stripe_next_action(
@@ -437,6 +440,9 @@ pub(crate) fn into_stripe_next_action(
url: None,
},
},
+ payments::NextActionData::InvokeSdkClient { next_action_data } => {
+ StripeNextAction::InvokeSdkClient { next_action_data }
+ }
})
}
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 1fe86a209e3..0405f318071 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -7914,6 +7914,170 @@ impl Default for super::settings::RequiredFields {
]),
},
),
+ (
+ // Added shipping fields for the SDK flow to accept it from wallet directly,
+ // this won't show up in SDK in payment's sheet but will be used in the background
+ enums::PaymentMethodType::Paypal,
+ ConnectorFields {
+ fields: HashMap::from([
+ (
+ enums::Connector::Braintree,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(),
+ common: HashMap::from([
+ (
+ "shipping.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.first_name".to_string(),
+ display_name: "shipping_first_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.last_name".to_string(),
+ display_name: "shipping_last_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserShippingAddressState,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserShippingAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserShippingAddressLine1,
+ value: None,
+ }
+ ),
+ ]),
+ }
+ ),
+ (
+ enums::Connector::Paypal,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::new(
+ ),
+ common: HashMap::from(
+ [
+ (
+ "shipping.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.first_name".to_string(),
+ display_name: "shipping_first_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.last_name".to_string(),
+ display_name: "shipping_last_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserShippingAddressState,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserShippingAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserShippingAddressLine1,
+ value: None,
+ }
+ ),
+ ]
+ ),
+ }
+ ),
+ ]),
+ },
+ ),
])),
),
(
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index a939f0a83f7..136782cab6e 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -308,6 +308,10 @@ impl<F, T>
session_token: api::SessionToken::Paypal(Box::new(
payments::PaypalSessionTokenResponse {
session_token: item.response.client_token.value.expose(),
+ connector: "braintree".to_string(),
+ sdk_next_action: payments::SdkNextAction {
+ next_action: payments::NextActionCall::Confirm,
+ },
},
)),
}),
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs
index 9ff6b84a064..9e7b208ef70 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -34,7 +34,7 @@ use crate::{
self,
api::{self, CompleteAuthorize, ConnectorCommon, ConnectorCommonExt, VerifyWebhookSource},
storage::enums as storage_enums,
- transformers::ForeignFrom,
+ transformers::{ForeignFrom, ForeignTryFrom},
ConnectorAuthType, ErrorResponse, Response,
},
utils::BytesExt,
@@ -629,7 +629,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
res.response
.parse_struct("paypal PaypalAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
+ let payment_method_data = data.request.payment_method_data.clone();
match response {
PaypalAuthResponse::PaypalOrdersResponse(response) => {
event_builder.map(|i| i.set_response_body(&response));
@@ -644,11 +644,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
PaypalAuthResponse::PaypalRedirectResponse(response) => {
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
+ types::RouterData::foreign_try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ payment_method_data,
+ ))
}
PaypalAuthResponse::PaypalThreeDsResponse(response) => {
event_builder.map(|i| i.set_response_body(&response));
@@ -1033,11 +1036,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
+ types::RouterData::foreign_try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ data.request.payment_experience,
+ ))
}
fn get_error_response(
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 0ea1331c448..d240c1b05e0 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -18,7 +18,9 @@ use crate::{
core::errors,
services,
types::{
- self, api, domain, storage::enums as storage_enums, transformers::ForeignFrom,
+ self, api, domain,
+ storage::enums as storage_enums,
+ transformers::{ForeignFrom, ForeignTryFrom},
ConnectorAuthType, VerifyWebhookSourceResponseData,
},
};
@@ -387,28 +389,33 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
let paypal_auth: PaypalAuthType =
PaypalAuthType::try_from(&item.router_data.connector_auth_type)?;
let payee = get_payee(&paypal_auth);
+
+ let amount = OrderRequestAmount::from(item);
+
+ let intent = if item.router_data.request.is_auto_capture()? {
+ PaypalPaymentIntent::Capture
+ } else {
+ PaypalPaymentIntent::Authorize
+ };
+
+ let connector_request_reference_id =
+ item.router_data.connector_request_reference_id.clone();
+
+ let shipping_address = ShippingAddress::try_from(item)?;
+ let item_details = vec![ItemDetails::from(item)];
+
+ let purchase_units = vec![PurchaseUnitRequest {
+ reference_id: Some(connector_request_reference_id.clone()),
+ custom_id: Some(connector_request_reference_id.clone()),
+ invoice_id: Some(connector_request_reference_id),
+ amount,
+ payee,
+ shipping: Some(shipping_address),
+ items: item_details,
+ }];
+
match item.router_data.request.payment_method_data {
domain::PaymentMethodData::Card(ref ccard) => {
- let intent = if item.router_data.request.is_auto_capture()? {
- PaypalPaymentIntent::Capture
- } else {
- PaypalPaymentIntent::Authorize
- };
- let amount = OrderRequestAmount::from(item);
- let connector_request_reference_id =
- item.router_data.connector_request_reference_id.clone();
- let shipping_address = ShippingAddress::try_from(item)?;
- let item_details = vec![ItemDetails::from(item)];
-
- let purchase_units = vec![PurchaseUnitRequest {
- reference_id: Some(connector_request_reference_id.clone()),
- custom_id: Some(connector_request_reference_id.clone()),
- invoice_id: Some(connector_request_reference_id),
- amount,
- payee,
- shipping: Some(shipping_address),
- items: item_details,
- }];
let card = item.router_data.request.get_card()?;
let expiry = Some(card.get_expiry_date_as_yyyymm("-"));
@@ -441,27 +448,6 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
}
domain::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
domain::WalletData::PaypalRedirect(_) => {
- let intent = if item.router_data.request.is_auto_capture()? {
- PaypalPaymentIntent::Capture
- } else {
- PaypalPaymentIntent::Authorize
- };
- let amount = OrderRequestAmount::from(item);
-
- let connector_req_reference_id =
- item.router_data.connector_request_reference_id.clone();
- let shipping_address = ShippingAddress::try_from(item)?;
- let item_details = vec![ItemDetails::from(item)];
-
- let purchase_units = vec![PurchaseUnitRequest {
- reference_id: Some(connector_req_reference_id.clone()),
- custom_id: Some(connector_req_reference_id.clone()),
- invoice_id: Some(connector_req_reference_id),
- amount,
- payee,
- shipping: Some(shipping_address),
- items: item_details,
- }];
let payment_source =
Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest {
experience_context: ContextStruct {
@@ -486,6 +472,23 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
payment_source,
})
}
+ domain::WalletData::PaypalSdk(_) => {
+ let payment_source =
+ Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest {
+ experience_context: ContextStruct {
+ return_url: None,
+ cancel_url: None,
+ shipping_preference: ShippingPreference::GetFromFile,
+ user_action: Some(UserAction::PayNow),
+ },
+ }));
+
+ Ok(Self {
+ intent,
+ purchase_units,
+ payment_source,
+ })
+ }
domain::WalletData::AliPayQr(_)
| domain::WalletData::AliPayRedirect(_)
| domain::WalletData::AliPayHkRedirect(_)
@@ -502,7 +505,6 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
| domain::WalletData::GooglePayThirdPartySdk(_)
| domain::WalletData::MbWayRedirect(_)
| domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalSdk(_)
| domain::WalletData::SamsungPay(_)
| domain::WalletData::TwintRedirect {}
| domain::WalletData::VippsRedirect {}
@@ -515,7 +517,7 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
))?,
},
domain::PaymentMethodData::BankRedirect(ref bank_redirection_data) => {
- let intent = if item.router_data.request.is_auto_capture()? {
+ let bank_redirect_intent = if item.router_data.request.is_auto_capture()? {
PaypalPaymentIntent::Capture
} else {
Err(errors::ConnectorError::FlowNotSupported {
@@ -523,26 +525,12 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
connector: "Paypal".to_string(),
})?
};
- let amount = OrderRequestAmount::from(item);
- let connector_req_reference_id =
- item.router_data.connector_request_reference_id.clone();
- let shipping_address = ShippingAddress::try_from(item)?;
- let item_details = vec![ItemDetails::from(item)];
-
- let purchase_units = vec![PurchaseUnitRequest {
- reference_id: Some(connector_req_reference_id.clone()),
- custom_id: Some(connector_req_reference_id.clone()),
- invoice_id: Some(connector_req_reference_id),
- amount,
- payee,
- shipping: Some(shipping_address),
- items: item_details,
- }];
+
let payment_source =
Some(get_payment_source(item.router_data, bank_redirection_data)?);
Ok(Self {
- intent,
+ intent: bank_redirect_intent,
purchase_units,
payment_source,
})
@@ -1060,6 +1048,7 @@ pub struct PaypalMeta {
pub authorize_id: Option<String>,
pub capture_id: Option<String>,
pub psync_flow: PaypalPaymentIntent,
+ pub next_action: Option<api_models::payments::NextActionCall>,
}
fn get_id_based_on_intent(
@@ -1112,7 +1101,8 @@ impl<F, T>
serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: Some(id),
- psync_flow: item.response.intent.clone()
+ psync_flow: item.response.intent.clone(),
+ next_action: None,
}),
types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
),
@@ -1121,7 +1111,8 @@ impl<F, T>
serde_json::json!(PaypalMeta {
authorize_id: Some(id),
capture_id: None,
- psync_flow: item.response.intent.clone()
+ psync_flow: item.response.intent.clone(),
+ next_action: None,
}),
types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
),
@@ -1183,23 +1174,27 @@ fn get_redirect_url(
}
impl<F>
- TryFrom<
+ ForeignTryFrom<(
types::ResponseRouterData<
F,
PaypalSyncResponse,
types::PaymentsSyncData,
types::PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>
+ Option<common_enums::PaymentExperience>,
+ )> for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<
- F,
- PaypalSyncResponse,
- types::PaymentsSyncData,
- types::PaymentsResponseData,
- >,
+ fn foreign_try_from(
+ (item, payment_experience): (
+ types::ResponseRouterData<
+ F,
+ PaypalSyncResponse,
+ types::PaymentsSyncData,
+ types::PaymentsResponseData,
+ >,
+ Option<common_enums::PaymentExperience>,
+ ),
) -> Result<Self, Self::Error> {
match item.response {
PaypalSyncResponse::PaypalOrdersSyncResponse(response) => {
@@ -1209,13 +1204,14 @@ impl<F>
http_code: item.http_code,
})
}
- PaypalSyncResponse::PaypalRedirectSyncResponse(response) => {
- Self::try_from(types::ResponseRouterData {
+ PaypalSyncResponse::PaypalRedirectSyncResponse(response) => Self::foreign_try_from((
+ types::ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
- })
- }
+ },
+ payment_experience,
+ )),
PaypalSyncResponse::PaypalPaymentsSyncResponse(response) => {
Self::try_from(types::ResponseRouterData {
response,
@@ -1235,25 +1231,96 @@ impl<F>
}
impl<F, T>
- TryFrom<types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+ ForeignTryFrom<(
+ types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>,
+ Option<common_enums::PaymentExperience>,
+ )> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>,
+ fn foreign_try_from(
+ (item, payment_experience): (
+ types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>,
+ Option<common_enums::PaymentExperience>,
+ ),
) -> Result<Self, Self::Error> {
let status = storage_enums::AttemptStatus::foreign_from((
item.response.clone().status,
item.response.intent.clone(),
));
let link = get_redirect_url(item.response.links.clone())?;
+
+ // For Paypal SDK flow, we need to trigger SDK client and then complete authorize
+ let next_action =
+ if let Some(common_enums::PaymentExperience::InvokeSdkClient) = payment_experience {
+ Some(api_models::payments::NextActionCall::CompleteAuthorize)
+ } else {
+ None
+ };
let connector_meta = serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: None,
- psync_flow: item.response.intent
+ psync_flow: item.response.intent,
+ next_action,
});
let purchase_units = item.response.purchase_units.first();
+ Ok(Self {
+ status,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
+ redirection_data: Some(services::RedirectForm::from((
+ link.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?,
+ services::Method::Get,
+ ))),
+ mandate_reference: None,
+ connector_metadata: Some(connector_meta),
+ network_txn_id: None,
+ connector_response_reference_id: Some(
+ purchase_units.map_or(item.response.id, |item| item.invoice_id.clone()),
+ ),
+ incremental_authorization_allowed: None,
+ charge_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+impl<F, T>
+ ForeignTryFrom<(
+ types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>,
+ domain::PaymentMethodData,
+ )> for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn foreign_try_from(
+ (item, payment_method_data): (
+ types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>,
+ domain::PaymentMethodData,
+ ),
+ ) -> Result<Self, Self::Error> {
+ let status = storage_enums::AttemptStatus::foreign_from((
+ item.response.clone().status,
+ item.response.intent.clone(),
+ ));
+ let link = get_redirect_url(item.response.links.clone())?;
+
+ // For Paypal SDK flow, we need to trigger SDK client and then complete authorize
+ let next_action =
+ if let domain::PaymentMethodData::Wallet(domain::WalletData::PaypalSdk(_)) =
+ payment_method_data
+ {
+ Some(api_models::payments::NextActionCall::CompleteAuthorize)
+ } else {
+ None
+ };
+
+ let connector_meta = serde_json::json!(PaypalMeta {
+ authorize_id: None,
+ capture_id: None,
+ psync_flow: item.response.intent,
+ next_action,
+ });
+ let purchase_units = item.response.purchase_units.first();
Ok(Self {
status,
response: Ok(types::PaymentsResponseData::TransactionResponse {
@@ -1336,7 +1403,8 @@ impl<F>
let connector_meta = serde_json::json!(PaypalMeta {
authorize_id: None,
capture_id: None,
- psync_flow: PaypalPaymentIntent::Authenticate // when there is no capture or auth id present
+ psync_flow: PaypalPaymentIntent::Authenticate, // when there is no capture or auth id present
+ next_action: None,
});
let status = storage_enums::AttemptStatus::foreign_from((
@@ -1755,7 +1823,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaypalCaptureResponse>>
connector_metadata: Some(serde_json::json!(PaypalMeta {
authorize_id: connector_payment_id.authorize_id,
capture_id: Some(item.response.id.clone()),
- psync_flow: PaypalPaymentIntent::Capture
+ psync_flow: PaypalPaymentIntent::Capture,
+ next_action: None,
})),
network_txn_id: None,
connector_response_reference_id: item
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index f760e907288..a39f0deb3ca 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1012,6 +1012,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
api_models::payments::NextActionData::DisplayVoucherInformation{ .. } => None,
api_models::payments::NextActionData::WaitScreenInformation{..} => None,
api_models::payments::NextActionData::ThreeDsInvoke{..} => None,
+ api_models::payments::NextActionData::InvokeSdkClient{..} => None,
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 76ff96c7021..c74ed4bae15 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -634,6 +634,42 @@ where
) -> RouterResult<Self>;
}
+fn create_paypal_sdk_session_token(
+ _state: &routes::AppState,
+ router_data: &types::PaymentsSessionRouterData,
+ connector: &api::ConnectorData,
+ _business_profile: &storage::business_profile::BusinessProfile,
+) -> RouterResult<types::PaymentsSessionRouterData> {
+ let connector_metadata = router_data.connector_meta_data.clone();
+
+ let paypal_sdk_data = connector_metadata
+ .clone()
+ .parse_value::<payment_types::PaypalSdkSessionTokenData>("PaypalSdkSessionTokenData")
+ .change_context(errors::ConnectorError::NoConnectorMetaData)
+ .attach_printable(format!(
+ "cannot parse paypal_sdk metadata from the given value {connector_metadata:?}"
+ ))
+ .change_context(errors::ApiErrorResponse::InvalidDataFormat {
+ field_name: "connector_metadata".to_string(),
+ expected_format: "paypal_sdk_metadata_format".to_string(),
+ })?;
+
+ Ok(types::PaymentsSessionRouterData {
+ response: Ok(types::PaymentsResponseData::SessionResponse {
+ session_token: payment_types::SessionToken::Paypal(Box::new(
+ payment_types::PaypalSessionTokenResponse {
+ connector: connector.connector_name.to_string(),
+ session_token: paypal_sdk_data.data.client_id,
+ sdk_next_action: payment_types::SdkNextAction {
+ next_action: payment_types::NextActionCall::Confirm,
+ },
+ },
+ )),
+ }),
+ ..router_data.clone()
+ })
+}
+
#[async_trait]
impl RouterDataSession for types::PaymentsSessionRouterData {
async fn decide_flow<'a, 'b>(
@@ -651,6 +687,9 @@ impl RouterDataSession for types::PaymentsSessionRouterData {
api::GetToken::ApplePayMetadata => {
create_applepay_session_token(state, self, connector, business_profile).await
}
+ api::GetToken::PaypalSdkMetadata => {
+ create_paypal_sdk_session_token(state, self, connector, business_profile)
+ }
api::GetToken::Connector => {
let connector_integration: services::BoxedConnectorIntegration<
'_,
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index e4d91d4a068..2aa01cd587f 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -471,6 +471,7 @@ impl From<api_models::enums::PaymentMethodType> for api::GetToken {
match value {
api_models::enums::PaymentMethodType::GooglePay => Self::GpayMetadata,
api_models::enums::PaymentMethodType::ApplePay => Self::ApplePayMetadata,
+ api_models::enums::PaymentMethodType::Paypal => Self::PaypalSdkMetadata,
_ => Self::Connector,
}
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 11ce9cd7ede..7f6b0cc1f61 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -539,6 +539,8 @@ where
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_wait_screen =
wait_screen_next_steps_check(payment_attempt.clone())?;
@@ -547,6 +549,7 @@ where
|| next_action_voucher.is_some()
|| next_action_containing_qr_code_url.is_some()
|| next_action_containing_wait_screen.is_some()
+ || papal_sdk_next_action.is_some()
|| payment_data.authentication.is_some()
{
next_action_response = bank_transfer_next_steps
@@ -563,6 +566,11 @@ where
.or(next_action_containing_qr_code_url.map(|qr_code_data| {
api_models::payments::NextActionData::foreign_from(qr_code_data)
}))
+ .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_wait_screen.map(|wait_screen_data| {
api_models::payments::NextActionData::WaitScreenInformation {
display_from_timestamp: wait_screen_data.display_from_timestamp,
@@ -875,6 +883,21 @@ pub fn qr_code_next_steps_check(
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 wait_screen_next_steps_check(
payment_attempt: storage::PaymentAttempt,
@@ -1275,6 +1298,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData
},
payment_method_type: payment_data.payment_attempt.payment_method_type,
currency: payment_data.currency,
+ payment_experience: payment_data.payment_attempt.payment_experience,
})
}
}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index e2f2f6c0b70..89c2629c105 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -466,6 +466,7 @@ pub struct PaymentsSyncData {
pub mandate_id: Option<api_models::payments::MandateIds>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub currency: storage_enums::Currency,
+ pub payment_experience: Option<storage_enums::PaymentExperience>,
}
#[derive(Debug, Default, Clone)]
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 2013f482750..aea5e326cf7 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -217,6 +217,7 @@ type BoxedConnector = Box<&'static (dyn Connector + Sync)>;
pub enum GetToken {
GpayMetadata,
ApplePayMetadata,
+ PaypalSdkMetadata,
Connector,
}
diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs
index 3115c1143d7..d0bc77e7500 100644
--- a/crates/router/tests/connectors/bambora.rs
+++ b/crates/router/tests/connectors/bambora.rs
@@ -110,6 +110,7 @@ async fn should_sync_authorized_payment() {
connector_meta: None,
payment_method_type: None,
currency: enums::Currency::USD,
+ payment_experience: None,
}),
None,
)
@@ -226,6 +227,7 @@ async fn should_sync_auto_captured_payment() {
connector_meta: None,
payment_method_type: None,
currency: enums::Currency::USD,
+ payment_experience: None,
}),
None,
)
diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs
index d690524bd12..11153aa7088 100644
--- a/crates/router/tests/connectors/forte.rs
+++ b/crates/router/tests/connectors/forte.rs
@@ -159,6 +159,7 @@ async fn should_sync_authorized_payment() {
mandate_id: None,
payment_method_type: None,
currency: enums::Currency::USD,
+ payment_experience: None,
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs
index cdf94113c5a..c6a14ac202f 100644
--- a/crates/router/tests/connectors/nexinets.rs
+++ b/crates/router/tests/connectors/nexinets.rs
@@ -126,6 +126,7 @@ async fn should_sync_authorized_payment() {
mandate_id: None,
payment_method_type: None,
currency: enums::Currency::EUR,
+ payment_experience: None,
}),
None,
)
diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs
index 704aeca5936..b53cf71acfd 100644
--- a/crates/router/tests/connectors/paypal.rs
+++ b/crates/router/tests/connectors/paypal.rs
@@ -143,6 +143,7 @@ async fn should_sync_authorized_payment() {
connector_meta,
payment_method_type: None,
currency: enums::Currency::USD,
+ payment_experience: None,
}),
get_default_payment_info(),
)
@@ -341,6 +342,7 @@ async fn should_sync_auto_captured_payment() {
connector_meta,
payment_method_type: None,
currency: enums::Currency::USD,
+ payment_experience: None,
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 6718611b0c8..9955cb77df7 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -1002,6 +1002,7 @@ impl Default for PaymentSyncType {
connector_meta: None,
payment_method_type: None,
currency: enums::Currency::USD,
+ payment_experience: None,
};
Self(data)
}
diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs
index b11b78025d0..552edcaaf6f 100644
--- a/crates/router/tests/connectors/zen.rs
+++ b/crates/router/tests/connectors/zen.rs
@@ -105,6 +105,7 @@ async fn should_sync_authorized_payment() {
mandate_id: None,
payment_method_type: None,
currency: enums::Currency::USD,
+ payment_experience: None,
}),
None,
)
@@ -221,6 +222,7 @@ async fn should_sync_auto_captured_payment() {
mandate_id: None,
payment_method_type: None,
currency: enums::Currency::USD,
+ payment_experience: None,
}),
None,
)
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 47da1ae1074..b87b516de28 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -11660,7 +11660,8 @@
"type": "string",
"enum": [
"confirm",
- "sync"
+ "sync",
+ "complete_authorize"
]
},
"NextActionData": {
@@ -11816,6 +11817,24 @@
]
}
}
+ },
+ {
+ "type": "object",
+ "required": [
+ "next_action_data",
+ "type"
+ ],
+ "properties": {
+ "next_action_data": {
+ "$ref": "#/components/schemas/SdkNextActionData"
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "invoke_sdk_client"
+ ]
+ }
+ }
}
],
"discriminator": {
@@ -16780,12 +16799,21 @@
"PaypalSessionTokenResponse": {
"type": "object",
"required": [
- "session_token"
+ "connector",
+ "session_token",
+ "sdk_next_action"
],
"properties": {
+ "connector": {
+ "type": "string",
+ "description": "Name of the connector"
+ },
"session_token": {
"type": "string",
"description": "The session token for PayPal"
+ },
+ "sdk_next_action": {
+ "$ref": "#/components/schemas/SdkNextAction"
}
}
},
@@ -18030,6 +18058,17 @@
}
}
},
+ "SdkNextActionData": {
+ "type": "object",
+ "required": [
+ "next_action"
+ ],
+ "properties": {
+ "next_action": {
+ "$ref": "#/components/schemas/NextActionCall"
+ }
+ }
+ },
"SecretInfoToInitiateSdk": {
"type": "object",
"required": [
|
2024-05-19T17:37:00Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Add session_token flow to enable Paypal via Paypal SDK
- Accept data in `metadata` field of the MCA - create call
- Return that data in the sessions call
- Change payment_experience for paypal via paypal to sdk
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
#4698
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
### Create Paypal MCA with payment_experience as `invoke_sdk_client` for Paypal Wallet
```
curl --location 'http://localhost:8080/account/merchant_1716757295/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"business_country": "US",
"connector_name": "paypal",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "********************************",
"key1": "ASK*****************************_2"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 0,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"paypal_sdk": {
"client_id": "ASK****************************_2"
}
}
}'
```
### Payments Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_33Ad6faEcusLrqrqSeeFWyGRyTfOkKMoPMTSirAhCg0qqwkxQ25t7K1ucBEoq26M' \
--data-raw '{
"amount": 6100,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 6100,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
```
### Session Token
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: pk_dev_77ee3a2eb65741a0a4a3f1f6f3f0aa94' \
--data '{
"payment_id": "pay_msQQCSrBSCeNAZjBgwj9",
"client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW",
"wallets": []
}'
```
Response
```
{
"payment_id": "pay_msQQCSrBSCeNAZjBgwj9",
"client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW",
"session_token": [
{
"wallet_name": "paypal",
"connector": "paypal",
"session_token": "ASK************************_2",
"sdk_next_action": {
"next_action": "confirm"
}
}
]
}
```
### Payments - Confirm
```
curl --location 'http://localhost:8080/payments/pay_msQQCSrBSCeNAZjBgwj9/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_33Ad6faEcusLrqrqSeeFWyGRyTfOkKMoPMTSirAhCg0qqwkxQ25t7K1ucBEoq26M' \
--data '{
"confirm": true,
"payment_method": "wallet",
"payment_method_type": "paypal",
"payment_method_data": {
"wallet": {
"paypal_sdk": {
"token":""
}
}
}
}'
```
Response:
```
{
"payment_id": "pay_msQQCSrBSCeNAZjBgwj9",
"merchant_id": "merchant_1716757295",
"status": "requires_customer_action",
"amount": 6100,
"net_amount": 6100,
"amount_capturable": 6100,
"amount_received": null,
"connector": "paypal",
"client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW",
"created": "2024-05-26T21:03:19.068Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": {
"type": "invoke_sdk_client",
"next_action_data": {
"next_action": "complete_authorize"
}
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": "paypal_US_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "39X68391D53803705",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_msQQCSrBSCeNAZjBgwj9_1",
"payment_link": null,
"profile_id": "pro_L6gjuuDhzdKR9wlyV8yA",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ziKihOYd8bxdqpoLhP3u",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-26T21:18:19.068Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-26T21:06:09.286Z",
"charges": null,
"frm_metadata": null
}
```
### Authenticate Payment via SDK
### Payments - Complete Authorize
```
curl --location 'http://localhost:8080/payments/pay_msQQCSrBSCeNAZjBgwj9/complete_authorize' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_77ee3a2eb65741a0a4a3f1f6f3f0aa94' \
--data-raw '{
"shipping": {
"address": {
"line1": "1467",
"line2": "Kormangala",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW"
}'
```
Test Scenarios
- Test all the payments flow: Authorize, Manual Capture, Auto Capture, Refunds and webhooks
- Test for backwards compatibility: i.e use an older account where `redirect_to_url` is configured as payment_experience none of the flow should get affected by new code
- Update the connector account to SDK experience and then sync older payments and try new payments as well
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [X] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
1026f4783000a13b43f22e4db0b36c217d39e541
|
### Create Paypal MCA with payment_experience as `invoke_sdk_client` for Paypal Wallet
```
curl --location 'http://localhost:8080/account/merchant_1716757295/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"business_country": "US",
"connector_name": "paypal",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "********************************",
"key1": "ASK*****************************_2"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 0,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
"Visa",
"Mastercard"
],
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": "invoke_sdk_client",
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"paypal_sdk": {
"client_id": "ASK****************************_2"
}
}
}'
```
### Payments Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_33Ad6faEcusLrqrqSeeFWyGRyTfOkKMoPMTSirAhCg0qqwkxQ25t7K1ucBEoq26M' \
--data-raw '{
"amount": 6100,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 6100,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
}
}'
```
### Session Token
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: pk_dev_77ee3a2eb65741a0a4a3f1f6f3f0aa94' \
--data '{
"payment_id": "pay_msQQCSrBSCeNAZjBgwj9",
"client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW",
"wallets": []
}'
```
Response
```
{
"payment_id": "pay_msQQCSrBSCeNAZjBgwj9",
"client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW",
"session_token": [
{
"wallet_name": "paypal",
"connector": "paypal",
"session_token": "ASK************************_2",
"sdk_next_action": {
"next_action": "confirm"
}
}
]
}
```
### Payments - Confirm
```
curl --location 'http://localhost:8080/payments/pay_msQQCSrBSCeNAZjBgwj9/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_33Ad6faEcusLrqrqSeeFWyGRyTfOkKMoPMTSirAhCg0qqwkxQ25t7K1ucBEoq26M' \
--data '{
"confirm": true,
"payment_method": "wallet",
"payment_method_type": "paypal",
"payment_method_data": {
"wallet": {
"paypal_sdk": {
"token":""
}
}
}
}'
```
Response:
```
{
"payment_id": "pay_msQQCSrBSCeNAZjBgwj9",
"merchant_id": "merchant_1716757295",
"status": "requires_customer_action",
"amount": 6100,
"net_amount": 6100,
"amount_capturable": 6100,
"amount_received": null,
"connector": "paypal",
"client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW",
"created": "2024-05-26T21:03:19.068Z",
"currency": "USD",
"customer_id": null,
"customer": null,
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"next_action": {
"type": "invoke_sdk_client",
"next_action_data": {
"next_action": "complete_authorize"
}
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": "paypal_US_default",
"business_country": "US",
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": null,
"connector_transaction_id": "39X68391D53803705",
"frm_message": null,
"metadata": null,
"connector_metadata": {
"apple_pay": null,
"airwallex": null,
"noon": {
"order_category": "pay"
}
},
"feature_metadata": null,
"reference_id": "pay_msQQCSrBSCeNAZjBgwj9_1",
"payment_link": null,
"profile_id": "pro_L6gjuuDhzdKR9wlyV8yA",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ziKihOYd8bxdqpoLhP3u",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-26T21:18:19.068Z",
"fingerprint": null,
"browser_info": {
"language": null,
"time_zone": null,
"ip_address": "::1",
"user_agent": null,
"color_depth": null,
"java_enabled": null,
"screen_width": null,
"accept_header": null,
"screen_height": null,
"java_script_enabled": null
},
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-26T21:06:09.286Z",
"charges": null,
"frm_metadata": null
}
```
### Authenticate Payment via SDK
### Payments - Complete Authorize
```
curl --location 'http://localhost:8080/payments/pay_msQQCSrBSCeNAZjBgwj9/complete_authorize' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_77ee3a2eb65741a0a4a3f1f6f3f0aa94' \
--data-raw '{
"shipping": {
"address": {
"line1": "1467",
"line2": "Kormangala",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "guest@example.com"
},
"client_secret": "pay_msQQCSrBSCeNAZjBgwj9_secret_JdfpEbRZl5KTYwtNCURW"
}'
```
Test Scenarios
- Test all the payments flow: Authorize, Manual Capture, Auto Capture, Refunds and webhooks
- Test for backwards compatibility: i.e use an older account where `redirect_to_url` is configured as payment_experience none of the flow should get affected by new code
- Update the connector account to SDK experience and then sync older payments and try new payments as well
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4675
|
Bug: Add audit events for PaymentCapture update
|
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 447f7b92906..02c69681a88 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -12,6 +12,7 @@ use crate::{
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, types::MultipleCaptureData},
},
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -255,7 +256,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe
async fn update_trackers<'b>(
&'b self,
db: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut payment_data: payments::PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
@@ -294,6 +295,16 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe
} 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))
}
}
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index 6fc19018655..367a573a93b 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -1,3 +1,4 @@
+use common_utils::types::MinorUnit;
use diesel_models::fraud_check::FraudCheck;
use events::{Event, EventInfo};
use serde::Serialize;
@@ -22,6 +23,10 @@ pub enum AuditEventType {
PaymentCancelled {
cancellation_reason: Option<String>,
},
+ PaymentCapture {
+ capture_amount: Option<MinorUnit>,
+ multiple_capture_count: Option<i16>,
+ },
}
#[derive(Debug, Clone, Serialize)]
@@ -55,6 +60,7 @@ impl Event for AuditEvent {
AuditEventType::PaymentConfirm { .. } => "payment_confirm",
AuditEventType::ConnectorDecided => "connector_decided",
AuditEventType::ConnectorCalled => "connector_called",
+ AuditEventType::PaymentCapture { .. } => "payment_capture",
AuditEventType::RefundCreated => "refund_created",
AuditEventType::RefundSuccess => "refund_success",
AuditEventType::RefundFail => "refund_fail",
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 12da9e6765f..baa824ced3f 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -958,6 +958,9 @@ where
}
})??
};
+ request_state
+ .event_context
+ .record_info(("tenant_id".to_string(), tenant_id.to_string()));
// let tenant_id = "public".to_string();
let mut session_state =
Arc::new(app_state.clone()).get_session_state(tenant_id.as_str(), || {
|
2024-06-07T11:15:30Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Added an event each time a payment capture happens with the relevant contextual info
- Pass along request_state to payment_core
- Modify the UpdateTracker trait to accept request state
- Modify the PaymentCapture implementation of UpdateTracker to generate an event
- Showing the `capture_amount` and `multiple_capture_count` fields in the event
- Added `tenant_id` field for the event
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
To generate audit events whenever the payment state changes so we can get a brief overview without needing to comb through the logs.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Implemented an event trigger that activates whenever the payment capture API is utilized. This event triggers an audit event, the details of which are subsequently reflected in the Kafka UI.
- Create a payment & then capture it.
- Fields that need to be tested are: `capture_amount`, `multiple_capture_count` and `tenant_id`.
```
{"topic": "hyperswitch-audit-events"}
```
<img width="894" alt="Screenshot 2024-06-10 at 4 09 13 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/6bc8137f-6fa8-4fbe-8daa-e31360b9321d">
<img width="879" alt="Screenshot 2024-06-10 at 4 09 51 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/ee713dd5-f4ff-4c64-9442-ad07c5860dc9">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
2119de9c1e6b1293a1eeff04010942895d7d5d4e
|
- Implemented an event trigger that activates whenever the payment capture API is utilized. This event triggers an audit event, the details of which are subsequently reflected in the Kafka UI.
- Create a payment & then capture it.
- Fields that need to be tested are: `capture_amount`, `multiple_capture_count` and `tenant_id`.
```
{"topic": "hyperswitch-audit-events"}
```
<img width="894" alt="Screenshot 2024-06-10 at 4 09 13 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/6bc8137f-6fa8-4fbe-8daa-e31360b9321d">
<img width="879" alt="Screenshot 2024-06-10 at 4 09 51 PM" src="https://github.com/juspay/hyperswitch/assets/83278309/ee713dd5-f4ff-4c64-9442-ad07c5860dc9">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4673
|
Bug: Add audit events for PaymentConfirm update
|
diff --git a/config/development.toml b/config/development.toml
index 25fe55e6057..78b10192f1e 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -634,4 +634,4 @@ sdk_eligible_payment_methods = "card"
enabled = false
[multitenancy.tenants]
-public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""}
\ No newline at end of file
+public = { name = "hyperswitch", base_url = "http://localhost:8080", schema = "public", redis_key_prefix = ""}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index ea5f2c0ecb4..cff51ed8091 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -29,6 +29,7 @@ use crate::{
utils as core_utils,
},
db::StorageInterface,
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -935,7 +936,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -1294,6 +1295,19 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
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,
+ }))
+ .with(payment_data.to_event())
+ .emit();
Ok((Box::new(self), payment_data))
}
}
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index 0f186e691b9..6fc19018655 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -1,18 +1,27 @@
+use diesel_models::fraud_check::FraudCheck;
use events::{Event, EventInfo};
use serde::Serialize;
use time::PrimitiveDateTime;
-
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "event_type")]
pub enum AuditEventType {
- Error { error_message: String },
+ Error {
+ error_message: String,
+ },
PaymentCreated,
ConnectorDecided,
ConnectorCalled,
RefundCreated,
RefundSuccess,
RefundFail,
- PaymentCancelled { cancellation_reason: Option<String> },
+ PaymentConfirm {
+ client_src: Option<String>,
+ client_ver: Option<String>,
+ frm_message: Option<FraudCheck>,
+ },
+ PaymentCancelled {
+ cancellation_reason: Option<String>,
+ },
}
#[derive(Debug, Clone, Serialize)]
@@ -43,6 +52,7 @@ impl Event for AuditEvent {
let event_type = match &self.event_type {
AuditEventType::Error { .. } => "error",
AuditEventType::PaymentCreated => "payment_created",
+ AuditEventType::PaymentConfirm { .. } => "payment_confirm",
AuditEventType::ConnectorDecided => "connector_decided",
AuditEventType::ConnectorCalled => "connector_called",
AuditEventType::RefundCreated => "refund_created",
|
2024-05-24T11:57:10Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
- Pass along request_state to payment_core
- Update `updatetrackers` trait to accept request state
- Update the paymentconfirm implementation of updatetracker to generate an event
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Generating domain events that can be used to track the high level overview of any process
## How did you test it?
### Test Case Description
- Implemented an event trigger that activates whenever the payment confirm API is utilized. This event triggers an audit event, the details of which are subsequently reflected in the Kafka UI.
- Create a payment & then confirm it
- Fields that need to be tested are: `client_src`, `client_ver`and `frm_message`.
```
{"topic" = "hyperswitch-audit-events"}
```
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ba0a1e95b72c0acf5bde81d424aa8fe220c40a22
|
### Test Case Description
- Implemented an event trigger that activates whenever the payment confirm API is utilized. This event triggers an audit event, the details of which are subsequently reflected in the Kafka UI.
- Create a payment & then confirm it
- Fields that need to be tested are: `client_src`, `client_ver`and `frm_message`.
```
{"topic" = "hyperswitch-audit-events"}
```

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4674
|
Bug: Add audit events for CompleteAuthorize update
Created from #4525
This covers adding events for Complete Authorize operation
This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166)
It should also include any metadata for the event
e.g reason for payment rejection, error codes, rejection source etc
### Submission Process:
- Ask the maintainers for assignment of the issue, you can request for assignment by commenting on the issue itself.
- Once assigned, submit a pull request (PR).
- Maintainers will review and provide feedback, if any.
- Maintainers can unassign issues due to inactivity, [read more here](https://github.com/juspay/hyperswitch/wiki/Hacktoberfest-Contribution-Rules).
Refer [here](https://github.com/juspay/hyperswitch/blob/main/docs/TERMS_OF_CONTEST.md) for Terms and conditions for the contest.
|
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 850fa738cd8..8c003f54adf 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -16,6 +16,7 @@ use crate::{
PaymentData,
},
},
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -462,7 +463,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -492,6 +493,12 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Comple
.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))
}
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index 5f2ed10bc5f..c314fa8409f 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -33,6 +33,7 @@ pub enum AuditEventType {
},
PaymentApprove,
PaymentCreate,
+ PaymentCompleteAuthorize,
PaymentReject {
error_code: Option<String>,
error_message: Option<String>,
@@ -78,6 +79,7 @@ impl Event for AuditEvent {
AuditEventType::PaymentUpdate { .. } => "payment_update",
AuditEventType::PaymentApprove { .. } => "payment_approve",
AuditEventType::PaymentCreate { .. } => "payment_create",
+ AuditEventType::PaymentCompleteAuthorize => "payment_complete_authorize",
AuditEventType::PaymentReject { .. } => "payment_rejected",
};
format!(
|
2024-10-14T13:49:41Z
|
## Type of Change
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Created from #4674
This covers adding events for `CompleteAuthorize` operation
## How did you test it
Use `globalpay` as connector, `wallet` as payment_method and `paypal` as payment_method_type
```bash
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "paypal",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
}
```
Create a payment:
```bash
{
"amount": 600,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 600,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "wallet",
"payment_method_type": "paypal",
"payment_method_data": {
"wallet": {
"paypal_redirect":{}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "DE",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
```
Response:
```json
{
"payment_id": "pay_AkkvFG6dZN3gasgy729h",
"merchant_id": "postman_merchant_GHAction_93d97914-663d-4099-b4a2-a9ec314d654e",
"status": "requires_customer_action",
"amount": 600,
"net_amount": 600,
"amount_capturable": 600,
"amount_received": null,
"connector": "globalpay",
"client_secret": "pay_AkkvFG6dZN3gasgy729h_secret_XLheDrFzLzXL7eF0BOxV",
"created": "2024-11-06T14:35:59.773Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "wallet",
"payment_method_data": {
"wallet": {},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "DE",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": {
"type": "redirect_to_url",
"redirect_to_url": "http://localhost:8080/payments/redirect/pay_AkkvFG6dZN3gasgy729h/postman_merchant_GHAction_93d97914-663d-4099-b4a2-a9ec314d654e/pay_AkkvFG6dZN3gasgy729h_1"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "paypal",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1730903759,
"expires": 1730907359,
"secret": "epk_2f5f6461495c44d5836e790820a006f4"
},
"manual_retry_allowed": null,
"connector_transaction_id": "TRN_N8FIKEvvsrYO5xqzUcwgzTLg9dXnCq_3gasgy729h_1",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_AkkvFG6dZN3gasgy729h_1",
"payment_link": null,
"profile_id": "pro_S5r08g7HrBg5FT2NWS3l",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_8uJfYpthurOSVoLJwxfR",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-11-06T14:50:59.773Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-11-06T14:36:02.437Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
Hit the `redirction_url` and complete the payment.
Audit logs will get generated and can be viewed in `hyperswitch-audit-events` topic in kafka with `PaymentCompleteAuthorize` event-type.
<img width="1361" alt="image" src="https://github.com/user-attachments/assets/aa909b5b-7eb8-4f03-8453-8c02af9aa74d">
## Checklist
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
535c8d4e6fc8226a66ba2c45bb8102625454306c
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4691
|
Bug: [FEATURE] The Eligibility Analysis during payments confirmation makes use of the Constraint Graph framework to carry out checks.
### Feature Description
The Eligibility Analysis during payments confirmation makes use of the Constraint Graph framework to carry out checks.
### Possible Implementation
We can make use of the constraint graph framework to represent all the checks as a constraint graph. One thing to be aware of is that the Payment Methods filtering logic checks the eligibility of payment methods whereas the Eligibility Analysis checks the eligibility of a connector for a particular payment, i.e. the goals differ even if the underlying checks are based on the same data.
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/Cargo.lock b/Cargo.lock
index abc265ad692..e3cc2e32387 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3944,6 +3944,7 @@ dependencies = [
"masking",
"serde",
"serde_json",
+ "strum 0.26.2",
"thiserror",
]
diff --git a/crates/euclid/src/dssa/graph.rs b/crates/euclid/src/dssa/graph.rs
index 0ffafe4d48b..ce61fa57bf5 100644
--- a/crates/euclid/src/dssa/graph.rs
+++ b/crates/euclid/src/dssa/graph.rs
@@ -12,6 +12,7 @@ use crate::{
pub mod euclid_graph_prelude {
pub use hyperswitch_constraint_graph as cgraph;
pub use rustc_hash::{FxHashMap, FxHashSet};
+ pub use strum::EnumIter;
pub use crate::{
dssa::graph::*,
@@ -71,6 +72,7 @@ impl<V: cgraph::ValueNode> AnalysisError<V> {
}
}
+#[derive(Debug)]
pub struct AnalysisContext {
keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>>,
}
diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rs
index f473c5980c7..1aba6338d9d 100644
--- a/crates/euclid/src/enums.rs
+++ b/crates/euclid/src/enums.rs
@@ -1,5 +1,5 @@
pub use common_enums::{
- AuthenticationType, CaptureMethod, CardNetwork, Country, Currency,
+ AuthenticationType, CaptureMethod, CardNetwork, Country, CountryAlpha2, Currency,
FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType, RoutableConnectors,
};
use strum::VariantNames;
diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs
index 941fc9d7465..c5f864bf770 100644
--- a/crates/euclid/src/frontend/dir/enums.rs
+++ b/crates/euclid/src/frontend/dir/enums.rs
@@ -3,8 +3,8 @@ use strum::VariantNames;
use crate::enums::collect_variants;
pub use crate::enums::{
AuthenticationType, CaptureMethod, CardNetwork, Country, Country as BusinessCountry,
- Country as BillingCountry, Currency as PaymentCurrency, MandateAcceptanceType, MandateType,
- PaymentMethod, PaymentType, RoutableConnectors, SetupFutureUsage,
+ Country as BillingCountry, CountryAlpha2, Currency as PaymentCurrency, MandateAcceptanceType,
+ MandateType, PaymentMethod, PaymentType, RoutableConnectors, SetupFutureUsage,
};
#[cfg(feature = "payouts")]
pub use crate::enums::{PayoutBankTransferType, PayoutType, PayoutWalletType};
diff --git a/crates/euclid_wasm/src/lib.rs b/crates/euclid_wasm/src/lib.rs
index 3668130608e..df78786a579 100644
--- a/crates/euclid_wasm/src/lib.rs
+++ b/crates/euclid_wasm/src/lib.rs
@@ -91,8 +91,12 @@ pub fn seed_knowledge_graph(mcas: JsValue) -> JsResult {
.collect::<Result<_, _>>()
.map_err(|_| "invalid connector name received")
.err_to_js()?;
-
- let mca_graph = kgraph_utils::mca::make_mca_graph(mcas).err_to_js()?;
+ let pm_filter = kgraph_utils::types::PaymentMethodFilters(HashMap::new());
+ let config = kgraph_utils::types::CountryCurrencyFilter {
+ connector_configs: HashMap::new(),
+ default_configs: Some(pm_filter),
+ };
+ let mca_graph = kgraph_utils::mca::make_mca_graph(mcas, &config).err_to_js()?;
let analysis_graph =
hyperswitch_constraint_graph::ConstraintGraph::combine(&mca_graph, &truth::ANALYSIS_GRAPH)
.err_to_js()?;
diff --git a/crates/hyperswitch_constraint_graph/src/builder.rs b/crates/hyperswitch_constraint_graph/src/builder.rs
index c1343eff885..fdd87eac51c 100644
--- a/crates/hyperswitch_constraint_graph/src/builder.rs
+++ b/crates/hyperswitch_constraint_graph/src/builder.rs
@@ -28,7 +28,7 @@ impl From<DomainId> for DomainIdOrIdentifier<'_> {
Self::DomainId(value)
}
}
-
+#[derive(Debug)]
pub struct ConstraintGraphBuilder<'a, V: ValueNode> {
domain: DenseMap<DomainId, DomainInfo<'a>>,
nodes: DenseMap<NodeId, Node<V>>,
diff --git a/crates/hyperswitch_constraint_graph/src/graph.rs b/crates/hyperswitch_constraint_graph/src/graph.rs
index d0a98e19520..4a93419df57 100644
--- a/crates/hyperswitch_constraint_graph/src/graph.rs
+++ b/crates/hyperswitch_constraint_graph/src/graph.rs
@@ -13,6 +13,7 @@ use crate::{
},
};
+#[derive(Debug)]
struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> {
ctx: &'a C,
node: &'a Node<V>,
@@ -24,6 +25,7 @@ struct CheckNodeContext<'a, V: ValueNode, C: CheckingContext<Value = V>> {
domains: Option<&'a [DomainId]>,
}
+#[derive(Debug)]
pub struct ConstraintGraph<'a, V: ValueNode> {
pub domain: DenseMap<DomainId, DomainInfo<'a>>,
pub domain_identifier_map: FxHashMap<DomainIdentifier<'a>, DomainId>,
@@ -139,6 +141,7 @@ where
ctx,
domains,
};
+
match &node.node_type {
NodeType::AllAggregator => self.validate_all_aggregator(check_node_context),
@@ -206,6 +209,7 @@ where
} else {
vald.memo
.insert((vald.node_id, vald.relation, vald.strength), Ok(()));
+
Ok(())
}
}
diff --git a/crates/kgraph_utils/Cargo.toml b/crates/kgraph_utils/Cargo.toml
index 86de6002c32..d068ee89692 100644
--- a/crates/kgraph_utils/Cargo.toml
+++ b/crates/kgraph_utils/Cargo.toml
@@ -21,6 +21,7 @@ masking = { version = "0.1.0", path = "../masking/" }
serde = "1.0.197"
serde_json = "1.0.115"
thiserror = "1.0.58"
+strum = { version = "0.26", features = ["derive"] }
[dev-dependencies]
criterion = "0.5"
diff --git a/crates/kgraph_utils/benches/evaluation.rs b/crates/kgraph_utils/benches/evaluation.rs
index 9921ee7af35..4cc526f973f 100644
--- a/crates/kgraph_utils/benches/evaluation.rs
+++ b/crates/kgraph_utils/benches/evaluation.rs
@@ -1,6 +1,6 @@
#![allow(unused, clippy::expect_used)]
-use std::str::FromStr;
+use std::{collections::HashMap, str::FromStr};
use api_models::{
admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes,
@@ -13,7 +13,7 @@ use euclid::{
types::{NumValue, NumValueRefinement},
};
use hyperswitch_constraint_graph::{CycleCheck, Memoization};
-use kgraph_utils::{error::KgraphError, transformers::IntoDirValue};
+use kgraph_utils::{error::KgraphError, transformers::IntoDirValue, types::CountryCurrencyFilter};
fn build_test_data<'a>(
total_enabled: usize,
@@ -71,8 +71,12 @@ fn build_test_data<'a>(
pm_auth_config: None,
status: api_enums::ConnectorStatus::Inactive,
};
-
- kgraph_utils::mca::make_mca_graph(vec![stripe_account]).expect("Failed graph construction")
+ let config = CountryCurrencyFilter {
+ connector_configs: HashMap::new(),
+ default_configs: None,
+ };
+ kgraph_utils::mca::make_mca_graph(vec![stripe_account], &config)
+ .expect("Failed graph construction")
}
fn evaluation(c: &mut Criterion) {
diff --git a/crates/kgraph_utils/src/lib.rs b/crates/kgraph_utils/src/lib.rs
index eb8eef6dedb..20c2abf0533 100644
--- a/crates/kgraph_utils/src/lib.rs
+++ b/crates/kgraph_utils/src/lib.rs
@@ -1,3 +1,4 @@
pub mod error;
pub mod mca;
pub mod transformers;
+pub mod types;
diff --git a/crates/kgraph_utils/src/mca.rs b/crates/kgraph_utils/src/mca.rs
index 14a88dd1c6e..ed96cd9b545 100644
--- a/crates/kgraph_utils/src/mca.rs
+++ b/crates/kgraph_utils/src/mca.rs
@@ -4,15 +4,138 @@ use api_models::{
admin as admin_api, enums as api_enums, payment_methods::RequestPaymentMethodTypes,
};
use euclid::{
+ dirval,
frontend::{ast, dir},
types::{NumValue, NumValueRefinement},
};
use hyperswitch_constraint_graph as cgraph;
+use strum::IntoEnumIterator;
-use crate::{error::KgraphError, transformers::IntoDirValue};
+use crate::{error::KgraphError, transformers::IntoDirValue, types as kgraph_types};
pub const DOMAIN_IDENTIFIER: &str = "payment_methods_enabled_for_merchantconnectoraccount";
+fn get_dir_value_payment_method(
+ from: api_enums::PaymentMethodType,
+) -> Result<dir::DirValue, KgraphError> {
+ match from {
+ api_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
+ api_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
+ api_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
+ api_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)),
+ api_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)),
+ api_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)),
+ api_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)),
+ api_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)),
+ api_enums::PaymentMethodType::AfterpayClearpay => {
+ Ok(dirval!(PayLaterType = AfterpayClearpay))
+ }
+ api_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)),
+ api_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)),
+ api_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)),
+ api_enums::PaymentMethodType::CryptoCurrency => Ok(dirval!(CryptoType = CryptoCurrency)),
+ api_enums::PaymentMethodType::Ach => Ok(dirval!(BankDebitType = Ach)),
+
+ api_enums::PaymentMethodType::Bacs => Ok(dirval!(BankDebitType = Bacs)),
+
+ api_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)),
+ api_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)),
+
+ api_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)),
+ api_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)),
+ api_enums::PaymentMethodType::BancontactCard => {
+ Ok(dirval!(BankRedirectType = BancontactCard))
+ }
+ api_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)),
+ api_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)),
+ api_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)),
+ api_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)),
+ api_enums::PaymentMethodType::Multibanco => Ok(dirval!(BankTransferType = Multibanco)),
+ api_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)),
+ api_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)),
+ api_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)),
+ api_enums::PaymentMethodType::OnlineBankingCzechRepublic => {
+ Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic))
+ }
+ api_enums::PaymentMethodType::OnlineBankingFinland => {
+ Ok(dirval!(BankRedirectType = OnlineBankingFinland))
+ }
+ api_enums::PaymentMethodType::OnlineBankingPoland => {
+ Ok(dirval!(BankRedirectType = OnlineBankingPoland))
+ }
+ api_enums::PaymentMethodType::OnlineBankingSlovakia => {
+ Ok(dirval!(BankRedirectType = OnlineBankingSlovakia))
+ }
+ api_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)),
+ api_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)),
+ api_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)),
+
+ api_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)),
+ api_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)),
+ api_enums::PaymentMethodType::Przelewy24 => Ok(dirval!(BankRedirectType = Przelewy24)),
+ api_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)),
+
+ api_enums::PaymentMethodType::ClassicReward => Ok(dirval!(RewardType = ClassicReward)),
+ api_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
+ api_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
+ api_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
+ api_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
+ api_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
+ api_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)),
+ api_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)),
+ api_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)),
+ api_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)),
+ api_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)),
+ api_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)),
+ api_enums::PaymentMethodType::OnlineBankingFpx => {
+ Ok(dirval!(BankRedirectType = OnlineBankingFpx))
+ }
+ api_enums::PaymentMethodType::OnlineBankingThailand => {
+ Ok(dirval!(BankRedirectType = OnlineBankingThailand))
+ }
+ api_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)),
+ api_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)),
+ api_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)),
+ api_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)),
+ api_enums::PaymentMethodType::PagoEfectivo => Ok(dirval!(VoucherType = PagoEfectivo)),
+ api_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)),
+ api_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)),
+ api_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)),
+ api_enums::PaymentMethodType::BcaBankTransfer => {
+ Ok(dirval!(BankTransferType = BcaBankTransfer))
+ }
+ api_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)),
+ api_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)),
+ api_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)),
+ api_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)),
+ api_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)),
+ api_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)),
+ api_enums::PaymentMethodType::LocalBankTransfer => {
+ Ok(dirval!(BankTransferType = LocalBankTransfer))
+ }
+ api_enums::PaymentMethodType::PermataBankTransfer => {
+ Ok(dirval!(BankTransferType = PermataBankTransfer))
+ }
+ api_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)),
+ api_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)),
+ api_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)),
+ api_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)),
+ api_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)),
+ api_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)),
+ api_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)),
+ api_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)),
+ api_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)),
+ api_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)),
+ api_enums::PaymentMethodType::OpenBankingUk => {
+ Ok(dirval!(BankRedirectType = OpenBankingUk))
+ }
+ api_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)),
+ api_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)),
+ api_enums::PaymentMethodType::CardRedirect => Ok(dirval!(CardRedirectType = CardRedirect)),
+ api_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)),
+ }
+}
+
fn compile_request_pm_types(
builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
pm_types: RequestPaymentMethodTypes,
@@ -258,16 +381,220 @@ fn compile_payment_method_enabled(
Ok(agg_id)
}
+macro_rules! collect_global_variants {
+ ($parent_enum:ident) => {
+ &mut dir::enums::$parent_enum::iter()
+ .map(dir::DirValue::$parent_enum)
+ .collect::<Vec<_>>()
+ };
+}
+fn global_vec_pmt(
+ enabled_pmt: Vec<dir::DirValue>,
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+) -> Vec<cgraph::NodeId> {
+ let mut global_vector: Vec<dir::DirValue> = Vec::new();
+
+ global_vector.append(collect_global_variants!(PayLaterType));
+ global_vector.append(collect_global_variants!(WalletType));
+ global_vector.append(collect_global_variants!(BankRedirectType));
+ global_vector.append(collect_global_variants!(BankDebitType));
+ global_vector.append(collect_global_variants!(CryptoType));
+ global_vector.append(collect_global_variants!(RewardType));
+ global_vector.append(collect_global_variants!(UpiType));
+ global_vector.append(collect_global_variants!(VoucherType));
+ global_vector.append(collect_global_variants!(GiftCardType));
+ global_vector.append(collect_global_variants!(BankTransferType));
+ global_vector.append(collect_global_variants!(CardRedirectType));
+ global_vector.push(dir::DirValue::PaymentMethod(
+ dir::enums::PaymentMethod::Card,
+ ));
+ let global_vector = global_vector
+ .into_iter()
+ .filter(|global_value| !enabled_pmt.contains(global_value))
+ .collect::<Vec<_>>();
+
+ global_vector
+ .into_iter()
+ .map(|dir_v| {
+ builder.make_value_node(
+ cgraph::NodeValue::Value(dir_v),
+ Some("Payment Method Type"),
+ None::<()>,
+ )
+ })
+ .collect::<Vec<_>>()
+}
+
+fn compile_graph_for_countries_and_currencies(
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+ config: &kgraph_types::CurrencyCountryFlowFilter,
+ payment_method_type_node: cgraph::NodeId,
+) -> Result<cgraph::NodeId, KgraphError> {
+ let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
+ agg_nodes.push((
+ payment_method_type_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Normal,
+ ));
+ if let Some(country) = config.country.clone() {
+ let node_country = country
+ .into_iter()
+ .map(|country| dir::DirValue::BillingCountry(api_enums::Country::from_alpha2(country)))
+ .collect();
+ let country_agg = builder
+ .make_in_aggregator(node_country, Some("Configs for Country"), None::<()>)
+ .map_err(KgraphError::GraphConstructionError)?;
+ agg_nodes.push((
+ country_agg,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Weak,
+ ))
+ }
+
+ if let Some(currency) = config.currency.clone() {
+ let node_currency = currency
+ .into_iter()
+ .map(IntoDirValue::into_dir_value)
+ .collect::<Result<Vec<_>, _>>()?;
+ let currency_agg = builder
+ .make_in_aggregator(node_currency, Some("Configs for Currency"), None::<()>)
+ .map_err(KgraphError::GraphConstructionError)?;
+ agg_nodes.push((
+ currency_agg,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Normal,
+ ))
+ }
+ if let Some(capture_method) = config
+ .not_available_flows
+ .and_then(|naf| naf.capture_method)
+ {
+ let make_capture_node = builder.make_value_node(
+ cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(capture_method)),
+ Some("Configs for CaptureMethod"),
+ None::<()>,
+ );
+ agg_nodes.push((
+ make_capture_node,
+ cgraph::Relation::Negative,
+ cgraph::Strength::Normal,
+ ))
+ }
+
+ builder
+ .make_all_aggregator(
+ &agg_nodes,
+ Some("Country & Currency Configs With Payment Method Type"),
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)
+}
+
+fn compile_config_graph(
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+ config: &kgraph_types::CountryCurrencyFilter,
+ connector: &api_enums::RoutableConnectors,
+) -> Result<cgraph::NodeId, KgraphError> {
+ let mut agg_node_id: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
+ let mut pmt_enabled: Vec<dir::DirValue> = Vec::new();
+ if let Some(pmt) = config
+ .connector_configs
+ .get(connector)
+ .or(config.default_configs.as_ref())
+ .map(|inner| inner.0.clone())
+ {
+ for pm_filter_key in pmt {
+ match pm_filter_key {
+ (kgraph_types::PaymentMethodFilterKey::PaymentMethodType(pm), filter) => {
+ let dir_val_pm = get_dir_value_payment_method(pm)?;
+
+ let pm_node = if pm == api_enums::PaymentMethodType::Credit
+ || pm == api_enums::PaymentMethodType::Debit
+ {
+ pmt_enabled
+ .push(dir::DirValue::PaymentMethod(api_enums::PaymentMethod::Card));
+ builder.make_value_node(
+ cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(
+ dir::enums::PaymentMethod::Card,
+ )),
+ Some("PaymentMethod"),
+ None::<()>,
+ )
+ } else {
+ pmt_enabled.push(dir_val_pm.clone());
+ builder.make_value_node(
+ cgraph::NodeValue::Value(dir_val_pm),
+ Some("PaymentMethodType"),
+ None::<()>,
+ )
+ };
+
+ let node_config =
+ compile_graph_for_countries_and_currencies(builder, &filter, pm_node)?;
+
+ agg_node_id.push((
+ node_config,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Normal,
+ ));
+ }
+ (kgraph_types::PaymentMethodFilterKey::CardNetwork(cn), filter) => {
+ let dir_val_cn = cn.clone().into_dir_value()?;
+ pmt_enabled.push(dir_val_cn);
+ let cn_node = builder.make_value_node(
+ cn.clone().into_dir_value().map(Into::into)?,
+ Some("CardNetwork"),
+ None::<()>,
+ );
+ let node_config =
+ compile_graph_for_countries_and_currencies(builder, &filter, cn_node)?;
+
+ agg_node_id.push((
+ node_config,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Normal,
+ ));
+ }
+ }
+ }
+ }
+ let global_vector_pmt: Vec<cgraph::NodeId> = global_vec_pmt(pmt_enabled, builder);
+ let any_agg_pmt: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = global_vector_pmt
+ .into_iter()
+ .map(|node| (node, cgraph::Relation::Positive, cgraph::Strength::Normal))
+ .collect::<Vec<_>>();
+ let any_agg_node = builder
+ .make_any_aggregator(
+ &any_agg_pmt,
+ Some("Any Aggregator For Payment Method Types"),
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ agg_node_id.push((
+ any_agg_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Normal,
+ ));
+
+ builder
+ .make_any_aggregator(&agg_node_id, Some("Configs"), None::<()>, None)
+ .map_err(KgraphError::GraphConstructionError)
+}
+
fn compile_merchant_connector_graph(
builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
mca: admin_api::MerchantConnectorResponse,
+ config: &kgraph_types::CountryCurrencyFilter,
) -> Result<(), KgraphError> {
let connector = common_enums::RoutableConnectors::from_str(&mca.connector_name)
.map_err(|_| KgraphError::InvalidConnectorName(mca.connector_name.clone()))?;
let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
- if let Some(pms_enabled) = mca.payment_methods_enabled {
+ if let Some(pms_enabled) = mca.payment_methods_enabled.clone() {
for pm_enabled in pms_enabled {
let maybe_pm_enabled_id = compile_payment_method_enabled(builder, pm_enabled)?;
if let Some(pm_enabled_id) = maybe_pm_enabled_id {
@@ -285,10 +612,33 @@ fn compile_merchant_connector_graph(
.make_any_aggregator(&agg_nodes, Some(aggregator_info), None::<()>, None)
.map_err(KgraphError::GraphConstructionError)?;
+ let config_info = "Config for respective PaymentMethodType for the connector";
+
+ let config_enabled_agg_id = compile_config_graph(builder, config, &connector)?;
+
+ let domain_level_node_id = builder
+ .make_all_aggregator(
+ &[
+ (
+ config_enabled_agg_id,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Normal,
+ ),
+ (
+ pms_enabled_agg_id,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Normal,
+ ),
+ ],
+ Some(config_info),
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
let connector_dir_val = dir::DirValue::Connector(Box::new(ast::ConnectorChoice {
connector,
#[cfg(not(feature = "connector_choice_mca_id"))]
- sub_label: mca.business_sub_label,
+ sub_label: mca.business_sub_label.clone(),
}));
let connector_info = "Connector";
@@ -297,7 +647,7 @@ fn compile_merchant_connector_graph(
builder
.make_edge(
- pms_enabled_agg_id,
+ domain_level_node_id,
connector_node_id,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
@@ -310,6 +660,7 @@ fn compile_merchant_connector_graph(
pub fn make_mca_graph<'a>(
accts: Vec<admin_api::MerchantConnectorResponse>,
+ config: &kgraph_types::CountryCurrencyFilter,
) -> Result<cgraph::ConstraintGraph<'a, dir::DirValue>, KgraphError> {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _domain = builder.make_domain(
@@ -317,7 +668,7 @@ pub fn make_mca_graph<'a>(
"Payment methods enabled for MerchantConnectorAccount",
);
for acct in accts {
- compile_merchant_connector_graph(&mut builder, acct)?;
+ compile_merchant_connector_graph(&mut builder, acct, config)?;
}
Ok(builder.build())
@@ -327,6 +678,8 @@ pub fn make_mca_graph<'a>(
mod tests {
#![allow(clippy::expect_used)]
+ use std::collections::{HashMap, HashSet};
+
use api_models::enums as api_enums;
use euclid::{
dirval,
@@ -335,6 +688,7 @@ mod tests {
use hyperswitch_constraint_graph::{ConstraintGraph, CycleCheck, Memoization};
use super::*;
+ use crate::types as kgraph_types;
fn build_test_data<'a>() -> ConstraintGraph<'a, dir::DirValue> {
use api_models::{admin::*, payment_methods::*};
@@ -398,7 +752,36 @@ mod tests {
status: api_enums::ConnectorStatus::Inactive,
};
- make_mca_graph(vec![stripe_account]).expect("Failed graph construction")
+ let currency_country_flow_filter = kgraph_types::CurrencyCountryFlowFilter {
+ currency: Some(HashSet::from([api_enums::Currency::INR])),
+ country: Some(HashSet::from([api_enums::CountryAlpha2::IN])),
+ not_available_flows: Some(kgraph_types::NotAvailableFlows {
+ capture_method: Some(api_enums::CaptureMethod::Manual),
+ }),
+ };
+
+ let config_map = kgraph_types::CountryCurrencyFilter {
+ connector_configs: HashMap::from([(
+ api_enums::RoutableConnectors::Stripe,
+ kgraph_types::PaymentMethodFilters(HashMap::from([
+ (
+ kgraph_types::PaymentMethodFilterKey::PaymentMethodType(
+ api_enums::PaymentMethodType::Credit,
+ ),
+ currency_country_flow_filter.clone(),
+ ),
+ (
+ kgraph_types::PaymentMethodFilterKey::PaymentMethodType(
+ api_enums::PaymentMethodType::Debit,
+ ),
+ currency_country_flow_filter,
+ ),
+ ])),
+ )]),
+ default_configs: None,
+ };
+
+ make_mca_graph(vec![stripe_account], &config_map).expect("Failed graph construction")
}
#[test]
@@ -412,8 +795,8 @@ mod tests {
dirval!(PaymentMethod = Card),
dirval!(CardType = Credit),
dirval!(CardNetwork = Visa),
- dirval!(PaymentCurrency = USD),
- dirval!(PaymentAmount = 100),
+ dirval!(PaymentCurrency = INR),
+ dirval!(PaymentAmount = 101),
]),
&mut Memoization::new(),
&mut CycleCheck::new(),
@@ -711,8 +1094,11 @@ mod tests {
let data: Vec<admin_api::MerchantConnectorResponse> =
serde_json::from_value(value).expect("data");
-
- let graph = make_mca_graph(data).expect("graph");
+ let config = kgraph_types::CountryCurrencyFilter {
+ connector_configs: HashMap::new(),
+ default_configs: None,
+ };
+ let graph = make_mca_graph(data, &config).expect("graph");
let context = AnalysisContext::from_dir_values([
dirval!(Connector = Stripe),
dirval!(PaymentAmount = 212),
diff --git a/crates/kgraph_utils/src/types.rs b/crates/kgraph_utils/src/types.rs
new file mode 100644
index 00000000000..26f27896e0a
--- /dev/null
+++ b/crates/kgraph_utils/src/types.rs
@@ -0,0 +1,35 @@
+use std::collections::{HashMap, HashSet};
+
+use api_models::enums as api_enums;
+use serde::Deserialize;
+#[derive(Debug, Deserialize, Clone, Default)]
+
+pub struct CountryCurrencyFilter {
+ pub connector_configs: HashMap<api_enums::RoutableConnectors, PaymentMethodFilters>,
+ pub default_configs: Option<PaymentMethodFilters>,
+}
+
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(transparent)]
+pub struct PaymentMethodFilters(pub HashMap<PaymentMethodFilterKey, CurrencyCountryFlowFilter>);
+
+#[derive(Debug, Deserialize, Clone, PartialEq, Eq, Hash)]
+#[serde(untagged)]
+pub enum PaymentMethodFilterKey {
+ PaymentMethodType(api_enums::PaymentMethodType),
+ CardNetwork(api_enums::CardNetwork),
+}
+
+#[derive(Debug, Deserialize, Clone, Default)]
+#[serde(default)]
+pub struct CurrencyCountryFlowFilter {
+ pub currency: Option<HashSet<api_enums::Currency>>,
+ pub country: Option<HashSet<api_enums::CountryAlpha2>>,
+ pub not_available_flows: Option<NotAvailableFlows>,
+}
+
+#[derive(Debug, Deserialize, Copy, Clone, Default)]
+#[serde(default)]
+pub struct NotAvailableFlows {
+ pub capture_method: Option<api_enums::CaptureMethod>,
+}
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 6967c977753..4218fe3462c 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -1,8 +1,9 @@
mod transformers;
use std::{
- collections::hash_map,
+ collections::{hash_map, HashMap},
hash::{Hash, Hasher},
+ str::FromStr,
sync::Arc,
};
@@ -24,6 +25,7 @@ use euclid::{
use kgraph_utils::{
mca as mca_graph,
transformers::{IntoContext, IntoDirValue},
+ types::CountryCurrencyFilter,
};
use masking::PeekInterface;
use rand::{
@@ -43,8 +45,9 @@ use crate::{
},
logger,
types::{
- api, api::routing as routing_types, domain, storage as oss_storage,
- transformers::ForeignInto,
+ api::{self, routing as routing_types},
+ domain, storage as oss_storage,
+ transformers::{ForeignFrom, ForeignInto},
},
utils::{OptionExt, ValueExt},
AppState,
@@ -104,7 +107,6 @@ impl Default for MerchantAccountRoutingAlgorithm {
pub fn make_dsl_input_for_payouts(
payout_data: &payouts::PayoutData,
) -> RoutingResult<dsl_inputs::BackendInput> {
- use crate::types::transformers::ForeignFrom;
let mandate = dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
@@ -645,8 +647,32 @@ pub async fn refresh_kgraph_cache(
.map(admin_api::MerchantConnectorResponse::try_from)
.collect::<Result<Vec<_>, _>>()
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
-
- let kgraph = mca_graph::make_mca_graph(api_mcas)
+ 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 kgraph = mca_graph::make_mca_graph(api_mcas, &config_pm_filters)
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)
.attach_printable("when construction kgraph")?;
diff --git a/crates/router/src/core/payments/routing/transformers.rs b/crates/router/src/core/payments/routing/transformers.rs
index b273f18f3fd..ae779a6551f 100644
--- a/crates/router/src/core/payments/routing/transformers.rs
+++ b/crates/router/src/core/payments/routing/transformers.rs
@@ -1,8 +1,14 @@
+use std::collections::HashMap;
+
use api_models::{self, routing as routing_types};
use diesel_models::enums as storage_enums;
use euclid::{enums as dsl_enums, frontend::ast as dsl_ast};
+use kgraph_utils::types;
-use crate::types::transformers::ForeignFrom;
+use crate::{
+ configs::settings,
+ types::transformers::{ForeignFrom, ForeignInto},
+};
impl ForeignFrom<routing_types::RoutableConnectorChoice> for dsl_ast::ConnectorChoice {
fn foreign_from(from: routing_types::RoutableConnectorChoice) -> Self {
@@ -52,3 +58,40 @@ impl ForeignFrom<storage_enums::MandateDataType> for dsl_enums::MandateType {
}
}
}
+
+impl ForeignFrom<settings::PaymentMethodFilterKey> for types::PaymentMethodFilterKey {
+ fn foreign_from(from: settings::PaymentMethodFilterKey) -> Self {
+ match from {
+ settings::PaymentMethodFilterKey::PaymentMethodType(pmt) => {
+ Self::PaymentMethodType(pmt)
+ }
+ settings::PaymentMethodFilterKey::CardNetwork(cn) => Self::CardNetwork(cn),
+ }
+ }
+}
+impl ForeignFrom<settings::CurrencyCountryFlowFilter> for types::CurrencyCountryFlowFilter {
+ fn foreign_from(from: settings::CurrencyCountryFlowFilter) -> Self {
+ Self {
+ currency: from.currency,
+ country: from.country,
+ not_available_flows: from.not_available_flows.map(ForeignInto::foreign_into),
+ }
+ }
+}
+impl ForeignFrom<settings::NotAvailableFlows> for types::NotAvailableFlows {
+ fn foreign_from(from: settings::NotAvailableFlows) -> Self {
+ Self {
+ capture_method: from.capture_method,
+ }
+ }
+}
+impl ForeignFrom<settings::PaymentMethodFilters> for types::PaymentMethodFilters {
+ fn foreign_from(from: settings::PaymentMethodFilters) -> Self {
+ let iter_map = from
+ .0
+ .into_iter()
+ .map(|(key, val)| (key.foreign_into(), val.foreign_into()))
+ .collect::<HashMap<_, _>>();
+ Self(iter_map)
+ }
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json
index 273ed5ee3c6..d108e1198a7 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario13-BNPL-afterpay/Payments - Create/request.json
@@ -41,7 +41,7 @@
"zip": "94122",
"first_name": "John",
"last_name": "Doe",
- "country": "SE"
+ "country": "ES"
},
"email": "narayan@example.com"
},
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json
index 21e71ad037a..048893f3511 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario15-Bank Redirect-Ideal/Payments - Create/request.json
@@ -42,7 +42,7 @@
"city": "San Fransico",
"state": "California",
"zip": "94122",
- "country": "DE"
+ "country": "NL"
}
},
"browser_info": {
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json
index 61add73d411..c0e2a2a3d5e 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Confirm/request.json
@@ -48,7 +48,7 @@
},
"bank_name": "hypo_oberosterreich_salzburg_steiermark",
"preferred_language": "en",
- "country": "DE"
+ "country": "AT"
}
}
},
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json
index 21e71ad037a..026af8449ce 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario17-Bank Redirect-eps/Payments - Create/request.json
@@ -42,7 +42,7 @@
"city": "San Fransico",
"state": "California",
"zip": "94122",
- "country": "DE"
+ "country": "AT"
}
},
"browser_info": {
diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json
index 47f732f2153..397864885cb 100644
--- a/postman/collection-json/stripe.postman_collection.json
+++ b/postman/collection-json/stripe.postman_collection.json
@@ -13677,7 +13677,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"SE\"},\"email\":\"narayan@example.com\"},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ "raw": "{\"amount\":7000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"ES\"},\"email\":\"narayan@example.com\"},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -14537,7 +14537,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1000,\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"DE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1000,\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"NL\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -15397,7 +15397,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1000,\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"DE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ "raw": "{\"amount\":1000,\"currency\":\"EUR\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1000,\"customer_id\":\"StripeCustomer\",\"email\":\"abcdef123@gmail.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"AT\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -15576,7 +15576,7 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"eps\",\"payment_method_data\":{\"bank_redirect\":{\"eps\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_oberosterreich_salzburg_steiermark\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}"
+ "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"eps\",\"payment_method_data\":{\"bank_redirect\":{\"eps\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_oberosterreich_salzburg_steiermark\",\"preferred_language\":\"en\",\"country\":\"AT\"}}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
|
2024-05-17T13:14:13Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Refactor the Knowledge Graph to include configs(pm_filters) check, while eligibility analysis
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
- Wrote unit test
- To test it,
- You can create MCA for 2 connectors
- Do a payment using BOA and with some currency that it doesn't support , for eg:INR
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ylNGvTk4tI1OQFRGQN1CzMZMANf1jFHzTZqOkD4Ha4L4ubnngKMp98C6puzz1XPr' \
--data-raw '{
"amount": 6540,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "example@example.com"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"routing": {
"type": "single",
"data": "bankofamerica"
}
}'
```
- The payment would go through Stripe , as the eligibility analysis would fail
```
Response
{
"payment_id": "pay_dhTO36kNBB03SWsTvSKC",
"merchant_id": "merchant_1716296468",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_dhTO36kNBB03SWsTvSKC_secret_siY75j9e6hsgwNuAC3rS",
"created": "2024-05-21T13:04:21.786Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": {
"address_line1_check": "pass",
"address_postal_code_check": "pass",
"cvc_check": "pass"
},
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "example@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1716296661,
"expires": 1716300261,
"secret": "epk_a404fe01e93d445da59f0a1d7346ad90"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3PIsMcD5R7gDAGff0O0dJvGC",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3PIsMcD5R7gDAGff0O0dJvGC",
"payment_link": null,
"profile_id": "pro_vucql9T54ccffbKNdOvw",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_41ElW94TenDAaISxhaVj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-21T13:19:21.786Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-21T13:04:23.236Z",
"frm_metadata": null
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
be9343affeb178e646d4046785a105a9c6040037
|
- Wrote unit test
- To test it,
- You can create MCA for 2 connectors
- Do a payment using BOA and with some currency that it doesn't support , for eg:INR
```
Create
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ylNGvTk4tI1OQFRGQN1CzMZMANf1jFHzTZqOkD4Ha4L4ubnngKMp98C6puzz1XPr' \
--data-raw '{
"amount": 6540,
"currency": "INR",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "example@example.com"
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"routing": {
"type": "single",
"data": "bankofamerica"
}
}'
```
- The payment would go through Stripe , as the eligibility analysis would fail
```
Response
{
"payment_id": "pay_dhTO36kNBB03SWsTvSKC",
"merchant_id": "merchant_1716296468",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_dhTO36kNBB03SWsTvSKC_secret_siY75j9e6hsgwNuAC3rS",
"created": "2024-05-21T13:04:21.786Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"payment_checks": {
"address_line1_check": "pass",
"address_postal_code_check": "pass",
"cvc_check": "pass"
},
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": "example@example.com"
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://duck.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1716296661,
"expires": 1716300261,
"secret": "epk_a404fe01e93d445da59f0a1d7346ad90"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3PIsMcD5R7gDAGff0O0dJvGC",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3PIsMcD5R7gDAGff0O0dJvGC",
"payment_link": null,
"profile_id": "pro_vucql9T54ccffbKNdOvw",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_41ElW94TenDAaISxhaVj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-21T13:19:21.786Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-21T13:04:23.236Z",
"frm_metadata": null
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4669
|
Bug: Adding events for Payment Reject
Created from #4525
This covers adding events for Payment Reject operation
This event should include the payment data similar to [PaymentCancel](https://github.com/juspay/hyperswitch/pull/4166)
It should also include any metadata for the event
e.g reason for payment rejection, error codes, rejection source etc
|
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index 55b93501275..23531d2342d 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -12,6 +12,7 @@ use crate::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentAddress, PaymentData},
},
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -209,7 +210,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for Payme
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
@@ -264,6 +265,16 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for Payme
)
.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))
}
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index a6b0884d21d..5f2ed10bc5f 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -33,6 +33,10 @@ pub enum AuditEventType {
},
PaymentApprove,
PaymentCreate,
+ PaymentReject {
+ error_code: Option<String>,
+ error_message: Option<String>,
+ },
}
#[derive(Debug, Clone, Serialize)]
@@ -74,6 +78,7 @@ impl Event for AuditEvent {
AuditEventType::PaymentUpdate { .. } => "payment_update",
AuditEventType::PaymentApprove { .. } => "payment_approve",
AuditEventType::PaymentCreate { .. } => "payment_create",
+ AuditEventType::PaymentReject { .. } => "payment_rejected",
};
format!(
"{event_type}-{}",
|
2024-10-29T18:10:34Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [X] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Pass along request_state to payment_core
Modify the UpdateTracker trait to accept request state
Modify the PaymentReject implementation of UpdateTracker to generate an event
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
Files changed
1. `crates/router/src/core/payments/operations/payment_reject.rs`
2. `crates/router/src/events/audit_events.rs`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Resolves #4669
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
This requires FRM related flows to be tested, and may not be tested locally.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ce95b6538dca4515b04ac65c2b1063bdd0a9c3a7
|
This requires FRM related flows to be tested, and may not be tested locally.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4672
|
Bug: Add audit events for PaymentCreate update
Created from https://github.com/juspay/hyperswitch/issues/4525
This covers adding events for PaymentCreate operation
This event should include the payment data similar to https://github.com/juspay/hyperswitch/pull/4166
It should also include any metadata for the event
e.g reason for payment rejection, error codes, rejection source etc
|
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index d4057c523bc..c65e58ea2d4 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -42,6 +42,7 @@ use crate::{
utils as core_utils,
},
db::StorageInterface,
+ events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
@@ -818,7 +819,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
- _req_state: ReqState,
+ req_state: ReqState,
mut payment_data: PaymentData<F>,
customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
@@ -923,6 +924,11 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
)
.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((
diff --git a/crates/router/src/events/audit_events.rs b/crates/router/src/events/audit_events.rs
index 9b7a688f7eb..54c1934e36f 100644
--- a/crates/router/src/events/audit_events.rs
+++ b/crates/router/src/events/audit_events.rs
@@ -27,6 +27,7 @@ pub enum AuditEventType {
capture_amount: Option<MinorUnit>,
multiple_capture_count: Option<i16>,
},
+ PaymentCreate,
}
#[derive(Debug, Clone, Serialize)]
@@ -65,6 +66,7 @@ impl Event for AuditEvent {
AuditEventType::RefundSuccess => "refund_success",
AuditEventType::RefundFail => "refund_fail",
AuditEventType::PaymentCancelled { .. } => "payment_cancelled",
+ AuditEventType::PaymentCreate { .. } => "payment_create",
};
format!(
"{event_type}-{}",
|
2024-10-24T11:52:21Z
|
## Type of Change
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR adds an Audit event for the PaymentCreate operation.
### Additional Changes
- [x] This PR modifies the files below
- `crates/router/src/core/payments/operations/payment_create.rs`
- `crates/router/src/events/audit_events.rs`
## Motivation and Context
This PR fixes #4672
## How did you test it
Hit the `Payments - Create` endpoint with `"confirm": false`
- Curl:
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_LZcIA7XeMpnK5satp4CDvjcnHCaeKTBcosyuBBJaknZu1odhFo96cwS0nSdfzuJF' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"profile_id": "pro_v5sFoHe80OeiUlIonocM"
}'
```
- Response:
```json
{
"payment_id": "pay_pvLYaf7aejhEVszi9OnZ",
"merchant_id": "merchant_1726046328",
"status": "requires_confirmation",
"amount": 6540,
"net_amount": 6540,
"shipping_cost": null,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_pvLYaf7aejhEVszi9OnZ_secret_a9hynS88hC0oz7LNRjFc",
"created": "2024-11-06T18:21:43.625Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+65"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": null,
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": "token_btocKPXDGHw1UKcvTpMW",
"shipping": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
},
"email": null
},
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://google.com/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1730917303,
"expires": 1730920903,
"secret": "epk_11b7865dffb2468e8d16f29afcf8677f"
},
"manual_retry_allowed": null,
"connector_transaction_id": null,
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_v5sFoHe80OeiUlIonocM",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": null,
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-11-06T18:36:43.625Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-11-06T18:21:43.669Z",
"charges": null,
"frm_metadata": null,
"merchant_order_reference_id": null,
"order_tax_amount": null,
"connector_mandate_id": null
}
```
Audit log will get generated and can be viewed in hyperswitch-audit-events topic in kafka with `PaymentCreate` event-type.
<img width="1298" alt="Screenshot 2024-11-06 at 11 52 00 PM" src="https://github.com/user-attachments/assets/efc6ff47-3a6e-411a-a539-3b4d13f71967">
Now hit the `Payments - Confirm` endpoint, and audit log will get generated with `PaymentConfirm` event-type.
<img width="1350" alt="image" src="https://github.com/user-attachments/assets/20afd6ca-7c84-4a77-885b-e235ef5cd98c">
## Checklist
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
1ba3d84df1e93d2286db1a262c4a67b3861b90c0
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4670
|
Bug: [REFACTOR] remove `deref` impl on `Cache` type
Currently `Cache` is a type having inner value as `MokaCache`.
```
pub struct Cache {
inner: MokaCache<String, Arc<dyn Cacheable>>,
}
```
There's a deref impl for this type which returns the inner `MokaCache`. We should instead have custom methods on `Cache` which calls the `MokaCache` methods instead of deref doing the job. There's already custom methods available on `Cache`. Invoke these method instead of calling it on the deref of `Cache`.
|
diff --git a/crates/router/src/db/cache.rs b/crates/router/src/db/cache.rs
index d9db13dde80..ba0aae55e89 100644
--- a/crates/router/src/db/cache.rs
+++ b/crates/router/src/db/cache.rs
@@ -88,7 +88,7 @@ where
Fut: futures::Future<Output = CustomResult<T, errors::StorageError>> + Send,
{
let data = fun().await?;
- in_memory.async_map(|cache| cache.invalidate(key)).await;
+ in_memory.async_map(|cache| cache.remove(key)).await;
let redis_conn = store
.get_redis_conn()
diff --git a/crates/router/tests/cache.rs b/crates/router/tests/cache.rs
index 040e0dddf97..c6eef06db7b 100644
--- a/crates/router/tests/cache.rs
+++ b/crates/router/tests/cache.rs
@@ -50,8 +50,14 @@ async fn invalidate_existing_cache_success() {
let response_body = response.body().await;
println!("invalidate Cache: {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
- assert!(cache::CONFIG_CACHE.get(&cache_key).await.is_none());
- assert!(cache::ACCOUNTS_CACHE.get(&cache_key).await.is_none());
+ assert!(cache::CONFIG_CACHE
+ .get_val::<String>(&cache_key)
+ .await
+ .is_none());
+ assert!(cache::ACCOUNTS_CACHE
+ .get_val::<String>(&cache_key)
+ .await
+ .is_none());
}
#[actix_web::test]
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index dc2a2225dc9..4cd2fc0c504 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -94,13 +94,6 @@ pub struct Cache {
inner: MokaCache<String, Arc<dyn Cacheable>>,
}
-impl std::ops::Deref for Cache {
- type Target = MokaCache<String, Arc<dyn Cacheable>>;
- fn deref(&self) -> &Self::Target {
- &self.inner
- }
-}
-
impl Cache {
/// With given `time_to_live` and `time_to_idle` creates a moka cache.
///
@@ -122,16 +115,16 @@ impl Cache {
}
pub async fn push<T: Cacheable>(&self, key: String, val: T) {
- self.insert(key, Arc::new(val)).await;
+ self.inner.insert(key, Arc::new(val)).await;
}
pub async fn get_val<T: Clone + Cacheable>(&self, key: &str) -> Option<T> {
- let val = self.get(key).await?;
+ let val = self.inner.get(key).await?;
(*val).as_any().downcast_ref::<T>().cloned()
}
pub async fn remove(&self, key: &str) {
- self.invalidate(key).await;
+ self.inner.invalidate(key).await;
}
}
@@ -208,7 +201,7 @@ where
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
{
let data = fun().await?;
- in_memory.async_map(|cache| cache.invalidate(key)).await;
+ in_memory.async_map(|cache| cache.remove(key)).await;
let redis_conn = store
.get_redis_conn()
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index 349d1872d2a..2922dbcadba 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -60,16 +60,16 @@ impl PubSubInterface for redis_interface::RedisConnectionPool {
let key = match key {
CacheKind::Config(key) => {
- CONFIG_CACHE.invalidate(key.as_ref()).await;
+ CONFIG_CACHE.remove(key.as_ref()).await;
key
}
CacheKind::Accounts(key) => {
- ACCOUNTS_CACHE.invalidate(key.as_ref()).await;
+ ACCOUNTS_CACHE.remove(key.as_ref()).await;
key
}
CacheKind::All(key) => {
- CONFIG_CACHE.invalidate(key.as_ref()).await;
- ACCOUNTS_CACHE.invalidate(key.as_ref()).await;
+ CONFIG_CACHE.remove(key.as_ref()).await;
+ ACCOUNTS_CACHE.remove(key.as_ref()).await;
key
}
};
|
2024-05-17T10:26:23Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Currently `Cache` is a type having inner value as `MokaCache`.
```
pub struct Cache {
inner: MokaCache<String, Arc<dyn Cacheable>>,
}
```
There's a deref impl on this type which returns the inner `MokaCache`. We should instead have custom methods on `Cache` which calls the `MokaCache` methods instead of deref doing the job. There's already custom methods available on `Cache`. This PR refactors it to invoke these methods instead of calling it on the deref of `Cache`.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Basic sanity tests should suffice
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
a62f69d447245273c73611309055d2341a47b783
|
Basic sanity tests should suffice
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4663
|
Bug: refactor session call to remove the shipping and billing parameter fields if null for apple pay and google pay
remove the shipping and billing parameter fields if null for apple pay and google pay as it not necessary to pass
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index dcabbde7ebe..d7ba24b5a3e 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3872,6 +3872,7 @@ pub struct GpayAllowedMethodsParameters {
/// Is billing address required
pub billing_address_required: Option<bool>,
/// Billing address parameters
+ #[serde(skip_serializing_if = "Option::is_none")]
pub billing_address_parameters: Option<GpayBillingAddressParameters>,
}
@@ -4247,7 +4248,9 @@ pub struct ApplePayPaymentRequest {
pub supported_networks: Option<Vec<String>>,
pub merchant_identifier: Option<String>,
/// The required billing contact fields for connector
+ #[serde(skip_serializing_if = "Option::is_none")]
pub required_billing_contact_fields: Option<ApplePayBillingContactFields>,
+ #[serde(skip_serializing_if = "Option::is_none")]
/// The required shipping contacht fields for connector
pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>,
}
|
2024-05-16T11:50:28Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
remove the shipping and billing parameter fields if null for apple pay and google pay.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
-> Apple pay payment create with confirm false
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRIQTZMeTl2WTNOd0xtRndjR3hsTG1OdmJTOXZZM053TURRdFlYQndiR1Z5YjI5MFkyRm5NekFkQmdOVkhRNEVGZ1FVSS9KSnhFK1Q1TzhuNXNUMktHdy9vcnY5TGtzd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZkJnTlZIU01FR0RBV2dCUzdzTjZoV0RPSW1xU0ttZDYrdmV1djJzc2txekEzQmdOVkhSOEVNREF1TUN5Z0txQW9oaVpvZEhSd09pOHZZM0pzTG1Gd2NHeGxMbU52YlM5aGNIQnNaWEp2YjNSallXY3pMbU55YkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RUFZS0tvWklodmRqWkFZQ0RnUUNCUUF3Q2dZSUtvWkl6ajBFQXdJRFp3QXdaQUl3T3M5eWcxRVdtYkdHK3pYRFZzcGl2L1FYN2RrUGRVMmlqcjd4bklGZVFyZUorSmozbTFtZm1OVkJEWStkNmNMK0FqQXlMZFZFSWJDakJYZHNYZk00TzVCbi9SZDhMQ0Z0bGsvR2NtbUNFbTlVK0hwOUc1bkxtd21KSVdFR21ROEpraDBBQURHQ0FZZ3dnZ0dFQWdFQk1JR0dNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV3SUlUREJCU1ZHZFZEWXdDd1lKWUlaSUFXVURCQUlCb0lHVE1CZ0dDU3FHU0liM0RRRUpBekVMQmdrcWhraUc5dzBCQndFd0hBWUpLb1pJaHZjTkFRa0ZNUThYRFRJME1ETXhOREE1TkRNeU0xb3dLQVlKS29aSWh2Y05BUWswTVJzdNTdMRElUVUQwcVI3RHd5SGx1VG0xMjJCejA5c2FzMkJVWitFRTlVPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBoMkNUKytubXZpYjU3YWNJZmVKTjFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}
```
-> Make a `/session` call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: api_key' \
--data '{
"payment_id": "pay_oit9SUYrdsYlI0WvCh1L",
"wallets": [],
"client_secret": "pay_oit9SUYrdsYlI0WvCh1L_secret_N61PV7OLGKa7PI0dv2Wo"
}'
```
Since the business profile config is not enabled the shipping details field is not present

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
4b5b558dae8d2fefb66b8b16c486f07e3e800758
|
-> Apple pay payment create with confirm false
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRIQTZMeTl2WTNOd0xtRndjR3hsTG1OdmJTOXZZM053TURRdFlYQndiR1Z5YjI5MFkyRm5NekFkQmdOVkhRNEVGZ1FVSS9KSnhFK1Q1TzhuNXNUMktHdy9vcnY5TGtzd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZkJnTlZIU01FR0RBV2dCUzdzTjZoV0RPSW1xU0ttZDYrdmV1djJzc2txekEzQmdOVkhSOEVNREF1TUN5Z0txQW9oaVpvZEhSd09pOHZZM0pzTG1Gd2NHeGxMbU52YlM5aGNIQnNaWEp2YjNSallXY3pMbU55YkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RUFZS0tvWklodmRqWkFZQ0RnUUNCUUF3Q2dZSUtvWkl6ajBFQXdJRFp3QXdaQUl3T3M5eWcxRVdtYkdHK3pYRFZzcGl2L1FYN2RrUGRVMmlqcjd4bklGZVFyZUorSmozbTFtZm1OVkJEWStkNmNMK0FqQXlMZFZFSWJDakJYZHNYZk00TzVCbi9SZDhMQ0Z0bGsvR2NtbUNFbTlVK0hwOUc1bkxtd21KSVdFR21ROEpraDBBQURHQ0FZZ3dnZ0dFQWdFQk1JR0dNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV3SUlUREJCU1ZHZFZEWXdDd1lKWUlaSUFXVURCQUlCb0lHVE1CZ0dDU3FHU0liM0RRRUpBekVMQmdrcWhraUc5dzBCQndFd0hBWUpLb1pJaHZjTkFRa0ZNUThYRFRJME1ETXhOREE1TkRNeU0xb3dLQVlKS29aSWh2Y05BUWswTVJzdNTdMRElUVUQwcVI3RHd5SGx1VG0xMjJCejA5c2FzMkJVWitFRTlVPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBoMkNUKytubXZpYjU3YWNJZmVKTjFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}
```
-> Make a `/session` call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: api_key' \
--data '{
"payment_id": "pay_oit9SUYrdsYlI0WvCh1L",
"wallets": [],
"client_secret": "pay_oit9SUYrdsYlI0WvCh1L_secret_N61PV7OLGKa7PI0dv2Wo"
}'
```
Since the business profile config is not enabled the shipping details field is not present

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4666
|
Bug: Creating a payment will shutdown the server due to stack overflow
### Discussed in https://github.com/juspay/hyperswitch/discussions/4636
<div type='discussions-op-text'>
<sup>Originally posted by **Rudy-Zidan** May 14, 2024</sup>
When ever i try to run the hyperswitch-web a call to "create-payment-intent" being triggered which will fail for empty reason
from the server side i see the following logs:
```
hyperswitch-hyperswitch-server-1 | {"message":"[SERVER_WRAP - EVENT] router::services::api","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"INFO","target":"router::services::api","service":"router","line":1143,"file":"crates/router/src/services/api.rs","fn":"server_wrap","full_name":"router::services::api::server_wrap","time":"2024-05-13T20:54:41.169167836Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","flow":"PaymentsCreate","extra":{"headers":"{\"accept-encoding\": \"**MASKED**\", \"host\": \"**MASKED**\", \"connection\": \"**MASKED**\", \"content-length\": \"**MASKED**\", \"accept\": \"**MASKED**\", \"user-agent\": \"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)\", \"api-key\": \"**MASKED**\", \"content-type\": \"**MASKED**\"}","tag":"BeginRequest","payload":"PaymentsRequest { amount: Some(Value(2999)), currency: Some(USD), amount_to_capture: None, payment_id: Some(PaymentIntentId(\"pay_ey8XCkOrX9XWspjLqoTD\")), merchant_id: None, routing: None, connector: None, capture_method: Some(Automatic), authentication_type: Some(ThreeDs), billing: Some(Address { address: Some(AddressDetails { city: Some(\"San Fransico\"), country: Some(US), line1: Some(*** alloc::string::String ***), line2: Some(*** alloc::string::String ***), line3: Some(*** alloc::string::String ***), zip: Some(*** alloc::string::String ***), state: Some(*** alloc::string::String ***), first_name: Some(*** alloc::string::String ***), last_name: Some(*** alloc::string::String ***) }), phone: Some(PhoneDetails { number: Some(*** alloc::string::String ***), country_code: Some(\"+91\") }), email: None }), capture_on: None, confirm: Some(false), customer: None, customer_id: Some(\"hyperswitch_sdk_demo_id\"), email: Some(Email(***********************@gmail.com)), name: None, phone: None, phone_country_code: None, off_session: None, description: Some(\"Hello this is description\"), return_url: None, setup_future_usage: None, payment_method_data: None, payment_method: None, payment_token: None, card_cvc: None, shipping: Some(Address { address: Some(AddressDetails { city: Some(\"Banglore\"), country: Some(US), line1: Some(*** alloc::string::String ***), line2: Some(*** alloc::string::String ***), line3: Some(*** alloc::string::String ***), zip: Some(*** alloc::string::String ***), state: Some(*** alloc::string::String ***), first_name: Some(*** alloc::string::String ***), last_name: Some(*** alloc::string::String ***) }), phone: Some(PhoneDetails { number: Some(*** alloc::string::String ***), country_code: Some(\"+1\") }), email: None }), statement_descriptor_name: None, statement_descriptor_suffix: None, order_details: Some([OrderDetailsWithAmount { product_name: \"Apple iphone 15\", quantity: 1, amount: 2999, requires_shipping: None, product_img_link: None, product_id: None, category: None, brand: None, product_type: None }]), client_secret: None, mandate_data: None, customer_acceptance: None, mandate_id: None, browser_info: None, payment_experience: None, payment_method_type: None, business_country: None, business_label: None, merchant_connector_details: None, allowed_payment_method_types: None, business_sub_label: None, retry_action: None, metadata: Some(*** serde_json::value::Value ***), connector_metadata: Some(ConnectorMetadata { apple_pay: None, airwallex: None, noon: Some(NoonData { order_category: Some(\"applepay\") }) }), feature_metadata: None, payment_link: None, payment_link_config: None, profile_id: None, surcharge_details: None, payment_type: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, recurring_details: None }","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"pay_ey8XCkOrX9XWspjLqoTD","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}}
hyperswitch-hyperswitch-server-1 | {"message":"[GET_OR_POPULATE_REDIS - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":376,"file":"crates/diesel_models/src/query/generics.rs","fn":"get_or_populate_redis","full_name":"diesel_models::query::generics::get_or_populate_redis","time":"2024-05-13T20:54:41.200493378Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","flow":"PaymentsCreate","extra":{"query":"SELECT \"api_keys\".\"key_id\", \"api_keys\".\"merchant_id\", \"api_keys\".\"name\", \"api_keys\".\"description\", \"api_keys\".\"hashed_api_key\", \"api_keys\".\"prefix\", \"api_keys\".\"created_at\", \"api_keys\".\"expires_at\", \"api_keys\".\"last_used\" FROM \"api_keys\" WHERE (\"api_keys\".\"hashed_api_key\" = $1) -- binds: [HashedApiKey(\"0e1be6b9d0b81d7ad11a839e2a7c1e5a8b4c206c4cdb30fea9a2971415db42f1\")]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"pay_ey8XCkOrX9XWspjLqoTD","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}}
hyperswitch-hyperswitch-server-1 | {"message":"[PERFORM_LOCKING_ACTION - EVENT] Lock acquired for locking input LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None }","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"INFO","target":"router::core::api_locking","service":"router","line":83,"file":"crates/router/src/core/api_locking.rs","fn":"perform_locking_action","full_name":"router::core::api_locking::perform_locking_action","time":"2024-05-13T20:54:41.221458336Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"pay_ey8XCkOrX9XWspjLqoTD","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}}
hyperswitch-hyperswitch-server-1 | {"message":"[FIND_BUSINESS_PROFILE_BY_PROFILE_ID - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":376,"file":"crates/diesel_models/src/query/generics.rs","fn":"find_business_profile_by_profile_id","full_name":"diesel_models::query::generics::find_business_profile_by_profile_id","time":"2024-05-13T20:54:41.223726670Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"SELECT \"business_profile\".\"profile_id\", \"business_profile\".\"merchant_id\", \"business_profile\".\"profile_name\", \"business_profile\".\"created_at\", \"business_profile\".\"modified_at\", \"business_profile\".\"return_url\", \"business_profile\".\"enable_payment_response_hash\", \"business_profile\".\"payment_response_hash_key\", \"business_profile\".\"redirect_to_merchant_with_http_post\", \"business_profile\".\"webhook_details\", \"business_profile\".\"metadata\", \"business_profile\".\"routing_algorithm\", \"business_profile\".\"intent_fulfillment_time\", \"business_profile\".\"frm_routing_algorithm\", \"business_profile\".\"payout_routing_algorithm\", \"business_profile\".\"is_recon_enabled\", \"business_profile\".\"applepay_verified_domains\", \"business_profile\".\"payment_link_config\", \"business_profile\".\"session_expiry\", \"business_profile\".\"authentication_connector_details\" FROM \"business_profile\" WHERE (\"business_profile\".\"profile_id\" = $1) -- binds: [\"pro_54CtNmzvo0L4wQN9A2bT\"]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}}
hyperswitch-hyperswitch-server-1 | {"message":"[FIND_BUSINESS_PROFILE_BY_PROFILE_ID - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":376,"file":"crates/diesel_models/src/query/generics.rs","fn":"find_business_profile_by_profile_id","full_name":"diesel_models::query::generics::find_business_profile_by_profile_id","time":"2024-05-13T20:54:41.225574920Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"SELECT \"business_profile\".\"profile_id\", \"business_profile\".\"merchant_id\", \"business_profile\".\"profile_name\", \"business_profile\".\"created_at\", \"business_profile\".\"modified_at\", \"business_profile\".\"return_url\", \"business_profile\".\"enable_payment_response_hash\", \"business_profile\".\"payment_response_hash_key\", \"business_profile\".\"redirect_to_merchant_with_http_post\", \"business_profile\".\"webhook_details\", \"business_profile\".\"metadata\", \"business_profile\".\"routing_algorithm\", \"business_profile\".\"intent_fulfillment_time\", \"business_profile\".\"frm_routing_algorithm\", \"business_profile\".\"payout_routing_algorithm\", \"business_profile\".\"is_recon_enabled\", \"business_profile\".\"applepay_verified_domains\", \"business_profile\".\"payment_link_config\", \"business_profile\".\"session_expiry\", \"business_profile\".\"authentication_connector_details\" FROM \"business_profile\" WHERE (\"business_profile\".\"profile_id\" = $1) -- binds: [\"pro_54CtNmzvo0L4wQN9A2bT\"]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}}
hyperswitch-hyperswitch-server-1 | {"message":"[INSERT_ADDRESS_FOR_PAYMENTS - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":85,"file":"crates/diesel_models/src/query/generics.rs","fn":"insert_address_for_payments","full_name":"diesel_models::query::generics::insert_address_for_payments","time":"2024-05-13T20:54:41.226624211Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"INSERT INTO \"address\" (\"address_id\", \"city\", \"country\", \"line1\", \"line2\", \"line3\", \"state\", \"zip\", \"first_name\", \"last_name\", \"phone_number\", \"country_code\", \"customer_id\", \"merchant_id\", \"payment_id\", \"created_at\", \"modified_at\", \"updated_by\", \"email\") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, DEFAULT) -- binds: [\"add_3dJ36tWTY2E8KzBegwhi\", \"Banglore\", US, Encryption { inner: *** Encrypted data of length 36 bytes *** }, Encryption { inner: *** Encrypted data of length 35 bytes *** }, Encryption { inner: *** Encrypted data of length 35 bytes *** }, Encryption { inner: *** Encrypted data of length 36 bytes *** }, Encryption { inner: *** Encrypted data of length 34 bytes *** }, Encryption { inner: *** Encrypted data of length 34 bytes *** }, Encryption { inner: *** Encrypted data of length 31 bytes *** }, Encryption { inner: *** Encrypted data of length 37 bytes *** }, \"+1\", \"hyperswitch_sdk_demo_id\", \"merchant_1715629529\", \"pay_ey8XCkOrX9XWspjLqoTD\", 2024-05-13 20:54:41.226276836, 2024-05-13 20:54:41.226276836, \"postgres_only\"]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}}
hyperswitch-hyperswitch-server-1 | {"message":"[INSERT_ADDRESS_FOR_PAYMENTS - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":85,"file":"crates/diesel_models/src/query/generics.rs","fn":"insert_address_for_payments","full_name":"diesel_models::query::generics::insert_address_for_payments","time":"2024-05-13T20:54:41.231528295Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"INSERT INTO \"address\" (\"address_id\", \"city\", \"country\", \"line1\", \"line2\", \"line3\", \"state\", \"zip\", \"first_name\", \"last_name\", \"phone_number\", \"country_code\", \"customer_id\", \"merchant_id\", \"payment_id\", \"created_at\", \"modified_at\", \"updated_by\", \"email\") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, DEFAULT) -- binds: [\"add_5XjpF5T4tDV7AP1wcqFH\", \"San Fransico\", US, Encryption { inner: *** Encrypted data of length 32 bytes *** }, Encryption { inner: *** Encrypted data of length 43 bytes *** }, Encryption { inner: *** Encrypted data of length 43 bytes *** }, Encryption { inner: *** Encrypted data of length 38 bytes *** }, Encryption { inner: *** Encrypted data of length 33 bytes *** }, Encryption { inner: *** Encrypted data of length 34 bytes *** }, Encryption { inner: *** Encrypted data of length 31 bytes *** }, Encryption { inner: *** Encrypted data of length 38 bytes *** }, \"+91\", \"hyperswitch_sdk_demo_id\", \"merchant_1715629529\", \"pay_ey8XCkOrX9XWspjLqoTD\", 2024-05-13 20:54:41.231505795, 2024-05-13 20:54:41.231505795, \"postgres_only\"]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}}
hyperswitch-hyperswitch-server-1 | {"message":"[INSERT_PAYMENT_INTENT - EVENT] diesel_models::query::generics","hostname":"9fda4b3f751e","pid":1,"env":"sandbox","version":"v1.108.0-dirty-a4c8ad3-2024-04-25T00:03:05.000000000Z","build":"0.1.0-a4c8ad3-2024-04-25T00:03:05.000000000Z-1.78.0-release-aarch64-unknown-linux-gnu","level":"DEBUG","target":"diesel_models::query::generics","service":"router","line":85,"file":"crates/diesel_models/src/query/generics.rs","fn":"insert_payment_intent","full_name":"diesel_models::query::generics::insert_payment_intent","time":"2024-05-13T20:54:41.232687545Z","request_id":"018f73bc-72fe-75ea-99b8-3b63e3f4cc19","request_method":"POST","request_url_path":"/payments","merchant_id":"merchant_1715629529","flow":"PaymentsCreate","extra":{"query":"INSERT INTO \"payment_intent\" (\"payment_id\", \"merchant_id\", \"status\", \"amount\", \"currency\", \"amount_captured\", \"customer_id\", \"description\", \"return_url\", \"metadata\", \"connector_id\", \"shipping_address_id\", \"billing_address_id\", \"statement_descriptor_name\", \"statement_descriptor_suffix\", \"created_at\", \"modified_at\", \"last_synced\", \"setup_future_usage\", \"off_session\", \"client_secret\", \"active_attempt_id\", \"business_country\", \"business_label\", \"order_details\", \"allowed_payment_method_types\", \"connector_metadata\", \"feature_metadata\", \"attempt_count\", \"profile_id\", \"merchant_decision\", \"payment_link_id\", \"payment_confirm_source\", \"updated_by\", \"surcharge_applicable\", \"request_incremental_authorization\", \"incremental_authorization_allowed\", \"authorization_count\", \"session_expiry\", \"fingerprint_id\", \"request_external_three_ds_authentication\") VALUES ($1, $2, $3, $4, $5, DEFAULT, DEFAULT, $6, DEFAULT, $7, DEFAULT, $8, $9, DEFAULT, DEFAULT, $10, $11, $12, DEFAULT, DEFAULT, $13, $14, DEFAULT, DEFAULT, $15, DEFAULT, $16, DEFAULT, $17, $18, DEFAULT, DEFAULT, DEFAULT, $19, DEFAULT, $20, DEFAULT, DEFAULT, $21, DEFAULT, DEFAULT) -- binds: [\"pay_ey8XCkOrX9XWspjLqoTD\", \"merchant_1715629529\", RequiresPaymentMethod, 2999, USD, \"Hello this is description\", *** serde_json::value::Value ***, \"add_3dJ36tWTY2E8KzBegwhi\", \"add_5XjpF5T4tDV7AP1wcqFH\", 2024-05-13 20:54:41.232288461, 2024-05-13 20:54:41.232288461, 2024-05-13 20:54:41.232288461, \"pay_ey8XCkOrX9XWspjLqoTD_secret_VMJKXn8hFbFOC424eAHo\", \"pay_ey8XCkOrX9XWspjLqoTD_1\", [*** serde_json::value::Value ***], Object {\"apple_pay\": Null, \"airwallex\": Null, \"noon\": Object {\"order_category\": String(\"applepay\")}}, 1, \"pro_54CtNmzvo0L4wQN9A2bT\", \"postgres_only\", Default, 2024-05-13 21:09:41.23227917]","http.scheme":"http","http.route":"/payments","http.client_ip":"172.26.0.1","http.target":"/payments","http.flavor":"1.1","payment_id":"payment_intent_id = \"pay_ey8XCkOrX9XWspjLqoTD\"","trace_id":"00000000000000000000000000000000","http.user_agent":"node-fetch/1.0 (+https://github.com/bitinn/node-fetch)","http.method":"POST","otel.name":"HTTP POST /payments","lock_action":"Hold { input: LockingInput { unique_locking_key: \"pay_ey8XCkOrX9XWspjLqoTD\", api_identifier: Payments, override_lock_retries: None } }","otel.kind":"server","http.host":"localhost:8080"}}
hyperswitch-hyperswitch-server-1 |
hyperswitch-hyperswitch-server-1 | thread 'actix-server worker 3' has overflowed its stack
hyperswitch-hyperswitch-server-1 | fatal runtime error: stack overflow
hyperswitch-hyperswitch-server-1 |
hyperswitch-hyperswitch-server-1 exited with code 133
```
i checked my memory for docker container it only use 2GB and the configuration is 12 GB.
same happens when i try it from the control center
<img width="1725" alt="Screenshot 2024-05-14 at 12 05 32 AM" src="https://github.com/juspay/hyperswitch/assets/19466376/376e1544-3008-49fe-97dd-67ff2cca9785">
Any ideas why?</div>
|
diff --git a/Dockerfile b/Dockerfile
index e9591e5e9f2..a8697177716 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -61,7 +61,8 @@ ENV TZ=Etc/UTC \
RUN_ENV=${RUN_ENV} \
CONFIG_DIR=${CONFIG_DIR} \
SCHEDULER_FLOW=${SCHEDULER_FLOW} \
- BINARY=${BINARY}
+ BINARY=${BINARY} \
+ RUST_MIN_STACK=4194304
RUN mkdir -p ${BIN_DIR}
|
2024-05-16T09:43:53Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Add a default `RUST_MIN_STACK` size in the docker images for router
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/discussions/4636
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- generating a docker image locally and testing it
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f79c12d4f78ac622300e56f7159ca72d65a4ac0d
|
- generating a docker image locally and testing it
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4651
|
Bug: Provide access of cypress tests to hyperswitch qa
Provide access to Cypress tests for the Hyperswitch QA team. Previously, QA did not have approval access.
|
2024-05-15T12:02:49Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [x] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
e79524b295544a959ec4c0dbdb71e5538adebc9d
| |||
juspay/hyperswitch
|
juspay__hyperswitch-4647
|
Bug: [BUG]: 2-Letter State abbreviation is not accepted
### Bug Description
Currently 2-Letter State abbreviation is not accepted, in `billing.state` if you pass 2 letter valid state it should not throw an error
### Expected Behavior
Both 2 letter and full state name shall be accepted in `billing.state` and should be manipulated according to the requirements before sending it to the connector.
### Actual Behavior
Currently 2-Letter State abbreviation is not accepted, in `billing.state` if you pass 2 letter valid state it should not throw an error
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 8b0974cc4f8..74eb8c048f9 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2010,7 +2010,9 @@ pub enum FileUploadProvider {
Checkout,
}
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display)]
+#[derive(
+ Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
+)]
pub enum UsStatesAbbreviation {
AL,
AK,
@@ -2073,7 +2075,9 @@ pub enum UsStatesAbbreviation {
WY,
}
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display)]
+#[derive(
+ Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,
+)]
pub enum CanadaStatesAbbreviation {
AB,
BC,
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 6a569e76a62..0d8f42e6504 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -10,6 +10,7 @@ use base64::Engine;
use common_utils::{
date_time,
errors::ReportSwitchExt,
+ ext_traits::StringExt,
pii::{self, Email, IpAddress},
};
use diesel_models::enums;
@@ -1801,72 +1802,80 @@ pub fn get_webhook_merchant_secret_key(connector_label: &str, merchant_id: &str)
impl ForeignTryFrom<String> for UsStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
- let binding = value.as_str().to_lowercase();
- let state = binding.as_str();
- match state {
- "alabama" => Ok(Self::AL),
- "alaska" => Ok(Self::AK),
- "american samoa" => Ok(Self::AS),
- "arizona" => Ok(Self::AZ),
- "arkansas" => Ok(Self::AR),
- "california" => Ok(Self::CA),
- "colorado" => Ok(Self::CO),
- "connecticut" => Ok(Self::CT),
- "delaware" => Ok(Self::DE),
- "district of columbia" | "columbia" => Ok(Self::DC),
- "federated states of micronesia" | "micronesia" => Ok(Self::FM),
- "florida" => Ok(Self::FL),
- "georgia" => Ok(Self::GA),
- "guam" => Ok(Self::GU),
- "hawaii" => Ok(Self::HI),
- "idaho" => Ok(Self::ID),
- "illinois" => Ok(Self::IL),
- "indiana" => Ok(Self::IN),
- "iowa" => Ok(Self::IA),
- "kansas" => Ok(Self::KS),
- "kentucky" => Ok(Self::KY),
- "louisiana" => Ok(Self::LA),
- "maine" => Ok(Self::ME),
- "marshall islands" => Ok(Self::MH),
- "maryland" => Ok(Self::MD),
- "massachusetts" => Ok(Self::MA),
- "michigan" => Ok(Self::MI),
- "minnesota" => Ok(Self::MN),
- "mississippi" => Ok(Self::MS),
- "missouri" => Ok(Self::MO),
- "montana" => Ok(Self::MT),
- "nebraska" => Ok(Self::NE),
- "nevada" => Ok(Self::NV),
- "new hampshire" => Ok(Self::NH),
- "new jersey" => Ok(Self::NJ),
- "new mexico" => Ok(Self::NM),
- "new york" => Ok(Self::NY),
- "north carolina" => Ok(Self::NC),
- "north dakota" => Ok(Self::ND),
- "northern mariana islands" => Ok(Self::MP),
- "ohio" => Ok(Self::OH),
- "oklahoma" => Ok(Self::OK),
- "oregon" => Ok(Self::OR),
- "palau" => Ok(Self::PW),
- "pennsylvania" => Ok(Self::PA),
- "puerto rico" => Ok(Self::PR),
- "rhode island" => Ok(Self::RI),
- "south carolina" => Ok(Self::SC),
- "south dakota" => Ok(Self::SD),
- "tennessee" => Ok(Self::TN),
- "texas" => Ok(Self::TX),
- "utah" => Ok(Self::UT),
- "vermont" => Ok(Self::VT),
- "virgin islands" => Ok(Self::VI),
- "virginia" => Ok(Self::VA),
- "washington" => Ok(Self::WA),
- "west virginia" => Ok(Self::WV),
- "wisconsin" => Ok(Self::WI),
- "wyoming" => Ok(Self::WY),
- _ => Err(errors::ConnectorError::InvalidDataFormat {
- field_name: "address.state",
+ let state_abbreviation_check =
+ StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "UsStatesAbbreviation");
+
+ match state_abbreviation_check {
+ Ok(state_abbreviation) => Ok(state_abbreviation),
+ Err(_) => {
+ let binding = value.as_str().to_lowercase();
+ let state = binding.as_str();
+ match state {
+ "alabama" => Ok(Self::AL),
+ "alaska" => Ok(Self::AK),
+ "american samoa" => Ok(Self::AS),
+ "arizona" => Ok(Self::AZ),
+ "arkansas" => Ok(Self::AR),
+ "california" => Ok(Self::CA),
+ "colorado" => Ok(Self::CO),
+ "connecticut" => Ok(Self::CT),
+ "delaware" => Ok(Self::DE),
+ "district of columbia" | "columbia" => Ok(Self::DC),
+ "federated states of micronesia" | "micronesia" => Ok(Self::FM),
+ "florida" => Ok(Self::FL),
+ "georgia" => Ok(Self::GA),
+ "guam" => Ok(Self::GU),
+ "hawaii" => Ok(Self::HI),
+ "idaho" => Ok(Self::ID),
+ "illinois" => Ok(Self::IL),
+ "indiana" => Ok(Self::IN),
+ "iowa" => Ok(Self::IA),
+ "kansas" => Ok(Self::KS),
+ "kentucky" => Ok(Self::KY),
+ "louisiana" => Ok(Self::LA),
+ "maine" => Ok(Self::ME),
+ "marshall islands" => Ok(Self::MH),
+ "maryland" => Ok(Self::MD),
+ "massachusetts" => Ok(Self::MA),
+ "michigan" => Ok(Self::MI),
+ "minnesota" => Ok(Self::MN),
+ "mississippi" => Ok(Self::MS),
+ "missouri" => Ok(Self::MO),
+ "montana" => Ok(Self::MT),
+ "nebraska" => Ok(Self::NE),
+ "nevada" => Ok(Self::NV),
+ "new hampshire" => Ok(Self::NH),
+ "new jersey" => Ok(Self::NJ),
+ "new mexico" => Ok(Self::NM),
+ "new york" => Ok(Self::NY),
+ "north carolina" => Ok(Self::NC),
+ "north dakota" => Ok(Self::ND),
+ "northern mariana islands" => Ok(Self::MP),
+ "ohio" => Ok(Self::OH),
+ "oklahoma" => Ok(Self::OK),
+ "oregon" => Ok(Self::OR),
+ "palau" => Ok(Self::PW),
+ "pennsylvania" => Ok(Self::PA),
+ "puerto rico" => Ok(Self::PR),
+ "rhode island" => Ok(Self::RI),
+ "south carolina" => Ok(Self::SC),
+ "south dakota" => Ok(Self::SD),
+ "tennessee" => Ok(Self::TN),
+ "texas" => Ok(Self::TX),
+ "utah" => Ok(Self::UT),
+ "vermont" => Ok(Self::VT),
+ "virgin islands" => Ok(Self::VI),
+ "virginia" => Ok(Self::VA),
+ "washington" => Ok(Self::WA),
+ "west virginia" => Ok(Self::WV),
+ "wisconsin" => Ok(Self::WI),
+ "wyoming" => Ok(Self::WY),
+ _ => Err(errors::ConnectorError::InvalidDataFormat {
+ field_name: "address.state",
+ }
+ .into()),
+ }
}
- .into()),
}
}
}
@@ -1874,26 +1883,33 @@ impl ForeignTryFrom<String> for UsStatesAbbreviation {
impl ForeignTryFrom<String> for CanadaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
- let binding = value.as_str().to_lowercase();
- let state = binding.as_str();
- match state {
- "alberta" => Ok(Self::AB),
- "british columbia" => Ok(Self::BC),
- "manitoba" => Ok(Self::MB),
- "new brunswick" => Ok(Self::NB),
- "newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL),
- "northwest territories" => Ok(Self::NT),
- "nova scotia" => Ok(Self::NS),
- "nunavut" => Ok(Self::NU),
- "ontario" => Ok(Self::ON),
- "prince edward island" => Ok(Self::PE),
- "quebec" => Ok(Self::QC),
- "saskatchewan" => Ok(Self::SK),
- "yukon" => Ok(Self::YT),
- _ => Err(errors::ConnectorError::InvalidDataFormat {
- field_name: "address.state",
+ let state_abbreviation_check =
+ StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "CanadaStatesAbbreviation");
+ match state_abbreviation_check {
+ Ok(state_abbreviation) => Ok(state_abbreviation),
+ Err(_) => {
+ let binding = value.as_str().to_lowercase();
+ let state = binding.as_str();
+ match state {
+ "alberta" => Ok(Self::AB),
+ "british columbia" => Ok(Self::BC),
+ "manitoba" => Ok(Self::MB),
+ "new brunswick" => Ok(Self::NB),
+ "newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL),
+ "northwest territories" => Ok(Self::NT),
+ "nova scotia" => Ok(Self::NS),
+ "nunavut" => Ok(Self::NU),
+ "ontario" => Ok(Self::ON),
+ "prince edward island" => Ok(Self::PE),
+ "quebec" => Ok(Self::QC),
+ "saskatchewan" => Ok(Self::SK),
+ "yukon" => Ok(Self::YT),
+ _ => Err(errors::ConnectorError::InvalidDataFormat {
+ field_name: "address.state",
+ }
+ .into()),
+ }
}
- .into()),
}
}
}
|
2024-05-15T07:38:22Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [X] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Accept `billing.state` with 2-letter abbreviation for US and CA
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
#4647
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
### For CA test with `AB` or any other abbreviation it should pass
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \
--data-raw '{
"amount": 9040,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "shanks57",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "abc-ext.kylta@flowbird.group",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "01",
"card_exp_year": "2027",
"card_holder_name": "joseph Doe",
"card_cvc": "100",
"nick_name": "hehe"
}
},
"billing": {
"address": {
"city": "SanFrancisco",
"country": "CA",
"line1": "1562",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "K1A 0A0",
"state": "AB",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 10,
"account_name": "transaction_processing"
}
]
}'
```
### For US test with `ca` or any other abbreviation it should pass
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \
--data-raw '{
"amount": 9040,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "shanks57",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "abc-ext.kylta@flowbird.group",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "01",
"card_exp_year": "2027",
"card_holder_name": "joseph Doe",
"card_cvc": "100",
"nick_name": "hehe"
}
},
"billing": {
"address": {
"city": "SanFrancisco",
"country": "US",
"line1": "1562",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "94122",
"state": "CA",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 10,
"account_name": "transaction_processing"
}
]
}'
```
### For US/CA test with full state name it should pass
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \
--data-raw '{
"amount": 9040,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "shanks57",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "abc-ext.kylta@flowbird.group",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "01",
"card_exp_year": "2027",
"card_holder_name": "joseph Doe",
"card_cvc": "100",
"nick_name": "hehe"
}
},
"billing": {
"address": {
"city": "SanFrancisco",
"country": "US",
"line1": "1562",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 10,
"account_name": "transaction_processing"
}
]
}'
```
### For US/CA test with invalid state name or abbreviation it should fail at hyperswitch level.
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \
--data-raw '{
"amount": 9040,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "shanks57",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "abc-ext.kylta@flowbird.group",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "01",
"card_exp_year": "2027",
"card_holder_name": "joseph Doe",
"card_cvc": "100",
"nick_name": "hehe"
}
},
"billing": {
"address": {
"city": "SanFrancisco",
"country": "US",
"line1": "1562",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "94122",
"state": "random_state",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 10,
"account_name": "transaction_processing"
}
]
}'
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [X] I formatted the code `cargo +nightly fmt --all`
- [X] I addressed lints thrown by `cargo clippy`
- [X] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ff1c2ddf8b9d8f35deee1ab41c2286cc5b349271
|
### For CA test with `AB` or any other abbreviation it should pass
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \
--data-raw '{
"amount": 9040,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "shanks57",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "abc-ext.kylta@flowbird.group",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "01",
"card_exp_year": "2027",
"card_holder_name": "joseph Doe",
"card_cvc": "100",
"nick_name": "hehe"
}
},
"billing": {
"address": {
"city": "SanFrancisco",
"country": "CA",
"line1": "1562",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "K1A 0A0",
"state": "AB",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 10,
"account_name": "transaction_processing"
}
]
}'
```
### For US test with `ca` or any other abbreviation it should pass
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \
--data-raw '{
"amount": 9040,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "shanks57",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "abc-ext.kylta@flowbird.group",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "01",
"card_exp_year": "2027",
"card_holder_name": "joseph Doe",
"card_cvc": "100",
"nick_name": "hehe"
}
},
"billing": {
"address": {
"city": "SanFrancisco",
"country": "US",
"line1": "1562",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "94122",
"state": "CA",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 10,
"account_name": "transaction_processing"
}
]
}'
```
### For US/CA test with full state name it should pass
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \
--data-raw '{
"amount": 9040,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "shanks57",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "abc-ext.kylta@flowbird.group",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "01",
"card_exp_year": "2027",
"card_holder_name": "joseph Doe",
"card_cvc": "100",
"nick_name": "hehe"
}
},
"billing": {
"address": {
"city": "SanFrancisco",
"country": "US",
"line1": "1562",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 10,
"account_name": "transaction_processing"
}
]
}'
```
### For US/CA test with invalid state name or abbreviation it should fail at hyperswitch level.
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_mFmnWfEBGI9OvZdkWlkrAEcp6PBReLfXynzHIbcl0d2z4bSDvvHIsegcqrCMDDqv' \
--data-raw '{
"amount": 9040,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "shanks57",
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"email": "abc-ext.kylta@flowbird.group",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "01",
"card_exp_year": "2027",
"card_holder_name": "joseph Doe",
"card_cvc": "100",
"nick_name": "hehe"
}
},
"billing": {
"address": {
"city": "SanFrancisco",
"country": "US",
"line1": "1562",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "94122",
"state": "random_state",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"browser_info": {
"user_agent": "Mozilla\/5.0 (iPhone NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.110 Safari\/537.36",
"accept_header": "text\/html,application\/xhtml+xml,application\/xml;q=0.9,image\/webp,image\/apng,*\/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "128.0.0.1"
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 10,
"account_name": "transaction_processing"
}
]
}'
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4640
|
Bug: [REFACTOR] update api contract for payment methods update endpoint
Remove unused fields from update payment method request and update the open api spec
|
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index b7a58b3b5b6..e045cf2c42d 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -88,24 +88,6 @@ pub struct PaymentMethodUpdate {
"card_holder_name": "John Doe"}))]
pub card: Option<CardDetailUpdate>,
- /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
- #[schema(value_type = Option<CardNetwork>,example = "Visa")]
- pub card_network: Option<api_enums::CardNetwork>,
-
- /// Payment method details from locker
- #[cfg(feature = "payouts")]
- #[schema(value_type = Option<Bank>)]
- pub bank_transfer: Option<payouts::Bank>,
-
- /// Payment method details from locker
- #[cfg(feature = "payouts")]
- #[schema(value_type = Option<Wallet>)]
- pub wallet: Option<payouts::Wallet>,
-
- /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
- #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))]
- pub metadata: Option<pii::SecretSerdeValue>,
-
/// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK
#[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")]
pub client_secret: Option<String>,
diff --git a/crates/openapi/src/routes/payment_method.rs b/crates/openapi/src/routes/payment_method.rs
index 07e6cc35903..3bc593aa5b2 100644
--- a/crates/openapi/src/routes/payment_method.rs
+++ b/crates/openapi/src/routes/payment_method.rs
@@ -138,7 +138,7 @@ pub async fn payment_method_retrieve_api() {}
/// This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.
#[utoipa::path(
post,
- path = "/payment_methods/{method_id}",
+ path = "/payment_methods/{method_id}/update",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
@@ -149,7 +149,7 @@ pub async fn payment_method_retrieve_api() {}
),
tag = "Payment Methods",
operation_id = "Update a Payment method",
- security(("api_key" = []))
+ security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn payment_method_update_api() {}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 8c946630c8a..307f2dcd085 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -775,6 +775,14 @@ pub async fn update_customer_payment_method(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ if let Some(cs) = &req.client_secret {
+ let is_client_secret_expired = authenticate_pm_client_secret_and_check_expiry(cs, &pm)?;
+
+ if is_client_secret_expired {
+ return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
+ };
+ };
+
if pm.status == enums::PaymentMethodStatus::AwaitingData {
return Err(report!(errors::ApiErrorResponse::NotSupported {
message: "Payment method is awaiting data so it cannot be updated".into()
@@ -849,18 +857,15 @@ pub async fn update_customer_payment_method(
payment_method_issuer: pm.payment_method_issuer.clone(),
payment_method_issuer_code: pm.payment_method_issuer_code,
#[cfg(feature = "payouts")]
- bank_transfer: req.bank_transfer,
+ bank_transfer: None,
card: Some(updated_card_details.clone()),
#[cfg(feature = "payouts")]
- wallet: req.wallet,
- metadata: req.metadata,
+ wallet: None,
+ metadata: None,
customer_id: Some(pm.customer_id.clone()),
client_secret: pm.client_secret.clone(),
payment_method_data: None,
- card_network: req
- .card_network
- .as_ref()
- .map(|card_network| card_network.to_string()),
+ card_network: None,
};
new_pm.validate()?;
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index d9061baebb3..0c3893c4635 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -2612,13 +2612,13 @@
}
]
},
- "post": {
+ "delete": {
"tags": [
"Payment Methods"
],
- "summary": "Payment Method - Update",
- "description": "Payment Method - Update\n\nUpdate an existing payment method of a customer.\nThis API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.",
- "operationId": "Update a Payment method",
+ "summary": "Payment Method - Delete",
+ "description": "Payment Method - Delete\n\nDeletes a payment method of a customer.",
+ "operationId": "Delete a Payment method",
"parameters": [
{
"name": "method_id",
@@ -2630,23 +2630,13 @@
}
}
],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/PaymentMethodUpdate"
- }
- }
- },
- "required": true
- },
"responses": {
"200": {
- "description": "Payment Method updated",
+ "description": "Payment Method deleted",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/PaymentMethodResponse"
+ "$ref": "#/components/schemas/PaymentMethodDeleteResponse"
}
}
}
@@ -2660,14 +2650,16 @@
"api_key": []
}
]
- },
- "delete": {
+ }
+ },
+ "/payment_methods/{method_id}/update": {
+ "post": {
"tags": [
"Payment Methods"
],
- "summary": "Payment Method - Delete",
- "description": "Payment Method - Delete\n\nDeletes a payment method of a customer.",
- "operationId": "Delete a Payment method",
+ "summary": "Payment Method - Update",
+ "description": "Payment Method - Update\n\nUpdate an existing payment method of a customer.\nThis API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.",
+ "operationId": "Update a Payment method",
"parameters": [
{
"name": "method_id",
@@ -2679,13 +2671,23 @@
}
}
],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PaymentMethodUpdate"
+ }
+ }
+ },
+ "required": true
+ },
"responses": {
"200": {
- "description": "Payment Method deleted",
+ "description": "Payment Method updated",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/PaymentMethodDeleteResponse"
+ "$ref": "#/components/schemas/PaymentMethodResponse"
}
}
}
@@ -2697,6 +2699,9 @@
"security": [
{
"api_key": []
+ },
+ {
+ "publishable_key": []
}
]
}
@@ -13258,35 +13263,6 @@
],
"nullable": true
},
- "card_network": {
- "allOf": [
- {
- "$ref": "#/components/schemas/CardNetwork"
- }
- ],
- "nullable": true
- },
- "bank_transfer": {
- "allOf": [
- {
- "$ref": "#/components/schemas/Bank"
- }
- ],
- "nullable": true
- },
- "wallet": {
- "allOf": [
- {
- "$ref": "#/components/schemas/Wallet"
- }
- ],
- "nullable": true
- },
- "metadata": {
- "type": "object",
- "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.",
- "nullable": true
- },
"client_secret": {
"type": "string",
"description": "This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK",
|
2024-05-14T10:10:43Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR updates the api contract for payment methods update endpoint and removes few unused fields. This PR adds the missing client secret validation for update endpoint
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
`/payment_methods/:id/update` endpoint have to be tested
1. Create a customer
```
curl --location 'http://localhost:8080/customers' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \
--data-raw '{
"email": "guest@example.com",
"name": "new_cus",
"phone": "999999999",
"phone_country_code": "+65",
"description": "First customer",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
2. Create a payment method (use `/payment_methods` endpoint)
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "40",
"card_holder_name": "John"
},
"customer_id": "cus_a05bSJXwCoO01KZmWOdX",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

3. Update the metadata (say `expiry_year` or `nick_name`) using `/payment_methods/:id/update`
```
curl --location 'http://localhost:8080/payment_methods/pm_BuRzGWSAgkNVLRgzyfuu/update' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \
--data '{
"card": {
"nick_name": "Rock"
}
}'
```

4. Do `list_payment_methods_for_customers` and verify whether updation of metadata is successful.
5. Also test the above flow with client secret auth in SDK
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
040d85826aea88ff242f59edfcdf59b592c7c956
|
`/payment_methods/:id/update` endpoint have to be tested
1. Create a customer
```
curl --location 'http://localhost:8080/customers' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \
--data-raw '{
"email": "guest@example.com",
"name": "new_cus",
"phone": "999999999",
"phone_country_code": "+65",
"description": "First customer",
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "John",
"last_name": "Doe"
},
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
2. Create a payment method (use `/payment_methods` endpoint)
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "40",
"card_holder_name": "John"
},
"customer_id": "cus_a05bSJXwCoO01KZmWOdX",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

3. Update the metadata (say `expiry_year` or `nick_name`) using `/payment_methods/:id/update`
```
curl --location 'http://localhost:8080/payment_methods/pm_BuRzGWSAgkNVLRgzyfuu/update' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_kxFm2YwE2I8srj4W96v9C5XkZl8VputfqADhqdumTgJFLpuXpgU5I2NlTHOM3ply' \
--data '{
"card": {
"nick_name": "Rock"
}
}'
```

4. Do `list_payment_methods_for_customers` and verify whether updation of metadata is successful.
5. Also test the above flow with client secret auth in SDK
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4648
|
Bug: [FIX] address non-digit character cases in card number validation
Enforce following validations on the card number -
* non-digit characters in card number
* invalid card number length
* invalid card number (luhn failure)
If any of the above validation fails, raise an appropriate error.
|
diff --git a/Cargo.lock b/Cargo.lock
index 5ba2d0dae6d..abc265ad692 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1728,7 +1728,6 @@ version = "0.1.0"
dependencies = [
"common_utils",
"error-stack",
- "luhn",
"masking",
"router_env",
"serde",
@@ -2598,12 +2597,6 @@ dependencies = [
"subtle",
]
-[[package]]
-name = "digits_iterator"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "af83450b771231745d43edf36dc9b7813ab83be5e8cbea344ccced1a09dfebcd"
-
[[package]]
name = "displaydoc"
version = "0.2.4"
@@ -4089,15 +4082,6 @@ dependencies = [
"linked-hash-map",
]
-[[package]]
-name = "luhn"
-version = "1.0.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4d10b831402a3b10e018c8bc7f0ec3344a67d0725919cbaf393accb9baf8700b"
-dependencies = [
- "digits_iterator",
-]
-
[[package]]
name = "masking"
version = "0.1.0"
diff --git a/crates/cards/Cargo.toml b/crates/cards/Cargo.toml
index ac8a417fb99..ed2be966559 100644
--- a/crates/cards/Cargo.toml
+++ b/crates/cards/Cargo.toml
@@ -11,7 +11,6 @@ license.workspace = true
[dependencies]
error-stack = "0.4.1"
-luhn = "1.0.1"
serde = { version = "1.0.197", features = ["derive"] }
thiserror = "1.0.58"
time = "0.3.35"
diff --git a/crates/cards/src/lib.rs b/crates/cards/src/lib.rs
index 5308718826a..91cb93301a9 100644
--- a/crates/cards/src/lib.rs
+++ b/crates/cards/src/lib.rs
@@ -7,7 +7,7 @@ use masking::{PeekInterface, StrongSecret};
use serde::{de, Deserialize, Serialize};
use time::{util::days_in_year_month, Date, Duration, PrimitiveDateTime, Time};
-pub use crate::validate::{CCValError, CardNumber, CardNumberStrategy};
+pub use crate::validate::{CardNumber, CardNumberStrategy, CardNumberValidationErr};
#[derive(Serialize)]
pub struct CardSecurityCode(StrongSecret<u16>);
diff --git a/crates/cards/src/validate.rs b/crates/cards/src/validate.rs
index 5a71aaa7863..1eb07599785 100644
--- a/crates/cards/src/validate.rs
+++ b/crates/cards/src/validate.rs
@@ -6,31 +6,36 @@ use router_env::{logger, which as router_env_which, Env};
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
-#[derive(Debug, Deserialize, Serialize, Error)]
-#[error("not a valid credit card number")]
-pub struct CCValError;
+///
+/// Minimum limit of a card number will not be less than 8 by ISO standards
+///
+pub const MIN_CARD_NUMBER_LENGTH: usize = 8;
-impl From<core::convert::Infallible> for CCValError {
- fn from(_: core::convert::Infallible) -> Self {
- Self
- }
-}
+///
+/// Maximum limit of a card number will not exceed 19 by ISO standards
+///
+pub const MAX_CARD_NUMBER_LENGTH: usize = 19;
+
+#[derive(Debug, Deserialize, Serialize, Error)]
+#[error("{0}")]
+pub struct CardNumberValidationErr(&'static str);
/// Card number
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct CardNumber(StrongSecret<String, CardNumberStrategy>);
impl CardNumber {
- pub fn get_card_isin(self) -> String {
+ pub fn get_card_isin(&self) -> String {
self.0.peek().chars().take(6).collect::<String>()
}
- pub fn get_extended_card_bin(self) -> String {
+
+ pub fn get_extended_card_bin(&self) -> String {
self.0.peek().chars().take(8).collect::<String>()
}
- pub fn get_card_no(self) -> String {
+ pub fn get_card_no(&self) -> String {
self.0.peek().chars().collect::<String>()
}
- pub fn get_last4(self) -> String {
+ pub fn get_last4(&self) -> String {
self.0
.peek()
.chars()
@@ -44,9 +49,9 @@ impl CardNumber {
}
impl FromStr for CardNumber {
- type Err = CCValError;
+ type Err = CardNumberValidationErr;
- fn from_str(s: &str) -> Result<Self, Self::Err> {
+ fn from_str(card_number: &str) -> Result<Self, Self::Err> {
// Valid test cards for threedsecureio
let valid_test_cards = vec![
"4000100511112003",
@@ -59,17 +64,79 @@ impl FromStr for CardNumber {
Env::Development | Env::Sandbox => valid_test_cards,
Env::Production => vec![],
};
- if luhn::valid(s) || valid_test_cards.contains(&s) {
- let cc_no_whitespace: String = s.split_whitespace().collect();
- Ok(Self(StrongSecret::from_str(&cc_no_whitespace)?))
+
+ let card_number = card_number.split_whitespace().collect::<String>();
+
+ let is_card_valid = sanitize_card_number(&card_number)?;
+
+ if valid_test_cards.contains(&card_number.as_str()) || is_card_valid {
+ Ok(Self(StrongSecret::new(card_number)))
} else {
- Err(CCValError)
+ Err(CardNumberValidationErr("card number invalid"))
}
}
}
+pub fn sanitize_card_number(card_number: &str) -> Result<bool, CardNumberValidationErr> {
+ let is_card_number_valid = Ok(card_number)
+ .and_then(validate_card_number_chars)
+ .and_then(validate_card_number_length)
+ .map(|number| luhn(&number))?;
+
+ Ok(is_card_number_valid)
+}
+
+///
+/// # Panics
+///
+/// Never, as a single character will never be greater than 10, or `u8`
+///
+pub fn validate_card_number_chars(number: &str) -> Result<Vec<u8>, CardNumberValidationErr> {
+ let data = number.chars().try_fold(
+ Vec::with_capacity(MAX_CARD_NUMBER_LENGTH),
+ |mut data, character| {
+ data.push(
+ #[allow(clippy::expect_used)]
+ character
+ .to_digit(10)
+ .ok_or(CardNumberValidationErr(
+ "invalid character found in card number",
+ ))?
+ .try_into()
+ .expect("error while converting a single character to u8"), // safety, a single character will never be greater `u8`
+ );
+ Ok::<Vec<u8>, CardNumberValidationErr>(data)
+ },
+ )?;
+
+ Ok(data)
+}
+
+pub fn validate_card_number_length(number: Vec<u8>) -> Result<Vec<u8>, CardNumberValidationErr> {
+ if number.len() >= MIN_CARD_NUMBER_LENGTH && number.len() <= MAX_CARD_NUMBER_LENGTH {
+ Ok(number)
+ } else {
+ Err(CardNumberValidationErr("invalid card number length"))
+ }
+}
+
+#[allow(clippy::as_conversions)]
+pub fn luhn(number: &[u8]) -> bool {
+ number
+ .iter()
+ .rev()
+ .enumerate()
+ .map(|(idx, element)| {
+ ((*element * 2) / 10 + (*element * 2) % 10) * ((idx as u8) % 2)
+ + (*element) * (((idx + 1) as u8) % 2)
+ })
+ .sum::<u8>()
+ % 10
+ == 0
+}
+
impl TryFrom<String> for CardNumber {
- type Error = CCValError;
+ type Error = CardNumberValidationErr;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value)
@@ -131,12 +198,30 @@ mod tests {
);
}
+ #[test]
+ fn invalid_card_number_length() {
+ let s = "371446";
+ assert_eq!(
+ CardNumber::from_str(s).unwrap_err().to_string(),
+ "invalid card number length".to_string()
+ );
+ }
+
+ #[test]
+ fn card_number_with_non_digit_character() {
+ let s = "371446431 A";
+ assert_eq!(
+ CardNumber::from_str(s).unwrap_err().to_string(),
+ "invalid character found in card number".to_string()
+ );
+ }
+
#[test]
fn invalid_card_number() {
let s = "371446431";
assert_eq!(
CardNumber::from_str(s).unwrap_err().to_string(),
- "not a valid credit card number".to_string()
+ "card number invalid".to_string()
);
}
@@ -180,6 +265,6 @@ mod tests {
fn test_invalid_card_number_deserialization() {
let card_number = serde_json::from_str::<CardNumber>(r#""1234 5678""#);
let error_msg = card_number.unwrap_err().to_string();
- assert_eq!(error_msg, "not a valid credit card number".to_string());
+ assert_eq!(error_msg, "card number invalid".to_string());
}
}
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index 7c01a9aca76..bc8724da823 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -319,7 +319,7 @@ where
{
generate_fingerprint(
state,
- StrongSecret::new(card.card_number.clone().get_card_no()),
+ StrongSecret::new(card.card_number.get_card_no()),
StrongSecret::new(merchant_fingerprint_secret.clone()),
api_models::enums::LockerChoice::HyperswitchCardVault,
)
@@ -343,7 +343,7 @@ where
.as_ref()
.and_then(|pm_data| match pm_data {
api_models::payments::PaymentMethodData::Card(card) => {
- Some(card.card_number.clone().get_card_isin())
+ Some(card.card_number.get_card_isin())
}
_ => None,
});
@@ -355,7 +355,7 @@ where
.as_ref()
.and_then(|pm_data| match pm_data {
api_models::payments::PaymentMethodData::Card(card) => {
- Some(card.card_number.clone().get_extended_card_bin())
+ Some(card.card_number.get_extended_card_bin())
}
_ => None,
});
@@ -464,7 +464,7 @@ pub async fn generate_payment_fingerprint(
{
generate_fingerprint(
state,
- StrongSecret::new(card.card_number.clone().get_card_no()),
+ StrongSecret::new(card.card_number.get_card_no()),
StrongSecret::new(merchant_fingerprint_secret),
api_models::enums::LockerChoice::HyperswitchCardVault,
)
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index d3870a9e598..f7667baefa1 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -427,7 +427,7 @@ pub async fn add_payment_method_data(
pm_resp.payment_method_id.clone_from(&pm_id);
pm_resp.client_secret = Some(client_secret.clone());
- let card_isin = card.card_number.clone().get_card_isin();
+ let card_isin = card.card_number.get_card_isin();
let card_info = db
.get_card_info(card_isin.as_str())
@@ -439,7 +439,7 @@ pub async fn add_payment_method_data(
issuer_country: card_info
.as_ref()
.and_then(|ci| ci.card_issuing_country.clone()),
- last4_digits: Some(card.card_number.clone().get_last4()),
+ last4_digits: Some(card.card_number.get_last4()),
expiry_month: Some(card.card_exp_month),
expiry_year: Some(card.card_exp_year),
nick_name: card.nick_name,
@@ -644,7 +644,7 @@ pub async fn add_payment_method(
let updated_card = Some(api::CardDetailFromLocker {
scheme: None,
- last4_digits: Some(card.card_number.clone().get_last4()),
+ last4_digits: Some(card.card_number.get_last4()),
issuer_country: None,
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
@@ -894,7 +894,7 @@ pub async fn update_customer_payment_method(
// Construct new updated card object. Consider a field if passed in request or else populate it with the existing value from existing_card_data
let updated_card = Some(api::CardDetailFromLocker {
scheme: existing_card_data.scheme,
- last4_digits: Some(card_data_from_locker.card_number.clone().get_last4()),
+ last4_digits: Some(card_data_from_locker.card_number.get_last4()),
issuer_country: existing_card_data.issuer_country,
card_number: existing_card_data.card_number,
expiry_month: card_update
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 009e9e54467..08e87b47f91 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -339,7 +339,7 @@ pub fn mk_add_card_response_hs(
merchant_id: &str,
) -> api::PaymentMethodResponse {
let card_number = card.card_number.clone();
- let last4_digits = card_number.clone().get_last4();
+ let last4_digits = card_number.get_last4();
let card_isin = card_number.get_card_isin();
let card = api::CardDetailFromLocker {
@@ -550,13 +550,13 @@ pub fn get_card_detail(
response: Card,
) -> CustomResult<api::CardDetailFromLocker, errors::VaultError> {
let card_number = response.card_number;
- let mut last4_digits = card_number.peek().to_owned();
+ let last4_digits = card_number.clone().get_last4();
//fetch form card bin
let card_detail = api::CardDetailFromLocker {
scheme: pm.scheme.to_owned(),
issuer_country: pm.issuer_country.clone(),
- last4_digits: Some(last4_digits.split_off(last4_digits.len() - 4)),
+ last4_digits: Some(last4_digits),
card_number: Some(card_number),
expiry_month: Some(response.card_exp_month),
expiry_year: Some(response.card_exp_year),
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 38acf574a7c..6f3dd1d33df 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3710,7 +3710,7 @@ pub async fn get_additional_payment_data(
) -> api_models::payments::AdditionalPaymentData {
match pm_data {
api_models::payments::PaymentMethodData::Card(card_data) => {
- let card_isin = Some(card_data.card_number.clone().get_card_isin());
+ 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).as_str(),
@@ -3719,11 +3719,11 @@ pub async fn get_additional_payment_data(
let card_extended_bin = match enable_extended_bin {
Some(config) if config.config == "true" => {
- Some(card_data.card_number.clone().get_extended_card_bin())
+ Some(card_data.card_number.get_extended_card_bin())
}
_ => None,
};
- let last4 = Some(card_data.card_number.clone().get_last4());
+ let last4 = Some(card_data.card_number.get_last4());
if card_data.card_issuer.is_some()
&& card_data.card_network.is_some()
&& card_data.card_type.is_some()
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 081dac14df0..f5a4265a9fb 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -470,7 +470,7 @@ where
let updated_card = Some(CardDetailFromLocker {
scheme: None,
- last4_digits: Some(card.card_number.clone().get_last4()),
+ last4_digits: Some(card.card_number.get_last4()),
issuer_country: None,
card_number: Some(card.card_number),
expiry_month: Some(card.card_exp_month),
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index c22f74bab4a..e8baba0d126 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -371,9 +371,7 @@ pub async fn save_payout_data_to_locker(
metadata_update.as_ref(),
) {
// Fetch card info from db
- let card_isin = card_details
- .as_ref()
- .map(|c| c.card_number.clone().get_card_isin());
+ let card_isin = card_details.as_ref().map(|c| c.card_number.get_card_isin());
let mut payment_method = api::PaymentMethodCreate {
payment_method: Some(api_enums::PaymentMethod::foreign_from(
@@ -410,9 +408,7 @@ pub async fn save_payout_data_to_locker(
card_info.card_network.clone().map(|cn| cn.to_string());
api::payment_methods::PaymentMethodsData::Card(
api::payment_methods::CardDetailsPaymentMethod {
- last4_digits: card_details
- .as_ref()
- .map(|c| c.card_number.clone().get_last4()),
+ last4_digits: card_details.as_ref().map(|c| c.card_number.get_last4()),
issuer_country: card_info.card_issuing_country,
expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()),
expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()),
@@ -432,9 +428,7 @@ pub async fn save_payout_data_to_locker(
.unwrap_or_else(|| {
api::payment_methods::PaymentMethodsData::Card(
api::payment_methods::CardDetailsPaymentMethod {
- last4_digits: card_details
- .as_ref()
- .map(|c| c.card_number.clone().get_last4()),
+ last4_digits: card_details.as_ref().map(|c| c.card_number.get_last4()),
issuer_country: None,
expiry_month: card_details.as_ref().map(|c| c.card_exp_month.clone()),
expiry_year: card_details.as_ref().map(|c| c.card_exp_year.clone()),
|
2024-05-15T09:49:54Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR enforces following validations on the card number -
* non-digit characters in card number
* invalid card number length
* invalid card number (luhn failure)
If any of the above validation fails, appropriate error is raised.
This PR also fixes the failing CI check.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Unit tests -

2. Invalid card number length -
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "1234567",
"card_exp_month": "10",
"card_exp_year": "26",
"card_holder_name": "Chethan"
},
"customer_id": "cus_Cbszk87dvhH7EuBp2ZoB",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

3. Non-digit character in card number
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "411111111111111🦀",
"card_exp_month": "10",
"card_exp_year": "26",
"card_holder_name": "Chethan"
},
"customer_id": "cus_Cbszk87dvhH7EuBp2ZoB",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

4. Invalid card number (Failing luhn check):
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "411111111111112",
"card_exp_month": "10",
"card_exp_year": "26",
"card_holder_name": "Chethan"
},
"customer_id": "cus_Cbszk87dvhH7EuBp2ZoB",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [x] I added unit tests for my changes where possible
|
0d45f854a2cc18cc421a3d449a6dc2c830ef9dd5
|
1. Unit tests -

2. Invalid card number length -
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "1234567",
"card_exp_month": "10",
"card_exp_year": "26",
"card_holder_name": "Chethan"
},
"customer_id": "cus_Cbszk87dvhH7EuBp2ZoB",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

3. Non-digit character in card number
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "411111111111111🦀",
"card_exp_month": "10",
"card_exp_year": "26",
"card_holder_name": "Chethan"
},
"customer_id": "cus_Cbszk87dvhH7EuBp2ZoB",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

4. Invalid card number (Failing luhn check):
```
curl --location 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ekfmmqSYoY0bvjOGGO0Pe5CQdP9oS0ycImpRG78tjNTrgp03HGxvDAhHCrmHrYoO' \
--data '{
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "411111111111112",
"card_exp_month": "10",
"card_exp_year": "26",
"card_holder_name": "Chethan"
},
"customer_id": "cus_Cbszk87dvhH7EuBp2ZoB",
"metadata": {
"city": "NY",
"unit": "245"
}
}'
```

|
|
juspay/hyperswitch
|
juspay__hyperswitch-4618
|
Bug: [FEAT] add an API to toggle KV for all the merchants
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 2e288140a9f..12d9832ada6 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -829,6 +829,22 @@ pub struct ToggleKVRequest {
pub kv_enabled: bool,
}
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct ToggleAllKVRequest {
+ /// Status of KV for the specific merchant
+ #[schema(example = true)]
+ pub kv_enabled: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+pub struct ToggleAllKVResponse {
+ ///Total number of updated merchants
+ #[schema(example = 20)]
+ pub total_updated: usize,
+ /// Status of KV for the specific merchant
+ #[schema(example = true)]
+ pub kv_enabled: bool,
+}
#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct MerchantConnectorDetailsWrap {
/// Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info in this field. And do not send the string "null".
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index c9ae775fed8..9c26576e77b 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -60,6 +60,8 @@ impl_misc_api_event_type!(
RevokeApiKeyResponse,
ToggleKVResponse,
ToggleKVRequest,
+ ToggleAllKVRequest,
+ ToggleAllKVResponse,
MerchantAccountDeleteResponse,
MerchantAccountUpdate,
CardInfoResponse,
diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs
index 1d4eef75206..dd2f284305b 100644
--- a/crates/diesel_models/src/query/merchant_account.rs
+++ b/crates/diesel_models/src/query/merchant_account.rs
@@ -123,4 +123,16 @@ impl MerchantAccount {
)
.await
}
+
+ pub async fn update_all_merchant_accounts(
+ conn: &PgPooledConn,
+ merchant_account: MerchantAccountUpdateInternal,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::merchant_id.ne_all(vec![""]),
+ merchant_account,
+ )
+ .await
+ }
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 288de66de07..af707087ce3 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1420,6 +1420,36 @@ pub async fn kv_for_merchant(
))
}
+pub async fn toggle_kv_for_all_merchants(
+ state: AppState,
+ 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: AppState,
merchant_id: String,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index bfe0592fd3d..88579892d2f 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -828,6 +828,15 @@ impl MerchantAccountInterface for KafkaStore {
.await
}
+ async fn update_all_merchant_account(
+ &self,
+ merchant_account: storage::MerchantAccountUpdate,
+ ) -> CustomResult<usize, errors::StorageError> {
+ self.diesel_store
+ .update_all_merchant_account(merchant_account)
+ .await
+ }
+
async fn find_merchant_account_by_publishable_key(
&self,
publishable_key: &str,
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index 08d0c279047..c323ca4abb1 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -2,6 +2,7 @@
use std::collections::HashMap;
use common_utils::ext_traits::AsyncExt;
+use diesel_models::MerchantAccountUpdateInternal;
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
@@ -40,6 +41,11 @@ where
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError>;
+ async fn update_all_merchant_account(
+ &self,
+ merchant_account: storage::MerchantAccountUpdate,
+ ) -> CustomResult<usize, errors::StorageError>;
+
async fn update_merchant(
&self,
this: domain::MerchantAccount,
@@ -354,6 +360,38 @@ impl MerchantAccountInterface for Store {
Ok(merchant_accounts)
}
+
+ async fn update_all_merchant_account(
+ &self,
+ merchant_account: storage::MerchantAccountUpdate,
+ ) -> CustomResult<usize, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+
+ let db_func = || async {
+ storage::MerchantAccount::update_all_merchant_accounts(
+ &conn,
+ MerchantAccountUpdateInternal::from(merchant_account),
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ };
+
+ let total;
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ let ma = db_func().await?;
+ total = ma.len();
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ let ma = db_func().await?;
+ publish_and_redact_all_merchant_account_cache(self, &ma).await?;
+ total = ma.len();
+ }
+
+ Ok(total)
+ }
}
#[async_trait::async_trait]
@@ -433,6 +471,13 @@ impl MerchantAccountInterface for MockDb {
Err(errors::StorageError::MockDbError)?
}
+ async fn update_all_merchant_account(
+ &self,
+ _merchant_account_update: storage::MerchantAccountUpdate,
+ ) -> CustomResult<usize, errors::StorageError> {
+ Err(errors::StorageError::MockDbError)?
+ }
+
async fn delete_merchant_account_by_merchant_id(
&self,
_merchant_id: &str,
@@ -477,3 +522,22 @@ async fn publish_and_redact_merchant_account_cache(
super::cache::publish_into_redact_channel(store, cache_keys).await?;
Ok(())
}
+
+#[cfg(feature = "accounts_cache")]
+async fn publish_and_redact_all_merchant_account_cache(
+ store: &dyn super::StorageInterface,
+ merchant_accounts: &[storage::MerchantAccount],
+) -> CustomResult<(), errors::StorageError> {
+ let merchant_ids = merchant_accounts.iter().map(|m| m.merchant_id.clone());
+ let publishable_keys = merchant_accounts
+ .iter()
+ .filter_map(|m| m.publishable_key.clone());
+
+ let cache_keys: Vec<CacheKind<'_>> = merchant_ids
+ .chain(publishable_keys)
+ .map(|s| CacheKind::Accounts(s.into()))
+ .collect();
+
+ super::cache::publish_into_redact_channel(store, cache_keys).await?;
+ Ok(())
+}
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index d9cadf002c1..2d1b77460a5 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -458,6 +458,31 @@ pub async fn merchant_account_toggle_kv(
)
.await
}
+
+/// Merchant Account - Toggle KV
+///
+/// Toggle KV mode for all Merchant Accounts
+#[instrument(skip_all)]
+pub async fn merchant_account_toggle_all_kv(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<admin::ToggleAllKVRequest>,
+) -> HttpResponse {
+ let flow = Flow::ConfigKeyUpdate;
+ let payload = json_payload.into_inner();
+
+ api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, _, payload, _| toggle_kv_for_all_merchants(state, payload.kv_enabled),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ )
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::BusinessProfileCreate))]
pub async fn business_profile_create(
state: web::Data<AppState>,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 21cc994381e..f4eded24be6 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -866,6 +866,7 @@ impl MerchantAccount {
.route(web::post().to(merchant_account_toggle_kv))
.route(web::get().to(merchant_account_kv_status)),
)
+ .service(web::resource("/kv").route(web::post().to(merchant_account_toggle_all_kv)))
.service(
web::resource("/{id}")
.route(web::get().to(retrieve_merchant_account))
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index fcbd97d5cb1..8fc3ebb721f 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -3,7 +3,8 @@ pub use api_models::admin::{
MerchantAccountDeleteResponse, MerchantAccountResponse, MerchantAccountUpdate,
MerchantConnectorCreate, MerchantConnectorDeleteResponse, MerchantConnectorDetails,
MerchantConnectorDetailsWrap, MerchantConnectorId, MerchantConnectorResponse, MerchantDetails,
- MerchantId, PaymentMethodsEnabled, ToggleKVRequest, ToggleKVResponse, WebhookDetails,
+ MerchantId, PaymentMethodsEnabled, ToggleAllKVRequest, ToggleAllKVResponse, ToggleKVRequest,
+ ToggleKVResponse, WebhookDetails,
};
use common_utils::ext_traits::{Encode, ValueExt};
use error_stack::ResultExt;
|
2024-05-09T07:02:01Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] New feature
## Description
<!-- Describe your changes in detail -->
Add an API to toggle KV for all merchants
### Additional Changes
- [x] This PR modifies the API contract
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Add an API to toggle KV for all merchants
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
- Enable KV for all merchants
```bash
curl --location 'http://localhost:8080/accounts/kv' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"kv_enabled": true
}'
```
Check if any merchant_account has `postgres_only`.
```sql
SELECT storage_scheme from merchant_account where storage_scheme='postgres_only'
```
It should return 0 rows
-Disable KV for all merchants
```bash
curl --location 'http://localhost:8080/accounts/kv' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"kv_enabled": false
}'
```
Check if any merchant_account has `redis_kv`
```sql
SELECT storage_scheme from merchant_account where storage_scheme='redis_kv'
```
It should return 0 rows
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
|
5e84855496d80959c1fc43c1efc9bb2a4d802d5a
|
- Enable KV for all merchants
```bash
curl --location 'http://localhost:8080/accounts/kv' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"kv_enabled": true
}'
```
Check if any merchant_account has `postgres_only`.
```sql
SELECT storage_scheme from merchant_account where storage_scheme='postgres_only'
```
It should return 0 rows
-Disable KV for all merchants
```bash
curl --location 'http://localhost:8080/accounts/kv' \
--header 'Content-Type: application/json' \
--header 'api-key: test_admin' \
--data '{
"kv_enabled": false
}'
```
Check if any merchant_account has `redis_kv`
```sql
SELECT storage_scheme from merchant_account where storage_scheme='redis_kv'
```
It should return 0 rows
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4612
|
Bug: [BUG] : QR Code Image Generation Failure
### Bug Description
The QR code generation function, 'new_from_data', is not working as expected. It is returning an empty string instead of the encoded image URL , leading to the failure of PIX QR code generation.
### Expected Behavior
Fix QR code into image generation function
### Actual Behavior
Generate QR code image URL
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
### Context For The Bug

### Environment
Are you using hyperswitch hosted version? Yes/No
If yes, please provide the value of the `x-request-id` response header to help us debug your issue.
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution:
2. Rust version (output of `rustc --version`): ``
3. App version (output of `cargo r --features vergen -- --version`): ``
### Have you spent some time checking if this bug has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
None
|
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index 87cd95364d5..059278a1b1c 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -185,7 +185,7 @@ impl QrImage {
let image_data_source = format!(
"{},{}",
consts::QR_IMAGE_DATA_SOURCE_STRING,
- consts::BASE64_ENGINE.encode(image_bytes.get_ref().get_ref())
+ consts::BASE64_ENGINE.encode(image_bytes.buffer())
);
Ok(Self {
data: image_data_source,
|
2024-05-10T06:44:48Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The QR code generation function, 'new_from_data', is not working as expected. It is returning an empty string instead of the encoded image URL , leading to the failure of PIX QR code generation.
Earlier
<img width="339" alt="Screenshot 2024-05-10 at 12 18 52 PM" src="https://github.com/juspay/hyperswitch/assets/131388445/b9d78dd5-ec62-4a79-9587-b6b359f9d122">
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. Create a PIX payment with Adyen. In response we must get a valid base64 encoded QR Code data
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Q1XJ407yuiyLeM1BwpMrGJos9JzwwHHztSVIypS3zsMkIYQqf1W7HA2NZhFpZyL4' \
--data-raw '{
"amount": 6540,
"currency": "BRL",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://hs-payments-test.netlify.app/payments/",
"payment_method": "bank_transfer",
"payment_method_type": "pix",
"payment_method_data": {
"bank_transfer": {
"pix": {}
}
}
}'
```
Response
```
{
"payment_id": "pay_pES0gbesSS9LXecyuhd6",
"merchant_id": "merchant_1715279316",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "adyen",
"client_secret": "pay_pES0gbesSS9LXecyuhd6_secret_Q3ma2x34cOKMp9h6OTRm",
"created": "2024-05-10T06:20:26.315Z",
"currency": "BRL",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_transfer",
"payment_method_data": {
"bank_transfer": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://hs-payments-test.netlify.app/payments/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "qr_code_information",
"image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg**********",
"display_to_timestamp": 1715325628000,
"qr_code_url": "https://test.adyen.com/hpp/generateQRCodeImage.shtml?url=*********"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "pix",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1715322026,
"expires": 1715325626,
"secret": "epk_eea7fdbbbeb645d28e1e0bd4a0905631"
},
"manual_retry_allowed": null,
"connector_transaction_id": "MQ9886QMBZNKWPT5",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "MQ9886QMBZNKWPT5",
"payment_link": null,
"profile_id": "pro_10opqc1gzSgRKhUq7O1H",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_mbTo85IbSKeh3xAG84jr",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-10T06:35:26.315Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-10T06:20:28.525Z"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ecdac814d802cfc260a956a77a99f22c5d899ba3
|
1. Create a PIX payment with Adyen. In response we must get a valid base64 encoded QR Code data
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_Q1XJ407yuiyLeM1BwpMrGJos9JzwwHHztSVIypS3zsMkIYQqf1W7HA2NZhFpZyL4' \
--data-raw '{
"amount": 6540,
"currency": "BRL",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://hs-payments-test.netlify.app/payments/",
"payment_method": "bank_transfer",
"payment_method_type": "pix",
"payment_method_data": {
"bank_transfer": {
"pix": {}
}
}
}'
```
Response
```
{
"payment_id": "pay_pES0gbesSS9LXecyuhd6",
"merchant_id": "merchant_1715279316",
"status": "requires_customer_action",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 6540,
"amount_received": null,
"connector": "adyen",
"client_secret": "pay_pES0gbesSS9LXecyuhd6_secret_Q3ma2x34cOKMp9h6OTRm",
"created": "2024-05-10T06:20:26.315Z",
"currency": "BRL",
"customer_id": "StripeCustomer",
"customer": {
"id": "StripeCustomer",
"name": "John Doe",
"email": "guest@example.com",
"phone": "999999999",
"phone_country_code": "+1"
},
"description": "Its my first payment request",
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "bank_transfer",
"payment_method_data": {
"bank_transfer": {},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"return_url": "https://hs-payments-test.netlify.app/payments/",
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": {
"type": "qr_code_information",
"image_data_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg**********",
"display_to_timestamp": 1715325628000,
"qr_code_url": "https://test.adyen.com/hpp/generateQRCodeImage.shtml?url=*********"
},
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "pix",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "StripeCustomer",
"created_at": 1715322026,
"expires": 1715325626,
"secret": "epk_eea7fdbbbeb645d28e1e0bd4a0905631"
},
"manual_retry_allowed": null,
"connector_transaction_id": "MQ9886QMBZNKWPT5",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "MQ9886QMBZNKWPT5",
"payment_link": null,
"profile_id": "pro_10opqc1gzSgRKhUq7O1H",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_mbTo85IbSKeh3xAG84jr",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-10T06:35:26.315Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-10T06:20:28.525Z"
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4627
|
Bug: ci: use git diff to add `M-database-changes` label for pr that contains migrations and schema changes
Use git diff to add `M-database-changes` label for pr that contains migrations and schema changes. This helps to identify the pr that has db migrations.
|
2024-05-13T07:00:48Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
This ps uses git diff to add `M-database-changes` label for pr that contains migrations and schema changes.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
We can see that `M-database-changes` was added for on of the below commits which contained migration changes.
<img width="1050" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/959f47f3-622b-40ef-a28d-2ba76dd51d9f">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
7085a46271791ca3f1c7b86afa7c8b199b93c0cd
|
We can see that `M-database-changes` was added for on of the below commits which contained migration changes.
<img width="1050" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/959f47f3-622b-40ef-a28d-2ba76dd51d9f">
|
||
juspay/hyperswitch
|
juspay__hyperswitch-4606
|
Bug: fix: Fix bugs caused by token only flows
- Password without special characters is not throwing parsing failed error.
- Signup is not populating the `last_password_modified_at`.
- Verify email is blacklisting all email tokens.
- If the SPT token time is less than JWT time, some SPTs issued after that blacklist are not working.
|
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index c40d284ee3a..610d8ef8b1f 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -70,7 +70,9 @@ pub const LOCKER_REDIS_EXPIRY_SECONDS: u32 = 60 * 15; // 15 minutes
pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days
-pub const SINGLE_PURPOSE_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
+// This should be one day, but it is causing issue while checking token in blacklist.
+// TODO: This should be fixed in future.
+pub const SINGLE_PURPOSE_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days
pub const JWT_TOKEN_COOKIE_NAME: &str = "login_token";
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 83cdd1d318b..bfe01863550 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1421,9 +1421,13 @@ pub async fn verify_email_token_only_flow(
.change_context(UserErrors::InternalServerError)?
.into();
- let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
- .await
- .map_err(|e| logger::error!(?e));
+ if matches!(user_token.origin, domain::Origin::VerifyEmail)
+ || matches!(user_token.origin, domain::Origin::MagicLink)
+ {
+ let _ = auth::blacklist::insert_email_token_in_blacklist(&state, &token)
+ .await
+ .map_err(|e| logger::error!(?e));
+ }
let current_flow =
domain::CurrentFlow::new(user_token.origin, domain::SPTFlow::VerifyEmail.into())?;
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 45f5d74d6f6..051e6ccf38e 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -1,4 +1,8 @@
-use std::{collections::HashSet, ops, str::FromStr};
+use std::{
+ collections::HashSet,
+ ops::{self, Not},
+ str::FromStr,
+};
use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
@@ -172,8 +176,7 @@ impl UserPassword {
has_upper_case = has_upper_case || c.is_uppercase();
has_lower_case = has_lower_case || c.is_lowercase();
has_numeric_value = has_numeric_value || c.is_numeric();
- has_special_character =
- has_special_character || !(c.is_alphanumeric() && c.is_whitespace());
+ has_special_character = has_special_character || !c.is_alphanumeric();
has_whitespace = has_whitespace || c.is_whitespace();
}
@@ -510,6 +513,7 @@ pub struct NewUser {
email: UserEmail,
password: UserPassword,
new_merchant: NewUserMerchant,
+ is_temporary_password: bool,
}
impl NewUser {
@@ -614,12 +618,20 @@ impl TryFrom<NewUser> for storage_user::UserNew {
fn try_from(value: NewUser) -> UserResult<Self> {
let hashed_password = password::generate_password_hash(value.password.get_secret())?;
+ let now = common_utils::date_time::now();
Ok(Self {
user_id: value.get_user_id(),
name: value.get_name(),
email: value.get_email().into_inner(),
password: hashed_password,
- ..Default::default()
+ is_verified: false,
+ created_at: Some(now),
+ last_modified_at: Some(now),
+ preferred_merchant_id: None,
+ totp_status: TotpStatus::NotSet,
+ totp_secret: None,
+ totp_recovery_codes: None,
+ last_password_modified_at: value.is_temporary_password.not().then_some(now),
})
}
}
@@ -640,6 +652,7 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser {
password,
user_id,
new_merchant,
+ is_temporary_password: false,
})
}
}
@@ -660,6 +673,7 @@ impl TryFrom<user_api::SignUpRequest> for NewUser {
email,
password,
new_merchant,
+ is_temporary_password: false,
})
}
}
@@ -680,6 +694,7 @@ impl TryFrom<user_api::ConnectAccountRequest> for NewUser {
email,
password,
new_merchant,
+ is_temporary_password: true,
})
}
}
@@ -700,6 +715,7 @@ impl TryFrom<user_api::CreateInternalUserRequest> for NewUser {
email,
password,
new_merchant,
+ is_temporary_password: false,
})
}
}
@@ -717,6 +733,9 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser {
email: user.0.email.clone().try_into()?,
password: UserPassword::new_password_without_validation(user.0.password)?,
new_merchant,
+ // This is true because we are not creating a user with this request. And if it is set
+ // to false, last_password_modified_at will be overwritten if this user is inserted.
+ is_temporary_password: true,
})
}
}
@@ -736,6 +755,7 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser {
email,
password,
new_merchant,
+ is_temporary_password: true,
})
}
}
|
2024-05-09T12:46:43Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR fixes the following bugs:
- Password without special characters is not throwing parsing failed error.
- Signup is not populating the `last_password_modified_at`.
- Verify email is blacklisting all email tokens.
- If the SPT token time is less than JWT time, some SPTs issued after that blacklist are not working.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #4606.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
> [!NOTE]
> This only works when email feature flag is disabled.
- To check the password validation
```
curl --location 'http://localhost:8080/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "unregistered email",
"password": "password"
}'
```
- If the password is valid, then you will get the following response
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2MwOTBiMDYtYWY2ZS00MDk0LTgwYzktMWEzOTlkOTQ2MjBjIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwiZXhwIjoxNzE1MzMzNTE1fQ.v3fBLoTdf01RDWs24ukphvNFuVQ9AsqaVBuUfjviEuQ",
"token_type": "totp"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f386f423c0e5fac55a24756d7ee7a3ce1c20fb13
|
> [!NOTE]
> This only works when email feature flag is disabled.
- To check the password validation
```
curl --location 'http://localhost:8080/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "unregistered email",
"password": "password"
}'
```
- If the password is valid, then you will get the following response
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiM2MwOTBiMDYtYWY2ZS00MDk0LTgwYzktMWEzOTlkOTQ2MjBjIiwicHVycG9zZSI6InRvdHAiLCJvcmlnaW4iOiJzaWduX2luIiwiZXhwIjoxNzE1MzMzNTE1fQ.v3fBLoTdf01RDWs24ukphvNFuVQ9AsqaVBuUfjviEuQ",
"token_type": "totp"
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4659
|
Bug: [FEATURE] add support for collecting and refunding charges on payments
### Feature Description
Charges can be collected on payments for collecting fees for resellers. Adyen, Stripe allows creating charges on payment intents using their marketplace platform.
The support for collecting charges on payments and refunding charges needs to be added.
### Possible Implementation
#### Payments
- A new field `charges` is introduced to read charge specific details
- Charge details are sent to the connector where request is transformed and sent
- `charge_id` is returned by the connector which is persisted in `payment_attempt` table. This can later be used for refunding charges
#### Refunds
- A new field `charges` is introduced to read charge id and refund options
- `charges` created during payments is fetched and used as a reference
- Charge details are sent to the connector where request is transformed and sent
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/connector-template/transformers.rs b/connector-template/transformers.rs
index 40e3c2a3665..fb08c1026f2 100644
--- a/connector-template/transformers.rs
+++ b/connector-template/transformers.rs
@@ -128,7 +128,8 @@ impl<F,T> TryFrom<types::ResponseRouterData<F, {{project-name | downcase | pasca
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
-incremental_authorization_allowed: None,
+ incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 8c945a03034..59a85841212 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -600,6 +600,50 @@ pub fn convert_authentication_connector(connector_name: &str) -> Option<Authenti
AuthenticationConnectors::from_str(connector_name).ok()
}
+#[derive(
+ Clone,
+ Debug,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ ToSchema,
+ Hash,
+)]
+pub enum PaymentChargeType {
+ #[serde(untagged)]
+ Stripe(StripeChargeType),
+}
+
+impl Default for PaymentChargeType {
+ fn default() -> Self {
+ Self::Stripe(StripeChargeType::default())
+ }
+}
+
+#[derive(
+ Clone,
+ Debug,
+ Default,
+ Hash,
+ Eq,
+ PartialEq,
+ ToSchema,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+)]
+#[serde(rename_all = "lowercase")]
+#[strum(serialize_all = "lowercase")]
+pub enum StripeChargeType {
+ #[default]
+ Direct,
+ Destination,
+}
+
#[cfg(feature = "frm")]
pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> {
FrmConnectors::from_str(connector_name).ok()
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 60952ee501f..f0ce3839fce 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -474,6 +474,23 @@ pub struct PaymentsRequest {
/// Details required for recurring payment
pub recurring_details: Option<RecurringDetails>,
+
+ /// Fee information to be charged on the payment being collected
+ pub charges: Option<PaymentChargeRequest>,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct PaymentChargeRequest {
+ /// Stripe's charge type
+ #[schema(value_type = PaymentChargeType, example = "direct")]
+ pub charge_type: api_enums::PaymentChargeType,
+
+ /// Platform fees to be collected on the payment
+ pub fees: i64,
+
+ /// Identifier for the reseller's account to send the funds to
+ pub transfer_account_id: String,
}
impl PaymentsRequest {
@@ -3426,11 +3443,30 @@ pub struct PaymentsResponse {
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub updated: Option<PrimitiveDateTime>,
+ /// Fee information to be charged on the payment being collected
+ pub charges: Option<PaymentChargeResponse>,
+
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM.
#[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)]
pub frm_metadata: Option<pii::SecretSerdeValue>,
}
+#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)]
+pub struct PaymentChargeResponse {
+ /// Identifier for charge created for the payment
+ pub charge_id: Option<String>,
+
+ /// Type of charge (connector specific)
+ #[schema(value_type = PaymentChargeType, example = "direct")]
+ pub charge_type: api_enums::PaymentChargeType,
+
+ /// Platform fees collected on the payment
+ pub application_fees: i64,
+
+ /// Identifier for the reseller's account where the funds were transferred
+ pub transfer_account_id: String,
+}
+
#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)]
pub struct ExternalAuthenticationDetailsResponse {
/// Authentication Type - Challenge / Frictionless
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index 369aa0a6602..881cc3912ec 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use common_utils::pii;
+pub use common_utils::types::ChargeRefunds;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
@@ -53,6 +54,10 @@ pub struct RefundRequest {
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorDetailsWrap>)]
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
+
+ /// Charge specific fields for controlling the revert of funds from either platform or connected account
+ #[schema(value_type = Option<ChargeRefunds>)]
+ pub charges: Option<ChargeRefunds>,
}
#[derive(Default, Debug, Clone, Deserialize)]
@@ -137,6 +142,9 @@ pub struct RefundResponse {
pub profile_id: Option<String>,
/// The merchant_connector_id of the processor through which this payment went through
pub merchant_connector_id: Option<String>,
+ /// Charge specific fields for controlling the revert of funds from either platform or connected account
+ #[schema(value_type = Option<ChargeRefunds>)]
+ pub charges: Option<ChargeRefunds>,
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
@@ -168,7 +176,7 @@ pub struct RefundListRequest {
pub refund_status: Option<Vec<enums::RefundStatus>>,
}
-#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
+#[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)]
pub struct RefundListResponse {
/// The number of refunds included in the list
pub count: usize,
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index e6fd27da31a..ff64d6517c7 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -39,8 +39,8 @@ thiserror = "1.0.58"
time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] }
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"], optional = true }
semver = { version = "1.0.22", features = ["serde"] }
-uuid = { version = "1.8.0", features = ["v7"] }
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] }
+uuid = { version = "1.8.0", features = ["v7"] }
# First party crates
common_enums = { version = "0.1.0", path = "../common_enums" }
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index 6574d1f1af4..d9a7aef3f57 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -17,7 +17,7 @@ use diesel::{
};
use error_stack::{report, ResultExt};
use semver::Version;
-use serde::{de::Visitor, Deserialize, Deserializer};
+use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
use utoipa::ToSchema;
use crate::{
@@ -25,7 +25,7 @@ use crate::{
errors::{CustomResult, ParsingError, PercentageError},
};
/// Represents Percentage Value between 0 and 100 both inclusive
-#[derive(Clone, Default, Debug, PartialEq, serde::Serialize)]
+#[derive(Clone, Default, Debug, PartialEq, Serialize)]
pub struct Percentage<const PRECISION: u8> {
// this value will range from 0 to 100, decimal length defined by precision macro
/// Percentage value ranging between 0 and 100
@@ -160,7 +160,7 @@ impl<'de, const PRECISION: u8> Deserialize<'de> for Percentage<PRECISION> {
}
/// represents surcharge type and value
-#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
+#[derive(Clone, Debug, PartialEq, Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
pub enum Surcharge {
/// Fixed Surcharge value
@@ -172,7 +172,7 @@ pub enum Surcharge {
/// This struct lets us represent a semantic version type
#[derive(Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, Ord, PartialOrd)]
#[diesel(sql_type = Jsonb)]
-#[derive(serde::Serialize, serde::Deserialize)]
+#[derive(Serialize, serde::Deserialize)]
pub struct SemanticVersion(#[serde(with = "Version")] Version);
impl SemanticVersion {
@@ -226,6 +226,48 @@ where
}
}
+#[derive(
+ Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
+)]
+#[diesel(sql_type = Jsonb)]
+/// Charge object for refunds
+pub struct ChargeRefunds {
+ /// Identifier for charge created for the payment
+ pub charge_id: String,
+
+ /// Toggle for reverting the application fee that was collected for the payment.
+ /// If set to false, the funds are pulled from the destination account.
+ pub revert_platform_fee: Option<bool>,
+
+ /// Toggle for reverting the transfer that was made during the charge.
+ /// If set to false, the funds are pulled from the main platform's account.
+ pub revert_transfer: Option<bool>,
+}
+
+impl<DB: Backend> FromSql<Jsonb, DB> for ChargeRefunds
+where
+ serde_json::Value: FromSql<Jsonb, DB>,
+{
+ fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
+ let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?;
+ Ok(serde_json::from_value(value)?)
+ }
+}
+
+impl ToSql<Jsonb, diesel::pg::Pg> for ChargeRefunds
+where
+ serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>,
+{
+ fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result {
+ let value = serde_json::to_value(self)?;
+
+ // the function `reborrow` only works in case of `Pg` backend. But, in case of other backends
+ // please refer to the diesel migration blog:
+ // https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations
+ <serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
+ }
+}
+
/// This Unit struct represents MinorUnit in which core amount works
#[derive(
Default,
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index ffa9aee1153..6bb286b42a9 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -70,6 +70,7 @@ pub struct PaymentAttempt {
pub mandate_data: Option<storage_enums::MandateDetails>,
pub fingerprint_id: Option<String>,
pub payment_method_billing_address_id: Option<String>,
+ pub charge_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
}
@@ -152,6 +153,7 @@ pub struct PaymentAttemptNew {
pub mandate_data: Option<storage_enums::MandateDetails>,
pub fingerprint_id: Option<String>,
pub payment_method_billing_address_id: Option<String>,
+ pub charge_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
}
@@ -281,6 +283,7 @@ pub enum PaymentAttemptUpdate {
unified_code: Option<Option<String>>,
unified_message: Option<Option<String>>,
payment_method_data: Option<serde_json::Value>,
+ charge_id: Option<String>,
},
UnresolvedResponseUpdate {
status: storage_enums::AttemptStatus,
@@ -334,6 +337,7 @@ pub enum PaymentAttemptUpdate {
encoded_data: Option<String>,
connector_transaction_id: Option<String>,
connector: Option<String>,
+ charge_id: Option<String>,
updated_by: String,
},
IncrementalAuthorizationAmountUpdate {
@@ -394,6 +398,7 @@ pub struct PaymentAttemptUpdateInternal {
authentication_id: Option<String>,
fingerprint_id: Option<String>,
payment_method_billing_address_id: Option<String>,
+ charge_id: Option<String>,
client_source: Option<String>,
client_version: Option<String>,
}
@@ -461,6 +466,7 @@ impl PaymentAttemptUpdate {
authentication_id,
payment_method_billing_address_id,
fingerprint_id,
+ charge_id,
client_source,
client_version,
} = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source);
@@ -511,6 +517,7 @@ impl PaymentAttemptUpdate {
payment_method_billing_address_id: payment_method_billing_address_id
.or(source.payment_method_billing_address_id),
fingerprint_id: fingerprint_id.or(source.fingerprint_id),
+ charge_id: charge_id.or(source.charge_id),
client_source: client_source.or(source.client_source),
client_version: client_version.or(source.client_version),
..source
@@ -698,6 +705,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
unified_code,
unified_message,
payment_method_data,
+ charge_id,
} => Self {
status: Some(status),
connector: connector.map(Some),
@@ -719,6 +727,7 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
unified_code,
unified_message,
payment_method_data,
+ charge_id,
..Default::default()
},
PaymentAttemptUpdate::ErrorUpdate {
@@ -841,12 +850,14 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
connector_transaction_id,
connector,
updated_by,
+ charge_id,
} => Self {
authentication_data,
encoded_data,
connector_transaction_id,
connector: connector.map(Some),
updated_by,
+ charge_id,
..Default::default()
},
PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 5b5eb0f79e2..2c992554671 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -58,6 +58,7 @@ pub struct PaymentIntent {
pub session_expiry: Option<PrimitiveDateTime>,
pub fingerprint_id: Option<String>,
pub request_external_three_ds_authentication: Option<bool>,
+ pub charges: Option<pii::SecretSerdeValue>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
}
@@ -112,6 +113,7 @@ pub struct PaymentIntentNew {
pub session_expiry: Option<PrimitiveDateTime>,
pub fingerprint_id: Option<String>,
pub request_external_three_ds_authentication: Option<bool>,
+ pub charges: Option<pii::SecretSerdeValue>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
}
@@ -242,6 +244,7 @@ pub struct PaymentIntentUpdateInternal {
pub session_expiry: Option<PrimitiveDateTime>,
pub fingerprint_id: Option<String>,
pub request_external_three_ds_authentication: Option<bool>,
+ pub charges: Option<pii::SecretSerdeValue>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
}
@@ -278,6 +281,7 @@ impl PaymentIntentUpdate {
session_expiry,
fingerprint_id,
request_external_three_ds_authentication,
+ charges,
frm_metadata,
} = self.into();
PaymentIntent {
@@ -316,6 +320,7 @@ impl PaymentIntentUpdate {
session_expiry: session_expiry.or(source.session_expiry),
request_external_three_ds_authentication: request_external_three_ds_authentication
.or(source.request_external_three_ds_authentication),
+ charges: charges.or(source.charges),
frm_metadata: frm_metadata.or(source.frm_metadata),
..source
diff --git a/crates/diesel_models/src/query/connector_response.rs b/crates/diesel_models/src/query/connector_response.rs
index 952db945ae3..bdc24139ab6 100644
--- a/crates/diesel_models/src/query/connector_response.rs
+++ b/crates/diesel_models/src/query/connector_response.rs
@@ -22,6 +22,7 @@ impl ConnectorResponseNew {
connector_transaction_id: self.connector_transaction_id.clone(),
connector: self.connector_name.clone(),
updated_by: self.updated_by.clone(),
+ charge_id: self.charge_id.clone(),
};
let _payment_attempt: Result<PaymentAttempt, _> =
@@ -63,12 +64,14 @@ impl ConnectorResponse {
authentication_data,
encoded_data,
connector_name,
+ charge_id,
updated_by,
} => PaymentAttemptUpdate::ConnectorResponse {
authentication_data,
encoded_data,
connector_transaction_id,
connector: connector_name,
+ charge_id,
updated_by,
},
ConnectorResponseUpdate::ErrorUpdate {
@@ -79,6 +82,7 @@ impl ConnectorResponse {
encoded_data: None,
connector_transaction_id: None,
connector: connector_name,
+ charge_id: None,
updated_by,
},
};
diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs
index 0ee486bae48..aac282992a8 100644
--- a/crates/diesel_models/src/refund.rs
+++ b/crates/diesel_models/src/refund.rs
@@ -1,4 +1,4 @@
-use common_utils::pii;
+use common_utils::{pii, types::ChargeRefunds};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -39,6 +39,7 @@ pub struct Refund {
pub profile_id: Option<String>,
pub updated_by: String,
pub merchant_connector_id: Option<String>,
+ pub charges: Option<ChargeRefunds>,
}
#[derive(
@@ -81,6 +82,7 @@ pub struct RefundNew {
pub profile_id: Option<String>,
pub updated_by: String,
pub merchant_connector_id: Option<String>,
+ pub charges: Option<ChargeRefunds>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -275,7 +277,8 @@ mod tests {
"refund_error_code": null,
"profile_id": null,
"updated_by": "admin",
- "merchant_connector_id": null
+ "merchant_connector_id": null,
+ "charges": null
}"#;
let deserialized = serde_json::from_str::<super::Refund>(serialized_refund);
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index ba540f7f0bc..de5b536dcda 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -785,6 +785,8 @@ diesel::table! {
#[max_length = 64]
payment_method_billing_address_id -> Nullable<Varchar>,
#[max_length = 64]
+ charge_id -> Nullable<Varchar>,
+ #[max_length = 64]
client_source -> Nullable<Varchar>,
#[max_length = 64]
client_version -> Nullable<Varchar>,
@@ -856,6 +858,7 @@ diesel::table! {
#[max_length = 64]
fingerprint_id -> Nullable<Varchar>,
request_external_three_ds_authentication -> Nullable<Bool>,
+ charges -> Nullable<Jsonb>,
frm_metadata -> Nullable<Jsonb>,
}
}
@@ -1094,6 +1097,7 @@ diesel::table! {
updated_by -> Varchar,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
+ charges -> Nullable<Jsonb>,
}
}
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index 298d82cf31e..1ffaa33a215 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -73,6 +73,7 @@ pub struct PaymentAttemptBatchNew {
pub mandate_data: Option<MandateDetails>,
pub payment_method_billing_address_id: Option<String>,
pub fingerprint_id: Option<String>,
+ pub charge_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
}
@@ -135,6 +136,7 @@ impl PaymentAttemptBatchNew {
mandate_data: self.mandate_data,
payment_method_billing_address_id: self.payment_method_billing_address_id,
fingerprint_id: self.fingerprint_id,
+ charge_id: self.charge_id,
client_source: self.client_source,
client_version: self.client_version,
}
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 0491081e876..b9adc162c47 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -60,5 +60,6 @@ pub struct PaymentIntent {
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub session_expiry: Option<PrimitiveDateTime>,
pub request_external_three_ds_authentication: Option<bool>,
+ pub charges: Option<pii::SecretSerdeValue>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index ff4c7ac017e..ac0c74ea913 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -167,6 +167,7 @@ pub struct PaymentAttempt {
pub mandate_data: Option<MandateDetails>,
pub payment_method_billing_address_id: Option<String>,
pub fingerprint_id: Option<String>,
+ pub charge_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
}
@@ -255,6 +256,7 @@ pub struct PaymentAttemptNew {
pub mandate_data: Option<MandateDetails>,
pub payment_method_billing_address_id: Option<String>,
pub fingerprint_id: Option<String>,
+ pub charge_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
}
@@ -381,6 +383,7 @@ pub enum PaymentAttemptUpdate {
unified_code: Option<Option<String>>,
unified_message: Option<Option<String>>,
payment_method_data: Option<serde_json::Value>,
+ charge_id: Option<String>,
},
UnresolvedResponseUpdate {
status: storage_enums::AttemptStatus,
@@ -434,6 +437,7 @@ pub enum PaymentAttemptUpdate {
encoded_data: Option<String>,
connector_transaction_id: Option<String>,
connector: Option<String>,
+ charge_id: Option<String>,
updated_by: String,
},
IncrementalAuthorizationAmountUpdate {
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index a3353e6dfaf..5cf6f1219f5 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -115,6 +115,7 @@ pub struct PaymentIntentNew {
pub fingerprint_id: Option<String>,
pub session_expiry: Option<PrimitiveDateTime>,
pub request_external_three_ds_authentication: Option<bool>,
+ pub charges: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index e95f6efd373..026a191977c 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -315,6 +315,33 @@ pub struct RefundsData {
/// Arbitrary metadata required for refund
pub connector_metadata: Option<serde_json::Value>,
pub browser_info: Option<BrowserInformation>,
+ /// Charges associated with the payment
+ pub charges: Option<ChargeRefunds>,
+}
+
+#[derive(Debug, serde::Deserialize, Clone)]
+pub struct ChargeRefunds {
+ pub charge_id: String,
+ pub transfer_account_id: String,
+ pub charge_type: api_models::enums::PaymentChargeType,
+ pub options: ChargeRefundsOptions,
+}
+
+#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+pub enum ChargeRefundsOptions {
+ Destination(DestinationChargeRefund),
+ Direct(DirectChargeRefund),
+}
+
+#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+pub struct DirectChargeRefund {
+ pub revert_platform_fee: bool,
+}
+
+#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
+pub struct DestinationChargeRefund {
+ pub revert_platform_fee: bool,
+ pub revert_transfer: bool,
}
#[derive(Debug, Clone)]
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index b040cb00898..8830c689937 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -521,6 +521,11 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::webhook_events::OutgoingWebhookRequestContent,
api_models::webhook_events::OutgoingWebhookResponseContent,
api_models::enums::WebhookDeliveryAttempt,
+ api_models::enums::PaymentChargeType,
+ api_models::enums::StripeChargeType,
+ api_models::payments::PaymentChargeRequest,
+ api_models::payments::PaymentChargeResponse,
+ api_models::refunds::ChargeRefunds,
)),
modifiers(&SecurityAddon)
)]
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index d818fb80dbb..8415453b6ae 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -771,6 +771,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 6e86bfb305d..1c24009c54b 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -3185,6 +3185,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>>
network_txn_id: None,
connector_response_reference_id: Some(item.response.reference),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -3219,6 +3220,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
payment_method_balance: Some(types::PaymentMethodBalance {
amount: item.response.balance.value,
@@ -3283,6 +3285,7 @@ pub fn get_adyen_response(
network_txn_id,
connector_response_reference_id: Some(response.merchant_reference),
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payments_response_data))
}
@@ -3345,6 +3348,7 @@ pub fn get_webhook_response(
network_txn_id: None,
connector_response_reference_id: Some(response.merchant_reference_id),
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payments_response_data))
}
@@ -3417,6 +3421,7 @@ pub fn get_redirection_response(
.clone()
.or(response.psp_reference),
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payments_response_data))
}
@@ -3474,6 +3479,7 @@ pub fn get_present_to_shopper_response(
.clone()
.or(response.psp_reference),
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payments_response_data))
}
@@ -3530,6 +3536,7 @@ pub fn get_qr_code_response(
.clone()
.or(response.psp_reference),
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payments_response_data))
}
@@ -3566,6 +3573,7 @@ pub fn get_redirection_error_response(
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payments_response_data))
@@ -3932,6 +3940,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>>
network_txn_id: None,
connector_response_reference_id: Some(item.response.reference),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
amount_captured: Some(0),
..item.data
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
index fe0cd021ebc..587a14caedf 100644
--- a/crates/router/src/connector/airwallex/transformers.rs
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -557,6 +557,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -599,6 +600,7 @@ impl
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 8069b925d44..3e4d0a382e6 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -385,6 +385,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
@@ -922,6 +923,7 @@ impl<F, T>
transaction_response.transaction_id.clone(),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
},
..item.data
@@ -994,6 +996,7 @@ impl<F, T>
transaction_response.transaction_id.clone(),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
},
..item.data
@@ -1318,6 +1321,7 @@ impl<F, Req>
network_txn_id: None,
connector_response_reference_id: Some(transaction.transaction_id.clone()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
status: payment_status,
..item.data
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index 5fd8c5658a5..af4afeca10d 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -447,6 +447,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: Some(pg_response.order_number.to_string()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
@@ -473,6 +474,7 @@ impl<F>
item.data.connector_request_reference_id.to_string(),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -522,6 +524,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -574,6 +577,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -615,6 +619,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -656,6 +661,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_number.to_string()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index 4a5d99023cf..90151f12aeb 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -415,6 +415,7 @@ impl<F, T>
.unwrap_or(info_response.id),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
},
connector_response,
@@ -1645,6 +1646,7 @@ fn get_payment_response(
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
+ charge_id: None,
})
}
}
@@ -1697,6 +1699,7 @@ impl<F, T>
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
@@ -2052,6 +2055,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -2452,6 +2456,7 @@ impl<F>
.map(|cref| cref.code)
.unwrap_or(Some(app_response.id)),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
connector_response,
..item.data
@@ -2470,6 +2475,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: Some(error_response.id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
diff --git a/crates/router/src/connector/billwerk/transformers.rs b/crates/router/src/connector/billwerk/transformers.rs
index 372a65af9f3..811076a11da 100644
--- a/crates/router/src/connector/billwerk/transformers.rs
+++ b/crates/router/src/connector/billwerk/transformers.rs
@@ -276,6 +276,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.handle),
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.state),
diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
index a70c4ba3ac2..8a54c79b185 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -172,6 +172,7 @@ impl<F, T>
.order_id
.or(Some(item.response.data.id)),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs
index dff76576ace..f2a903c91f3 100644
--- a/crates/router/src/connector/bluesnap.rs
+++ b/crates/router/src/connector/bluesnap.rs
@@ -728,6 +728,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..data.clone()
})
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index d1dbb9d92e7..b8b5091fe5e 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -869,6 +869,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rs
index c22b6567732..2ff3e247653 100644
--- a/crates/router/src/connector/boku/transformers.rs
+++ b/crates/router/src/connector/boku/transformers.rs
@@ -274,6 +274,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, BokuResponse, T, types::Payments
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
index a607d8fc605..729f1f85922 100644
--- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
+++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
@@ -245,6 +245,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -263,6 +264,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
@@ -427,6 +429,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -445,6 +448,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
@@ -489,6 +493,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -534,6 +539,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -1062,6 +1068,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<BraintreeCaptureResponse>>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -1160,6 +1167,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -1258,6 +1266,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index e278ff40b43..a939f0a83f7 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -282,6 +282,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/cashtocode/transformers.rs b/crates/router/src/connector/cashtocode/transformers.rs
index f8c275df33b..ba55fca9b80 100644
--- a/crates/router/src/connector/cashtocode/transformers.rs
+++ b/crates/router/src/connector/cashtocode/transformers.rs
@@ -268,6 +268,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
)
}
@@ -312,6 +313,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index ddf65d23aa4..c92d75f1de8 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -681,6 +681,7 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>>
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok(Self {
status,
@@ -733,6 +734,7 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>>
item.response.reference.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok(Self {
status,
@@ -808,6 +810,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymentVoidResponse>>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
status: response.into(),
..item.data
@@ -908,6 +911,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
network_txn_id: None,
connector_response_reference_id: item.response.reference,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
status,
amount_captured,
diff --git a/crates/router/src/connector/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs
index f02984136bd..82a6add72ee 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/router/src/connector/coinbase/transformers.rs
@@ -149,6 +149,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.data.id.clone()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
|context| {
Ok(types::PaymentsResponseData::TransactionUnresolvedResponse{
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index d9d164ac201..1a1f23b93bf 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -190,6 +190,7 @@ impl<F, T>
.custom_id
.or(Some(item.response.data.id)),
incremental_authorization_allowed: None,
+ charge_id: None,
})
};
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index a9b1c37ae9c..f1774a0de39 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -1778,6 +1778,7 @@ fn get_payment_response(
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed,
+ charge_id: None,
})
}
}
@@ -1878,6 +1879,7 @@ impl<F>
.unwrap_or(info_response.id.clone()),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
@@ -2246,6 +2248,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -2486,6 +2489,7 @@ impl<F, T>
incremental_authorization_allowed: Some(
mandate_status == enums::AttemptStatus::Authorized,
),
+ charge_id: None,
}),
},
connector_response,
@@ -2645,6 +2649,7 @@ impl<F>
.map(|cref| cref.code)
.unwrap_or(Some(app_response.id)),
incremental_authorization_allowed,
+ charge_id: None,
}),
..item.data
})
@@ -2662,6 +2667,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: Some(error_response.id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index c073dc03cc9..b736c6a6c5a 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -330,6 +330,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
@@ -370,6 +371,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -407,6 +409,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -444,6 +447,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id.clone()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs
index 52c9522842f..2cf5960bf75 100644
--- a/crates/router/src/connector/dummyconnector/transformers.rs
+++ b/crates/router/src/connector/dummyconnector/transformers.rs
@@ -259,6 +259,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentsResponse, T, types::Paym
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs
index 3d40876c353..2dedb92d1dd 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/router/src/connector/fiserv/transformers.rs
@@ -370,6 +370,7 @@ impl<F, T>
gateway_resp.transaction_processing_details.order_id,
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -412,6 +413,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, FiservSyncResponse, T, types::Pa
.clone(),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index 861801d1295..9a0881f63d1 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -278,6 +278,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -326,6 +327,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -394,6 +396,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<ForteCaptureResponse>>
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.to_string()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
amount_captured: None,
..item.data
@@ -462,6 +465,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(transaction_id.to_string()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index 6653205c06a..3bdc3360a79 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -235,6 +235,7 @@ fn get_payment_response(
network_txn_id: None,
connector_response_reference_id: response.reference,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
}
}
diff --git a/crates/router/src/connector/globepay/transformers.rs b/crates/router/src/connector/globepay/transformers.rs
index efe96454933..dc0f970481c 100644
--- a/crates/router/src/connector/globepay/transformers.rs
+++ b/crates/router/src/connector/globepay/transformers.rs
@@ -194,6 +194,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -268,6 +269,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index b94dd73dd27..ee1ff91cd47 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -512,6 +512,7 @@ impl<F>
redirection_data: None,
mandate_reference,
network_txn_id: None,
+ charge_id: None,
}),
status: enums::AttemptStatus::Charged,
..item.data
@@ -664,6 +665,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -699,6 +701,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/helcim/transformers.rs b/crates/router/src/connector/helcim/transformers.rs
index 655d8a8663b..a3341ddab47 100644
--- a/crates/router/src/connector/helcim/transformers.rs
+++ b/crates/router/src/connector/helcim/transformers.rs
@@ -369,6 +369,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
@@ -424,6 +425,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
@@ -483,6 +485,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
@@ -569,6 +572,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
@@ -631,6 +635,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: item.response.invoice_number.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
status: enums::AttemptStatus::from(item.response),
..item.data
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index 3e337d3a74e..5daa33ab944 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -300,6 +300,7 @@ fn get_iatpay_response(
network_txn_id: None,
connector_response_reference_id: connector_response_reference_id.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
},
|checkout_methods| types::PaymentsResponseData::TransactionResponse {
resource_id: id,
@@ -313,6 +314,7 @@ fn get_iatpay_response(
network_txn_id: None,
connector_response_reference_id: connector_response_reference_id.clone(),
incremental_authorization_allowed: None,
+ charge_id: None,
},
);
Ok((status, error, payment_response_data))
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index db77b9c30cd..15fed065f06 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -161,6 +161,7 @@ impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>>
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id.clone()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
status: item.response.fraud_status.into(),
..item.data
diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs
index 486d91cd57f..b37602e8d76 100644
--- a/crates/router/src/connector/mifinity/transformers.rs
+++ b/crates/router/src/connector/mifinity/transformers.rs
@@ -134,6 +134,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index a9fe46cb592..9320aee8d7a 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -540,6 +540,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index 400e5ecd111..8f2cf5f833d 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -699,6 +699,7 @@ impl<F, T>
payment_response.data.order_id.clone(),
),
incremental_authorization_allowed: None,
+ charge_id: None,
})
},
..item.data
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index c6ef4ea1ba8..e8c606d7c58 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -372,6 +372,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -455,6 +456,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.order.order_id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index fdc65963fe8..2a8498bfbad 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -225,6 +225,7 @@ impl
network_txn_id: None,
connector_response_reference_id: Some(item.response.transactionid),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
enums::AttemptStatus::AuthenticationPending,
),
@@ -378,6 +379,7 @@ impl
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
if let Some(diesel_models::enums::CaptureMethod::Automatic) =
item.data.request.capture_method
@@ -754,6 +756,7 @@ impl
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
enums::AttemptStatus::CaptureInitiated,
),
@@ -848,6 +851,7 @@ impl<T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
enums::AttemptStatus::Charged,
),
@@ -904,6 +908,7 @@ impl TryFrom<types::PaymentsResponseRouterData<StandardResponse>>
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
if let Some(diesel_models::enums::CaptureMethod::Automatic) =
item.data.request.capture_method
@@ -954,6 +959,7 @@ impl<T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.orderid),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
enums::AttemptStatus::VoidInitiated,
),
@@ -1004,6 +1010,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SyncResponse, T, types::Payments
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index de20f37cf37..7534d32a04a 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -599,6 +599,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
+ charge_id: None,
})
}
},
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index e0d7a58566d..ace33e3e30f 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -1472,6 +1472,7 @@ where
network_txn_id: None,
connector_response_reference_id: response.order_id,
incremental_authorization_allowed: None,
+ charge_id: None,
})
},
..item.data
diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs
index e00f9a331a1..327ec5def05 100644
--- a/crates/router/src/connector/opayo/transformers.rs
+++ b/crates/router/src/connector/opayo/transformers.rs
@@ -128,6 +128,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/router/src/connector/opennode/transformers.rs
index 09da5fc8f94..8f1579ac1ff 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/router/src/connector/opennode/transformers.rs
@@ -144,6 +144,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: item.response.data.order_id,
incremental_authorization_allowed: None,
+ charge_id: None,
})
} else {
Ok(types::PaymentsResponseData::TransactionUnresolvedResponse {
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index a8442f7ea8a..9b6da9a0e93 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -433,6 +433,7 @@ impl<F, T>
.unwrap_or(item.response.transaction_id),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index bf20eb1a0b5..634c0a17c7a 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -251,6 +251,7 @@ impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData {
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
})
}
}
@@ -317,6 +318,7 @@ impl From<&SaleQuery> for types::PaymentsResponseData {
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}
}
}
@@ -525,6 +527,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
}),
@@ -1080,6 +1083,7 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymeVoidResponse>>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
})
};
Ok(Self {
diff --git a/crates/router/src/connector/payone/transformers.rs b/crates/router/src/connector/payone/transformers.rs
index e9eb3b9ddd7..ebe34111abb 100644
--- a/crates/router/src/connector/payone/transformers.rs
+++ b/crates/router/src/connector/payone/transformers.rs
@@ -129,6 +129,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs
index f82317b5afd..9ff6b84a064 100644
--- a/crates/router/src/connector/paypal.rs
+++ b/crates/router/src/connector/paypal.rs
@@ -787,7 +787,8 @@ impl
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
- }),
+ charge_id: None,
+ }),
..data.clone()
})
}
@@ -837,6 +838,7 @@ impl
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..data.clone()
})
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 171d07f6517..0ea1331c448 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -1163,6 +1163,7 @@ impl<F, T>
.clone()
.or(Some(item.response.id)),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -1268,6 +1269,7 @@ impl<F, T>
purchase_units.map_or(item.response.id, |item| item.invoice_id.clone()),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -1305,6 +1307,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -1355,6 +1358,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -1423,6 +1427,7 @@ impl<F, T>
.clone()
.or(Some(item.response.supplementary_data.related_ids.order_id)),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -1758,6 +1763,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaypalCaptureResponse>>
.invoice_id
.or(Some(item.response.id)),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
amount_captured: Some(amount_captured),
..item.data
@@ -1809,6 +1815,7 @@ impl<F, T>
.invoice_id
.or(Some(item.response.id)),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs
index 575f199b730..5365fc74ef2 100644
--- a/crates/router/src/connector/payu/transformers.rs
+++ b/crates/router/src/connector/payu/transformers.rs
@@ -211,6 +211,7 @@ impl<F, T>
.ext_order_id
.or(Some(item.response.order_id)),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
amount_captured: None,
..item.data
@@ -264,6 +265,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
amount_captured: None,
..item.data
@@ -350,6 +352,7 @@ impl<F, T>
.ext_order_id
.or(Some(item.response.order_id)),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
amount_captured: None,
..item.data
@@ -484,6 +487,7 @@ impl<F, T>
.clone()
.or(Some(order.order_id.clone())),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
amount_captured: Some(
order
diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs
index e400dc9b399..ef6bde8f1a2 100644
--- a/crates/router/src/connector/placetopay/transformers.rs
+++ b/crates/router/src/connector/placetopay/transformers.rs
@@ -279,6 +279,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index 6b0675b1611..e47e0f51206 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -337,6 +337,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_identifier),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
Err,
);
diff --git a/crates/router/src/connector/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs
index 7a8cd6e14d0..6862c7c4c80 100644
--- a/crates/router/src/connector/prophetpay/transformers.rs
+++ b/crates/router/src/connector/prophetpay/transformers.rs
@@ -207,6 +207,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -406,6 +407,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -456,6 +458,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -506,6 +509,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs
index d949a30a011..128fca65a92 100644
--- a/crates/router/src/connector/rapyd/transformers.rs
+++ b/crates/router/src/connector/rapyd/transformers.rs
@@ -480,6 +480,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
)
}
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 30f327c700e..7a8bc2587f9 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -677,6 +677,7 @@ impl<F>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -719,6 +720,7 @@ impl<T, F>
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index 0de122d5da2..184b1824362 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -381,6 +381,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: item.response.payment.reference_id,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
amount_captured,
..item.data
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs
index 6477b2325e4..d3072654028 100644
--- a/crates/router/src/connector/stax/transformers.rs
+++ b/crates/router/src/connector/stax/transformers.rs
@@ -360,6 +360,7 @@ impl<F, T>
item.response.idempotency_id.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index b41c331b74b..febb039768c 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -877,6 +877,21 @@ impl
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
+
+ req.request
+ .charges
+ .as_ref()
+ .map(|charge| match &charge.charge_type {
+ api::enums::PaymentChargeType::Stripe(stripe_charge) => {
+ if stripe_charge == &api::enums::StripeChargeType::Direct {
+ let mut customer_account_header = vec![(
+ headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
+ charge.transfer_account_id.clone().into_masked(),
+ )];
+ header.append(&mut customer_account_header);
+ }
+ }
+ });
Ok(header)
}
@@ -1355,6 +1370,21 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
+
+ req.request
+ .charges
+ .as_ref()
+ .map(|charge| match &charge.charge_type {
+ api::enums::PaymentChargeType::Stripe(stripe_charge) => {
+ if stripe_charge == &api::enums::StripeChargeType::Direct {
+ let mut customer_account_header = vec![(
+ headers::STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
+ charge.transfer_account_id.clone().into_masked(),
+ )];
+ header.append(&mut customer_account_header);
+ }
+ }
+ });
Ok(header)
}
@@ -1375,8 +1405,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
req: &types::RefundsRouterData<api::Execute>,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = stripe::RefundRequest::try_from(req)?;
- Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
+ let request_body = match req.request.charges.as_ref() {
+ None => RequestContent::FormUrlEncoded(Box::new(stripe::RefundRequest::try_from(req)?)),
+ Some(_) => RequestContent::FormUrlEncoded(Box::new(
+ stripe::ChargeRefundRequest::try_from(req)?,
+ )),
+ };
+ Ok(request_body)
}
fn build_request(
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index da524bea4c7..55b0d7f4675 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -157,6 +157,18 @@ pub struct PaymentIntentRequest {
pub expand: Option<ExpandableObjects>,
#[serde(flatten)]
pub browser_info: Option<StripeBrowserInformation>,
+ #[serde(flatten)]
+ pub charges: Option<IntentCharges>,
+}
+
+#[derive(Debug, Eq, PartialEq, Serialize)]
+pub struct IntentCharges {
+ pub application_fee_amount: i64,
+ #[serde(
+ rename = "transfer_data[destination]",
+ skip_serializing_if = "Option::is_none"
+ )]
+ pub destination_account_id: Option<String>,
}
// Field rename is required only in case of serialization as it is passed in the request to the connector.
@@ -1826,6 +1838,25 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
None
};
+ let (charges, customer) = match &item.request.charges {
+ Some(charges) => {
+ let charges = match &charges.charge_type {
+ api_enums::PaymentChargeType::Stripe(charge_type) => match charge_type {
+ api_enums::StripeChargeType::Direct => Some(IntentCharges {
+ application_fee_amount: charges.fees,
+ destination_account_id: None,
+ }),
+ api_enums::StripeChargeType::Destination => Some(IntentCharges {
+ application_fee_amount: charges.fees,
+ destination_account_id: Some(charges.transfer_account_id.clone()),
+ }),
+ },
+ };
+ (charges, None)
+ }
+ None => (None, item.connector_customer.to_owned().map(Secret::new)),
+ };
+
Ok(Self {
amount: item.request.amount, //hopefully we don't loose some cents here
currency: item.request.currency.to_string(), //we need to copy the value and not transfer ownership
@@ -1845,13 +1876,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
payment_data,
payment_method_options,
payment_method,
- customer: item.connector_customer.to_owned().map(Secret::new),
+ customer,
setup_mandate_details,
off_session: item.request.off_session,
setup_future_usage: item.request.setup_future_usage,
payment_method_types,
expand: Some(ExpandableObjects::LatestCharge),
browser_info,
+ charges,
})
}
}
@@ -2350,6 +2382,14 @@ impl<F, T>
item.response.id.clone(),
))
} else {
+ let charge_id = item
+ .response
+ .latest_charge
+ .as_ref()
+ .map(|charge| match charge {
+ StripeChargeEnum::ChargeId(charge_id) => charge_id.clone(),
+ StripeChargeEnum::ChargeObject(charge) => charge.id.clone(),
+ });
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data,
@@ -2358,6 +2398,7 @@ impl<F, T>
network_txn_id,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
+ charge_id,
})
};
@@ -2533,6 +2574,14 @@ impl<F, T>
}),
_ => None,
};
+ let charge_id = item
+ .response
+ .latest_charge
+ .as_ref()
+ .map(|charge| match charge {
+ StripeChargeEnum::ChargeId(charge_id) => charge_id.clone(),
+ StripeChargeEnum::ChargeObject(charge) => charge.id.clone(),
+ });
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data,
@@ -2541,6 +2590,7 @@ impl<F, T>
network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id.clone()),
incremental_authorization_allowed: None,
+ charge_id,
})
};
@@ -2614,6 +2664,7 @@ impl<F, T>
network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
+ charge_id: None,
})
};
@@ -2817,6 +2868,50 @@ impl<F> TryFrom<&types::RefundsRouterData<F>> for RefundRequest {
}
}
+#[derive(Debug, Serialize)]
+pub struct ChargeRefundRequest {
+ pub charge: String,
+ pub refund_application_fee: Option<bool>,
+ pub reverse_transfer: Option<bool>,
+ pub amount: Option<i64>, //amount in cents, hence passed as integer
+ #[serde(flatten)]
+ pub meta_data: StripeMetadata,
+}
+
+impl<F> TryFrom<&types::RefundsRouterData<F>> for ChargeRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ let amount = item.request.refund_amount;
+ match item.request.charges.as_ref() {
+ None => Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "charges",
+ }
+ .into()),
+ Some(charges) => {
+ let (refund_application_fee, reverse_transfer) = match charges.options {
+ types::ChargeRefundsOptions::Direct(types::DirectChargeRefund {
+ revert_platform_fee,
+ }) => (Some(revert_platform_fee), None),
+ types::ChargeRefundsOptions::Destination(types::DestinationChargeRefund {
+ revert_platform_fee,
+ revert_transfer,
+ }) => (Some(revert_platform_fee), Some(revert_transfer)),
+ };
+ Ok(Self {
+ charge: charges.charge_id.clone(),
+ refund_application_fee,
+ reverse_transfer,
+ amount: Some(amount),
+ meta_data: StripeMetadata {
+ order_id: Some(item.request.refund_id.clone()),
+ is_refund_id_as_reference: Some("true".to_string()),
+ },
+ })
+ }
+ }
+ }
+}
+
// Type definition for Stripe Refund Response
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
@@ -3248,8 +3343,9 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ChargesResponse, T, types::Payme
mandate_reference: None,
connector_metadata: Some(connector_metadata),
network_txn_id: None,
- connector_response_reference_id: Some(item.response.id),
+ connector_response_reference_id: Some(item.response.id.clone()),
incremental_authorization_allowed: None,
+ charge_id: Some(item.response.id),
})
};
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index db225585f41..f6c494170f2 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -735,6 +735,7 @@ fn handle_cards_response(
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payment_response_data))
}
@@ -764,6 +765,7 @@ fn handle_bank_redirects_response(
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payment_response_data))
}
@@ -797,6 +799,7 @@ fn handle_bank_redirects_error_response(
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payment_response_data))
}
@@ -857,6 +860,7 @@ fn handle_bank_redirects_sync_response(
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payment_response_data))
}
@@ -904,6 +908,7 @@ pub fn handle_webhook_response(
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payment_response_data))
}
diff --git a/crates/router/src/connector/tsys/transformers.rs b/crates/router/src/connector/tsys/transformers.rs
index dfc7e61c000..2febb9c72ec 100644
--- a/crates/router/src/connector/tsys/transformers.rs
+++ b/crates/router/src/connector/tsys/transformers.rs
@@ -218,6 +218,7 @@ fn get_payments_response(connector_response: TsysResponse) -> types::PaymentsRes
network_txn_id: None,
connector_response_reference_id: Some(connector_response.transaction_id),
incremental_authorization_allowed: None,
+ charge_id: None,
}
}
@@ -242,6 +243,7 @@ fn get_payments_sync_response(
.clone(),
),
incremental_authorization_allowed: None,
+ charge_id: None,
}
}
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs
index 814eefaf5ff..a78ecc94443 100644
--- a/crates/router/src/connector/volt/transformers.rs
+++ b/crates/router/src/connector/volt/transformers.rs
@@ -283,6 +283,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -364,6 +365,7 @@ impl<F, T>
.merchant_internal_reference
.or(Some(payment_response.id)),
incremental_authorization_allowed: None,
+ charge_id: None,
})
},
..item.data
@@ -404,6 +406,7 @@ impl<F, T>
.merchant_internal_reference
.or(Some(webhook_response.payment)),
incremental_authorization_allowed: None,
+ charge_id: None,
})
},
..item.data
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index 1966c65a0a5..06d608a172e 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -582,6 +582,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, Payment, T, PaymentsResponseData
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -636,6 +637,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaymentResponse, T, PaymentsResp
network_txn_id: None,
connector_response_reference_id: Some(item.response.payment.id),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index af1a0787d9d..c44ae7afddf 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -233,6 +233,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..data.clone()
})
@@ -337,6 +338,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..data.clone()
})
@@ -400,6 +402,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..data.clone()
})
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index 5f0fd9f332f..8a61f0f693f 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -254,6 +254,7 @@ impl TryFrom<types::PaymentsResponseRouterData<WorldpayPaymentsResponse>>
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index 67538b819d5..0f067ab935c 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -946,6 +946,7 @@ fn get_zen_response(
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
};
Ok((status, error, payment_response_data))
}
@@ -989,6 +990,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, CheckoutResponse, T, types::Paym
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..value.data
})
diff --git a/crates/router/src/connector/zsl/transformers.rs b/crates/router/src/connector/zsl/transformers.rs
index 58ff6ab2fab..ce1ae41fa49 100644
--- a/crates/router/src/connector/zsl/transformers.rs
+++ b/crates/router/src/connector/zsl/transformers.rs
@@ -336,6 +336,7 @@ impl<F, T>
network_txn_id: None,
connector_response_reference_id: Some(item.response.mer_ref.clone()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
@@ -425,6 +426,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, ZslWebhookResponse, T, types::Pa
network_txn_id: None,
connector_response_reference_id: Some(item.response.mer_ref.clone()),
incremental_authorization_allowed: None,
+ charge_id: None,
}),
..item.data
})
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 06c8c7f2c94..81751e62f8b 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2972,6 +2972,7 @@ mod tests {
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
),
request_external_three_ds_authentication: None,
+ charges: None,
frm_metadata: None,
};
let req_cs = Some("1".to_string());
@@ -3031,6 +3032,7 @@ mod tests {
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
),
request_external_three_ds_authentication: None,
+ charges: None,
frm_metadata: None,
};
let req_cs = Some("1".to_string());
@@ -3089,6 +3091,7 @@ mod tests {
.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
),
request_external_three_ds_authentication: None,
+ charges: None,
frm_metadata: None,
};
let req_cs = Some("1".to_string());
@@ -3561,6 +3564,7 @@ impl AttemptType {
// New payment method billing address can be passed for a retry
payment_method_billing_address_id: None,
fingerprint_id: None,
+ charge_id: None,
client_source: None,
client_version: None,
}
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 5501dfe7caf..68f8b7056c0 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -14,7 +14,7 @@ use hyperswitch_domain_models::{
mandates::{MandateData, MandateDetails},
payments::payment_attempt::PaymentAttempt,
};
-use masking::{ExposeInterface, PeekInterface};
+use masking::{ExposeInterface, PeekInterface, Secret};
use router_derive::PaymentOperation;
use router_env::{instrument, logger, tracing};
use time::PrimitiveDateTime;
@@ -933,6 +933,7 @@ impl PaymentCreate {
fingerprint_id: None,
authentication_connector: None,
authentication_id: None,
+ charge_id: None,
client_source: None,
client_version: None,
},
@@ -997,6 +998,19 @@ impl PaymentCreate {
request.capture_method,
)?;
+ let charges = request
+ .charges
+ .as_ref()
+ .map(|charges| {
+ charges.encode_to_value().map_err(|err| {
+ logger::warn!("Failed to serialize PaymentCharges - {}", err);
+ err
+ })
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)?
+ .map(Secret::new);
+
Ok(storage::PaymentIntentNew {
payment_id: payment_id.to_string(),
merchant_id: merchant_account.merchant_id.to_string(),
@@ -1042,6 +1056,7 @@ impl PaymentCreate {
session_expiry: Some(session_expiry),
request_external_three_ds_authentication: request
.request_external_three_ds_authentication,
+ charges,
frm_metadata: request.frm_metadata.clone(),
})
}
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 6723a2ee5af..047eb350378 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -870,6 +870,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
connector_metadata,
connector_response_reference_id,
incremental_authorization_allowed,
+ charge_id,
..
} => {
payment_data
@@ -959,6 +960,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
authentication_data,
encoded_data,
payment_method_data: additional_payment_method_data,
+ charge_id,
}),
),
};
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 7c6c6336fcb..3bafd777409 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -360,6 +360,7 @@ where
resource_id,
connector_metadata,
redirection_data,
+ charge_id,
..
}) => {
let encoded_data = payment_data.payment_attempt.encoded_data.clone();
@@ -407,6 +408,7 @@ where
unified_code: None,
unified_message: None,
payment_method_data: additional_payment_method_data,
+ charge_id,
},
storage_scheme,
)
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index ca068f1d592..11ce9cd7ede 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1,13 +1,16 @@
use std::{fmt::Debug, marker::PhantomData, str::FromStr};
-use api_models::payments::{FrmMessage, GetAddressFromPaymentMethodData, RequestSurchargeDetails};
+use api_models::payments::{
+ FrmMessage, GetAddressFromPaymentMethodData, PaymentChargeRequest, PaymentChargeResponse,
+ RequestSurchargeDetails,
+};
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutAttemptResponse;
use common_enums::RequestIncrementalAuthorization;
use common_utils::{consts::X_HS_LATENCY, fp_utils, types::MinorUnit};
use diesel_models::ephemeral_key;
use error_stack::{report, ResultExt};
-use masking::{Maskable, Secret};
+use masking::{Maskable, PeekInterface, Secret};
use router_env::{instrument, tracing};
use super::{flows::Feature, types::AuthenticationData, PaymentData};
@@ -86,6 +89,7 @@ where
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
+ charge_id: None,
});
let additional_data = PaymentAdditionalData {
@@ -637,6 +641,28 @@ where
)
});
+ let charges_response = match payment_intent.charges {
+ None => None,
+ Some(charges) => {
+ let payment_charges: PaymentChargeRequest = charges
+ .peek()
+ .clone()
+ .parse_value("PaymentChargeRequest")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "Failed to parse PaymentChargeRequest for payment_intent {}",
+ payment_intent.payment_id
+ ))?;
+
+ Some(PaymentChargeResponse {
+ charge_id: payment_attempt.charge_id,
+ charge_type: payment_charges.charge_type,
+ application_fees: payment_charges.fees,
+ transfer_account_id: payment_charges.transfer_account_id,
+ })
+ }
+ };
+
services::ApplicationResponse::JsonWithHeaders((
response
.set_net_amount(payment_attempt.net_amount)
@@ -788,6 +814,7 @@ where
.set_customer(customer_details_response.clone())
.set_browser_info(payment_attempt.browser_info)
.set_updated(Some(payment_intent.modified_at))
+ .set_charges(charges_response)
.set_frm_metadata(payment_intent.frm_metadata)
.to_owned(),
headers,
@@ -1166,6 +1193,16 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
.map(|customer| customer.clone().into_inner())
});
+ let charges = match payment_data.payment_intent.charges {
+ Some(charges) => charges
+ .peek()
+ .clone()
+ .parse_value("PaymentCharges")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse charges in to PaymentCharges")?,
+ None => None,
+ };
+
Ok(Self {
payment_method_data: From::from(
payment_method_data.get_required_value("payment_method_data")?,
@@ -1209,6 +1246,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
.map(AuthenticationData::foreign_try_from)
.transpose()?,
customer_acceptance: payment_data.customer_acceptance,
+ charges,
})
}
}
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index e3a1daf39ac..eb3a711b5b9 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -374,3 +374,10 @@ impl ForeignTryFrom<&storage::Authentication> for AuthenticationData {
}
}
}
+
+#[derive(Debug, serde::Deserialize, Clone)]
+pub struct PaymentCharges {
+ pub charge_type: api_models::enums::PaymentChargeType,
+ pub fees: i64,
+ pub transfer_account_id: String,
+}
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 987d627f568..b9861ea1f23 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -5,8 +5,9 @@ use std::collections::HashMap;
#[cfg(feature = "olap")]
use api_models::admin::MerchantConnectorInfo;
-use common_utils::ext_traits::AsyncExt;
+use common_utils::ext_traits::{AsyncExt, ValueExt};
use error_stack::{report, ResultExt};
+use masking::PeekInterface;
use router_env::{instrument, tracing};
use scheduler::{consumer::types::process_data, utils as process_tracker_utils};
#[cfg(feature = "olap")]
@@ -16,7 +17,7 @@ use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt},
- payments::{self, access_token},
+ payments::{self, access_token, types::PaymentCharges},
utils as core_utils,
},
db, logger,
@@ -28,6 +29,7 @@ use crate::{
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignInto},
+ ChargeRefunds,
},
utils::{self, OptionExt},
workflows::payment_sync,
@@ -128,6 +130,7 @@ pub async fn refund_create_core(
.map(services::ApplicationResponse::Json)
}
+#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn trigger_refund_to_gateway(
state: &AppState,
@@ -137,6 +140,7 @@ pub async fn trigger_refund_to_gateway(
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
creds_identifier: Option<String>,
+ charges: Option<ChargeRefunds>,
) -> RouterResult<storage::Refund> {
let routed_through = payment_attempt
.connector
@@ -179,6 +183,7 @@ pub async fn trigger_refund_to_gateway(
payment_attempt,
refund,
creds_identifier,
+ charges,
)
.await?;
@@ -458,6 +463,7 @@ pub async fn sync_refund_with_gateway(
payment_attempt,
refund,
creds_identifier,
+ None,
)
.await?;
@@ -588,6 +594,39 @@ pub async fn validate_and_create_refund(
) -> RouterResult<refunds::RefundResponse> {
let db = &*state.store;
+ // Validate charge_id and refund options
+ let charges = match (
+ payment_intent.charges.as_ref(),
+ payment_attempt.charge_id.as_ref(),
+ ) {
+ (Some(charges), Some(charge_id)) => {
+ let refund_charge_request = req.charges.clone().get_required_value("charges")?;
+ utils::when(*charge_id != refund_charge_request.charge_id, || {
+ Err(report!(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "charges.charge_id"
+ }))
+ .attach_printable("charge_id sent in request mismatches with original charge_id")
+ })?;
+ let payment_charges: PaymentCharges = charges
+ .peek()
+ .clone()
+ .parse_value("PaymentCharges")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse charges in to PaymentCharges")?;
+ let options = validator::validate_charge_refund(
+ &refund_charge_request,
+ &payment_charges.charge_type,
+ )?;
+ Some(ChargeRefunds {
+ charge_id: charge_id.to_string(),
+ charge_type: payment_charges.charge_type,
+ transfer_account_id: payment_charges.transfer_account_id,
+ options,
+ })
+ }
+ _ => None,
+ };
+
// Only for initial dev and testing
let refund_type = req.refund_type.unwrap_or_default();
@@ -678,6 +717,7 @@ pub async fn validate_and_create_refund(
.set_refund_reason(req.reason)
.set_profile_id(payment_intent.profile_id.clone())
.set_merchant_connector_id(payment_attempt.merchant_connector_id.clone())
+ .set_charges(req.charges)
.to_owned();
let refund = match db
@@ -694,6 +734,7 @@ pub async fn validate_and_create_refund(
payment_attempt,
payment_intent,
creds_identifier,
+ charges,
)
.await?
}
@@ -832,6 +873,7 @@ pub async fn get_filters_for_refunds(
impl ForeignFrom<storage::Refund> for api::RefundResponse {
fn foreign_from(refund: storage::Refund) -> Self {
let refund = refund;
+
Self {
payment_id: refund.payment_id,
refund_id: refund.refund_id,
@@ -847,6 +889,7 @@ impl ForeignFrom<storage::Refund> for api::RefundResponse {
updated_at: Some(refund.updated_at),
connector: refund.connector,
merchant_connector_id: refund.merchant_connector_id,
+ charges: refund.charges,
}
}
}
@@ -864,6 +907,7 @@ pub async fn schedule_refund_execution(
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
creds_identifier: Option<String>,
+ charges: Option<ChargeRefunds>,
) -> RouterResult<storage::Refund> {
// refunds::RefundResponse> {
let db = &*state.store;
@@ -900,6 +944,7 @@ pub async fn schedule_refund_execution(
payment_attempt,
payment_intent,
creds_identifier,
+ charges,
)
.await
}
@@ -1079,6 +1124,41 @@ pub async fn trigger_refund_execute_workflow(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ let charges = match (
+ payment_intent.charges.as_ref(),
+ payment_attempt.charge_id.as_ref(),
+ ) {
+ (Some(charges), Some(charge_id)) => {
+ let refund_charge_request =
+ refund.charges.clone().get_required_value("charges")?;
+ utils::when(*charge_id != refund_charge_request.charge_id, || {
+ Err(report!(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "charges.charge_id"
+ }))
+ .attach_printable(
+ "charge_id sent in request mismatches with original charge_id",
+ )
+ })?;
+ let payment_charges: PaymentCharges = charges
+ .peek()
+ .clone()
+ .parse_value("PaymentCharges")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse charges in to PaymentCharges")?;
+ let options = validator::validate_charge_refund(
+ &refund_charge_request,
+ &payment_charges.charge_type,
+ )?;
+ Some(ChargeRefunds {
+ charge_id: charge_id.to_string(),
+ charge_type: payment_charges.charge_type,
+ transfer_account_id: payment_charges.transfer_account_id,
+ options,
+ })
+ }
+ _ => None,
+ };
+
//trigger refund request to gateway
let updated_refund = trigger_refund_to_gateway(
state,
@@ -1088,6 +1168,7 @@ pub async fn trigger_refund_execute_workflow(
&payment_attempt,
&payment_intent,
None,
+ charges,
)
.await?;
add_refund_sync_task(
diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/refunds/validator.rs
index 49248ae4fea..3788b8ac26d 100644
--- a/crates/router/src/core/refunds/validator.rs
+++ b/crates/router/src/core/refunds/validator.rs
@@ -4,7 +4,11 @@ use time::PrimitiveDateTime;
use crate::{
core::errors::{self, CustomResult, RouterResult},
- types::storage::{self, enums},
+ types::{
+ self,
+ api::enums as api_enums,
+ storage::{self, enums},
+ },
utils::{self, OptionExt},
};
@@ -144,3 +148,28 @@ pub fn validate_for_valid_refunds(
_ => Ok(()),
}
}
+
+pub fn validate_charge_refund(
+ charges: &common_utils::types::ChargeRefunds,
+ charge_type: &api_enums::PaymentChargeType,
+) -> RouterResult<types::ChargeRefundsOptions> {
+ match charge_type {
+ api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Direct) => Ok(
+ types::ChargeRefundsOptions::Direct(types::DirectChargeRefund {
+ revert_platform_fee: charges
+ .revert_platform_fee
+ .get_required_value("revert_platform_fee")?,
+ }),
+ ),
+ api_enums::PaymentChargeType::Stripe(api_enums::StripeChargeType::Destination) => Ok(
+ types::ChargeRefundsOptions::Destination(types::DestinationChargeRefund {
+ revert_platform_fee: charges
+ .revert_platform_fee
+ .get_required_value("revert_platform_fee")?,
+ revert_transfer: charges
+ .revert_transfer
+ .get_required_value("revert_transfer")?,
+ }),
+ ),
+ }
+}
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 237d8b62237..ca464cc6270 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -223,6 +223,7 @@ pub async fn construct_refund_router_data<'a, F>(
payment_attempt: &storage::PaymentAttempt,
refund: &'a storage::Refund,
creds_identifier: Option<String>,
+ charges: Option<types::ChargeRefunds>,
) -> RouterResult<types::RefundsRouterData<F>> {
let profile_id = get_profile_id_from_business_details(
payment_intent.business_country,
@@ -330,6 +331,7 @@ pub async fn construct_refund_router_data<'a, F>(
reason: refund.refund_reason.clone(),
connector_refund_id: refund.connector_refund_id.clone(),
browser_info,
+ charges,
},
response: Ok(types::RefundsResponseData {
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 3b24dd3960e..1b1bfed3871 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -394,6 +394,7 @@ mod storage {
profile_id: new.profile_id.clone(),
updated_by: new.updated_by.clone(),
merchant_connector_id: new.merchant_connector_id.clone(),
+ charges: new.charges.clone(),
};
let field = format!(
@@ -848,6 +849,7 @@ impl RefundInterface for MockDb {
profile_id: new.profile_id,
updated_by: new.updated_by,
merchant_connector_id: new.merchant_connector_id,
+ charges: new.charges,
};
refunds.push(refund.clone());
Ok(refund)
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 7f2f0764b5f..e2f2f6c0b70 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -35,8 +35,9 @@ pub use hyperswitch_domain_models::{
PaymentMethodBalance, PaymentMethodToken, RecurringMandatePaymentData, RouterData,
},
router_request_types::{
- AcceptDisputeRequestData, AccessTokenRequestData, BrowserInformation,
- DefendDisputeRequestData, RefundsData, ResponseId, RetrieveFileRequestData,
+ AcceptDisputeRequestData, AccessTokenRequestData, BrowserInformation, ChargeRefunds,
+ ChargeRefundsOptions, DefendDisputeRequestData, DestinationChargeRefund,
+ DirectChargeRefund, RefundsData, ResponseId, RetrieveFileRequestData,
SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData,
},
};
@@ -349,6 +350,7 @@ pub struct PaymentsAuthorizeData {
pub request_incremental_authorization: bool,
pub metadata: Option<pii::SecretSerdeValue>,
pub authentication_data: Option<AuthenticationData>,
+ pub charges: Option<types::PaymentCharges>,
}
#[derive(Debug, Clone, Default)]
@@ -806,6 +808,7 @@ pub enum PaymentsResponseData {
network_txn_id: Option<String>,
connector_response_reference_id: Option<String>,
incremental_authorization_allowed: Option<bool>,
+ charge_id: Option<String>,
},
MultipleCaptureResponse {
// pending_capture_id_list: Vec<String>,
@@ -1169,6 +1172,7 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData {
metadata: None,
authentication_data: None,
customer_acceptance: data.request.customer_acceptance.clone(),
+ charges: None, // TODO: allow charges on mandates?
}
}
}
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index d35abd233f1..cf7ba2382a3 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -52,6 +52,7 @@ impl VerifyConnectorData {
request_incremental_authorization: false,
authentication_data: None,
customer_acceptance: None,
+ charges: None,
}
}
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index ef39a5fca16..8936b2af67f 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -218,6 +218,7 @@ pub async fn generate_sample_data(
fingerprint_id: None,
session_expiry: Some(session_expiry),
request_external_three_ds_authentication: None,
+ charges: None,
frm_metadata: Default::default(),
};
let payment_attempt = PaymentAttemptBatchNew {
@@ -295,6 +296,7 @@ pub async fn generate_sample_data(
profile_id: payment_intent.profile_id.clone(),
updated_by: merchant_from_db.storage_scheme.to_string(),
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
+ charges: None,
})
} else {
None
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 3548bc5e5bd..b4eafee4c83 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -75,6 +75,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
metadata: None,
authentication_data: None,
customer_acceptance: None,
+ ..utils::PaymentAuthorizeType::default().0
},
response: Err(types::ErrorResponse::default()),
address: PaymentAddress::new(
@@ -152,6 +153,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
reason: None,
connector_refund_id: None,
browser_info: None,
+ ..utils::PaymentRefundType::default().0
},
response: Err(types::ErrorResponse::default()),
address: PaymentAddress::default(),
diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs
index 4d4318064e2..ff703dd84ef 100644
--- a/crates/router/tests/connectors/adyen.rs
+++ b/crates/router/tests/connectors/adyen.rs
@@ -182,6 +182,7 @@ impl AdyenTest {
metadata: None,
authentication_data: None,
customer_acceptance: None,
+ ..utils::PaymentAuthorizeType::default().0
})
}
}
diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs
index 2dd90e704b9..85026c9c447 100644
--- a/crates/router/tests/connectors/bitpay.rs
+++ b/crates/router/tests/connectors/bitpay.rs
@@ -99,6 +99,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
metadata: None,
authentication_data: None,
customer_acceptance: None,
+ ..utils::PaymentAuthorizeType::default().0
})
}
diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs
index 60620d1b4c4..76887fa0441 100644
--- a/crates/router/tests/connectors/cashtocode.rs
+++ b/crates/router/tests/connectors/cashtocode.rs
@@ -72,6 +72,7 @@ impl CashtocodeTest {
metadata: None,
authentication_data: None,
customer_acceptance: None,
+ ..utils::PaymentAuthorizeType::default().0
})
}
diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs
index 5dd42a2c97c..306255c94c5 100644
--- a/crates/router/tests/connectors/coinbase.rs
+++ b/crates/router/tests/connectors/coinbase.rs
@@ -101,6 +101,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
metadata: None,
authentication_data: None,
customer_acceptance: None,
+ ..utils::PaymentAuthorizeType::default().0
})
}
diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs
index c26bad8c567..6d52a174b58 100644
--- a/crates/router/tests/connectors/cryptopay.rs
+++ b/crates/router/tests/connectors/cryptopay.rs
@@ -99,6 +99,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
metadata: None,
authentication_data: None,
customer_acceptance: None,
+ ..utils::PaymentAuthorizeType::default().0
})
}
diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs
index 1e2cea554e9..91162b829e2 100644
--- a/crates/router/tests/connectors/opennode.rs
+++ b/crates/router/tests/connectors/opennode.rs
@@ -100,6 +100,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
metadata: None,
authentication_data: None,
customer_acceptance: None,
+ ..utils::PaymentAuthorizeType::default().0
})
}
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index cd1a44a7022..6718611b0c8 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -423,6 +423,7 @@ pub trait ConnectorActions: Connector {
reason: None,
connector_refund_id: Some(refund_id),
browser_info: None,
+ charges: None,
}),
payment_info,
);
@@ -942,6 +943,7 @@ impl Default for PaymentAuthorizeType {
metadata: None,
authentication_data: None,
customer_acceptance: None,
+ charges: None,
};
Self(data)
}
@@ -1018,6 +1020,7 @@ impl Default for PaymentRefundType {
reason: Some("Customer returned product".to_string()),
connector_refund_id: None,
browser_info: None,
+ charges: None,
};
Self(data)
}
@@ -1081,6 +1084,7 @@ pub fn get_connector_metadata(
network_txn_id: _,
connector_response_reference_id: _,
incremental_authorization_allowed: _,
+ charge_id: _,
}) => connector_metadata,
_ => None,
}
diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs
index 36d0bba6c46..e26ba15eb25 100644
--- a/crates/router/tests/connectors/worldline.rs
+++ b/crates/router/tests/connectors/worldline.rs
@@ -111,6 +111,7 @@ impl WorldlineTest {
metadata: None,
authentication_data: None,
customer_acceptance: None,
+ ..utils::PaymentAuthorizeType::default().0
})
}
}
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index cc2f2abc004..0e8df898f12 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -157,6 +157,7 @@ impl PaymentAttemptInterface for MockDb {
mandate_data: payment_attempt.mandate_data,
payment_method_billing_address_id: payment_attempt.payment_method_billing_address_id,
fingerprint_id: payment_attempt.fingerprint_id,
+ charge_id: payment_attempt.charge_id,
client_source: payment_attempt.client_source,
client_version: payment_attempt.client_version,
};
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index 8ad010be133..a12b06b2914 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -108,6 +108,7 @@ impl PaymentIntentInterface for MockDb {
fingerprint_id: new.fingerprint_id,
session_expiry: new.session_expiry,
request_external_three_ds_authentication: new.request_external_three_ds_authentication,
+ charges: new.charges,
frm_metadata: new.frm_metadata,
};
payment_intents.push(payment_intent.clone());
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index fb9a5882ee5..1e60c3e02f2 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -413,6 +413,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.payment_method_billing_address_id
.clone(),
fingerprint_id: payment_attempt.fingerprint_id.clone(),
+ charge_id: payment_attempt.charge_id.clone(),
client_source: payment_attempt.client_source.clone(),
client_version: payment_attempt.client_version.clone(),
};
@@ -1197,6 +1198,7 @@ impl DataModelExt for PaymentAttempt {
mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
payment_method_billing_address_id: self.payment_method_billing_address_id,
fingerprint_id: self.fingerprint_id,
+ charge_id: self.charge_id,
client_source: self.client_source,
client_version: self.client_version,
}
@@ -1263,6 +1265,7 @@ impl DataModelExt for PaymentAttempt {
.map(MandateDetails::from_storage_model),
payment_method_billing_address_id: storage_model.payment_method_billing_address_id,
fingerprint_id: storage_model.fingerprint_id,
+ charge_id: storage_model.charge_id,
client_source: storage_model.client_source,
client_version: storage_model.client_version,
}
@@ -1333,6 +1336,7 @@ impl DataModelExt for PaymentAttemptNew {
mandate_data: self.mandate_data.map(|d| d.to_storage_model()),
payment_method_billing_address_id: self.payment_method_billing_address_id,
fingerprint_id: self.fingerprint_id,
+ charge_id: self.charge_id,
client_source: self.client_source,
client_version: self.client_version,
}
@@ -1397,6 +1401,7 @@ impl DataModelExt for PaymentAttemptNew {
.map(MandateDetails::from_storage_model),
payment_method_billing_address_id: storage_model.payment_method_billing_address_id,
fingerprint_id: storage_model.fingerprint_id,
+ charge_id: storage_model.charge_id,
client_source: storage_model.client_source,
client_version: storage_model.client_version,
}
@@ -1585,6 +1590,7 @@ impl DataModelExt for PaymentAttemptUpdate {
unified_code,
unified_message,
payment_method_data,
+ charge_id,
} => DieselPaymentAttemptUpdate::ResponseUpdate {
status,
connector,
@@ -1606,6 +1612,7 @@ impl DataModelExt for PaymentAttemptUpdate {
unified_code,
unified_message,
payment_method_data,
+ charge_id,
},
Self::UnresolvedResponseUpdate {
status,
@@ -1709,12 +1716,14 @@ impl DataModelExt for PaymentAttemptUpdate {
encoded_data,
connector_transaction_id,
connector,
+ charge_id,
updated_by,
} => DieselPaymentAttemptUpdate::ConnectorResponse {
authentication_data,
encoded_data,
connector_transaction_id,
connector,
+ charge_id,
updated_by,
},
Self::IncrementalAuthorizationAmountUpdate {
@@ -1913,6 +1922,7 @@ impl DataModelExt for PaymentAttemptUpdate {
unified_code,
unified_message,
payment_method_data,
+ charge_id,
} => Self::ResponseUpdate {
status,
connector,
@@ -1933,6 +1943,7 @@ impl DataModelExt for PaymentAttemptUpdate {
unified_code,
unified_message,
payment_method_data,
+ charge_id,
},
DieselPaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
@@ -2034,12 +2045,14 @@ impl DataModelExt for PaymentAttemptUpdate {
encoded_data,
connector_transaction_id,
connector,
+ charge_id,
updated_by,
} => Self::ConnectorResponse {
authentication_data,
encoded_data,
connector_transaction_id,
connector,
+ charge_id,
updated_by,
},
DieselPaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 0ac963ae816..f40a9c3e2d4 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -118,6 +118,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
session_expiry: new.session_expiry,
request_external_three_ds_authentication: new
.request_external_three_ds_authentication,
+ charges: new.charges.clone(),
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
@@ -849,6 +850,7 @@ impl DataModelExt for PaymentIntentNew {
fingerprint_id: self.fingerprint_id,
session_expiry: self.session_expiry,
request_external_three_ds_authentication: self.request_external_three_ds_authentication,
+ charges: self.charges,
}
}
@@ -897,6 +899,7 @@ impl DataModelExt for PaymentIntentNew {
session_expiry: storage_model.session_expiry,
request_external_three_ds_authentication: storage_model
.request_external_three_ds_authentication,
+ charges: storage_model.charges,
}
}
}
@@ -948,6 +951,7 @@ impl DataModelExt for PaymentIntent {
fingerprint_id: self.fingerprint_id,
session_expiry: self.session_expiry,
request_external_three_ds_authentication: self.request_external_three_ds_authentication,
+ charges: self.charges,
frm_metadata: self.frm_metadata,
}
}
@@ -997,6 +1001,7 @@ impl DataModelExt for PaymentIntent {
session_expiry: storage_model.session_expiry,
request_external_three_ds_authentication: storage_model
.request_external_three_ds_authentication,
+ charges: storage_model.charges,
frm_metadata: storage_model.frm_metadata,
}
}
diff --git a/migrations/2024-05-06-165401_add_charges_in_payment_intent/down.sql b/migrations/2024-05-06-165401_add_charges_in_payment_intent/down.sql
new file mode 100644
index 00000000000..53c2368276e
--- /dev/null
+++ b/migrations/2024-05-06-165401_add_charges_in_payment_intent/down.sql
@@ -0,0 +1,5 @@
+ALTER TABLE payment_intent DROP COLUMN IF EXISTS charges;
+
+ALTER TABLE payment_attempt DROP COLUMN IF EXISTS charge_id;
+
+ALTER TABLE refund DROP COLUMN IF EXISTS charges;
diff --git a/migrations/2024-05-06-165401_add_charges_in_payment_intent/up.sql b/migrations/2024-05-06-165401_add_charges_in_payment_intent/up.sql
new file mode 100644
index 00000000000..c2f1ce14d8b
--- /dev/null
+++ b/migrations/2024-05-06-165401_add_charges_in_payment_intent/up.sql
@@ -0,0 +1,6 @@
+ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS charges jsonb;
+
+ALTER TABLE payment_attempt
+ADD COLUMN IF NOT EXISTS charge_id VARCHAR(64);
+
+ALTER TABLE refund ADD COLUMN IF NOT EXISTS charges jsonb;
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 26eb8997c17..47da1ae1074 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -7317,6 +7317,29 @@
"CashappQr": {
"type": "object"
},
+ "ChargeRefunds": {
+ "type": "object",
+ "description": "Charge object for refunds",
+ "required": [
+ "charge_id"
+ ],
+ "properties": {
+ "charge_id": {
+ "type": "string",
+ "description": "Identifier for charge created for the payment"
+ },
+ "revert_platform_fee": {
+ "type": "boolean",
+ "description": "Toggle for reverting the application fee that was collected for the payment.\nIf set to false, the funds are pulled from the destination account.",
+ "nullable": true
+ },
+ "revert_transfer": {
+ "type": "boolean",
+ "description": "Toggle for reverting the transfer that was made during the charge.\nIf set to false, the funds are pulled from the main platform's account.",
+ "nullable": true
+ }
+ }
+ },
"Comparison": {
"type": "object",
"description": "Represents a single comparison condition.",
@@ -12529,6 +12552,70 @@
}
}
},
+ "PaymentChargeRequest": {
+ "type": "object",
+ "required": [
+ "charge_type",
+ "fees",
+ "transfer_account_id"
+ ],
+ "properties": {
+ "charge_type": {
+ "$ref": "#/components/schemas/PaymentChargeType"
+ },
+ "fees": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Platform fees to be collected on the payment"
+ },
+ "transfer_account_id": {
+ "type": "string",
+ "description": "Identifier for the reseller's account to send the funds to"
+ }
+ }
+ },
+ "PaymentChargeResponse": {
+ "type": "object",
+ "required": [
+ "charge_type",
+ "application_fees",
+ "transfer_account_id"
+ ],
+ "properties": {
+ "charge_id": {
+ "type": "string",
+ "description": "Identifier for charge created for the payment",
+ "nullable": true
+ },
+ "charge_type": {
+ "$ref": "#/components/schemas/PaymentChargeType"
+ },
+ "application_fees": {
+ "type": "integer",
+ "format": "int64",
+ "description": "Platform fees collected on the payment"
+ },
+ "transfer_account_id": {
+ "type": "string",
+ "description": "Identifier for the reseller's account where the funds were transferred"
+ }
+ }
+ },
+ "PaymentChargeType": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "Stripe"
+ ],
+ "properties": {
+ "Stripe": {
+ "$ref": "#/components/schemas/StripeChargeType"
+ }
+ }
+ }
+ ]
+ },
"PaymentCreatePaymentLinkConfig": {
"allOf": [
{
@@ -13954,6 +14041,14 @@
}
],
"nullable": true
+ },
+ "charges": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentChargeRequest"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -14327,6 +14422,14 @@
}
],
"nullable": true
+ },
+ "charges": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentChargeRequest"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -14834,6 +14937,14 @@
}
],
"nullable": true
+ },
+ "charges": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentChargeRequest"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
@@ -15359,6 +15470,14 @@
"example": "2022-09-10T10:11:12Z",
"nullable": true
},
+ "charges": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentChargeResponse"
+ }
+ ],
+ "nullable": true
+ },
"frm_metadata": {
"type": "object",
"description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM.",
@@ -15847,6 +15966,14 @@
}
],
"nullable": true
+ },
+ "charges": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentChargeRequest"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -17096,6 +17223,14 @@
}
],
"nullable": true
+ },
+ "charges": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ChargeRefunds"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
@@ -17177,6 +17312,14 @@
"type": "string",
"description": "The merchant_connector_id of the processor through which this payment went through",
"nullable": true
+ },
+ "charges": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ChargeRefunds"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -18198,6 +18341,13 @@
"propertyName": "type"
}
},
+ "StripeChargeType": {
+ "type": "string",
+ "enum": [
+ "direct",
+ "destination"
+ ]
+ },
"SurchargeDetailsResponse": {
"type": "object",
"required": [
|
2024-05-13T11:13:35Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Detailed description - https://github.com/juspay/hyperswitch/issues/4659
This PR adds functionality to create charges on payment intents using Stripe
- create `charges` on payment_intent
- store `charge_id` in payment_attempt
- use `charge_id` for refunds
- Direct
```
"charges": {
"charge_id": "ch_3PJDz8Ihl7EEkW0O16Wetnl5",
"revert_platform_fee": true
}
```
- Destination
```
"charges": {
"charge_id": "ch_3PJDz8Ihl7EEkW0O16Wetnl5",
"revert_platform_fee": true,
"revert_transfer": true
}
_Note_ - charges on mandates is not added in this PR.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
Tested locally using postman collection.
**Steps for testing**
- Make sure Stripe Connect is enabled on your Stripe account
- Onboard a Standard user by initiating an account link from Stripe's dashboard
- Make sure merchant account is created and Stripe is added as a payment connector
- Create a direct charge on payment by adding below field in `/payment_intents` request
```
"charges": {
"charge_type": "direct",
"fees": 123,
"transfer_account_id": "acct_1PDftAIhl7EEkW0O"
}
```
- Create a destination charge on payment by adding below field in `/payment_intents` request
```
"charges": {
"charge_type": "destination",
"fees": 123,
"transfer_account_id": "acct_1PDftAIhl7EEkW0O"
}
```
### Direct charges
- ref - https://docs.stripe.com/connect/direct-charges
- these help in directly creating charges when customer is paying to the connected account
- charges are created, money is split (Stripe fees + reseller’s fees) and the remaining amount is transferred to connected account’s balance
### Destination charges
- ref - https://docs.stripe.com/connect/destination-charges
- charges are created on the reseller’s account
- reseller decides whether some of all of those funds are to be transferred to the connected account
- reseller’s account is used for debiting the cost of Stripe fees, refunds and chargebacks
- only supported when both reseller and connected accounts belong to the same country
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ae77373b4cac63979673fdac37c55986d954358e
|
Tested locally using postman collection.
**Steps for testing**
- Make sure Stripe Connect is enabled on your Stripe account
- Onboard a Standard user by initiating an account link from Stripe's dashboard
- Make sure merchant account is created and Stripe is added as a payment connector
- Create a direct charge on payment by adding below field in `/payment_intents` request
```
"charges": {
"charge_type": "direct",
"fees": 123,
"transfer_account_id": "acct_1PDftAIhl7EEkW0O"
}
```
- Create a destination charge on payment by adding below field in `/payment_intents` request
```
"charges": {
"charge_type": "destination",
"fees": 123,
"transfer_account_id": "acct_1PDftAIhl7EEkW0O"
}
```
### Direct charges
- ref - https://docs.stripe.com/connect/direct-charges
- these help in directly creating charges when customer is paying to the connected account
- charges are created, money is split (Stripe fees + reseller’s fees) and the remaining amount is transferred to connected account’s balance
### Destination charges
- ref - https://docs.stripe.com/connect/destination-charges
- charges are created on the reseller’s account
- reseller decides whether some of all of those funds are to be transferred to the connected account
- reseller’s account is used for debiting the cost of Stripe fees, refunds and chargebacks
- only supported when both reseller and connected accounts belong to the same country
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4596
|
Bug: feat: Create API for TOTP Verification
To complete the TOTP Flow, there needs to be an API which needs to verify the totp entered by the user and give the next token and flow that user should go to enter into the dashboard.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 1d91a47bf56..e9eb5157095 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -17,7 +17,7 @@ use crate::user::{
ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse,
SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse,
TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate,
- VerifyEmailRequest,
+ VerifyEmailRequest, VerifyTotpRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -74,7 +74,8 @@ common_utils::impl_misc_api_event_type!(
GetUserRoleDetailsResponse,
TokenResponse,
UserFromEmailRequest,
- BeginTotpResponse
+ BeginTotpResponse,
+ VerifyTotpRequest
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 0dde73d0545..7dbf867d1a0 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -252,3 +252,8 @@ pub struct TotpSecret {
pub totp_url: Secret<String>,
pub recovery_codes: Vec<Secret<String>>,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct VerifyTotpRequest {
+ pub totp: Option<Secret<String>>,
+}
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index ddcd10c32e4..580e34ba7e8 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -66,6 +66,10 @@ pub enum UserErrors {
RoleNameParsingError,
#[error("RoleNameAlreadyExists")]
RoleNameAlreadyExists,
+ #[error("TOTPNotSetup")]
+ TotpNotSetup,
+ #[error("InvalidTOTP")]
+ InvalidTotp,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -169,6 +173,12 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::RoleNameAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 35, self.get_error_message(), None))
}
+ Self::TotpNotSetup => {
+ AER::BadRequest(ApiError::new(sub_code, 36, self.get_error_message(), None))
+ }
+ Self::InvalidTotp => {
+ AER::BadRequest(ApiError::new(sub_code, 37, self.get_error_message(), None))
+ }
}
}
}
@@ -205,6 +215,8 @@ impl UserErrors {
Self::InvalidRoleOperationWithMessage(error_message) => error_message,
Self::RoleNameParsingError => "Invalid Role Name",
Self::RoleNameAlreadyExists => "Role name already exists",
+ Self::TotpNotSetup => "TOTP not setup",
+ Self::InvalidTotp => "Invalid TOTP",
}
}
}
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index e01ed4b1a23..83cdd1d318b 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1642,3 +1642,65 @@ pub async fn begin_totp(
}),
}))
}
+
+pub async fn verify_totp(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ req: user_api::VerifyTotpRequest,
+) -> UserResponse<user_api::TokenResponse> {
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_id(&user_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ if let Some(user_totp) = req.totp {
+ if user_from_db.get_totp_status() == TotpStatus::NotSet {
+ return Err(UserErrors::TotpNotSetup.into());
+ }
+
+ let user_totp_secret = user_from_db
+ .decrypt_and_get_totp_secret(&state)
+ .await?
+ .ok_or(UserErrors::InternalServerError)?;
+
+ let totp =
+ utils::user::generate_default_totp(user_from_db.get_email(), Some(user_totp_secret))?;
+
+ if totp
+ .generate_current()
+ .change_context(UserErrors::InternalServerError)?
+ != user_totp.expose()
+ {
+ return Err(UserErrors::InvalidTotp.into());
+ }
+
+ if user_from_db.get_totp_status() == TotpStatus::InProgress {
+ state
+ .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.origin, domain::SPTFlow::TOTP.into())?;
+ let next_flow = current_flow.next(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,
+ )
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 1560578f66f..49a8e063183 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1199,7 +1199,8 @@ impl User {
.route(web::get().to(get_multiple_dashboard_metadata))
.route(web::post().to(set_dashboard_metadata)),
)
- .service(web::resource("/totp/begin").route(web::get().to(totp_begin)));
+ .service(web::resource("/totp/begin").route(web::get().to(totp_begin)))
+ .service(web::resource("/totp/verify").route(web::post().to(totp_verify)));
#[cfg(feature = "email")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 5bef68073f0..ee42cc50fe3 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -211,7 +211,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
| Flow::UpdateUserAccountDetails
- | Flow::TotpBegin => Self::User,
+ | Flow::TotpBegin
+ | Flow::TotpVerify => Self::User,
Flow::ListRoles
| Flow::GetRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index db12729d01a..a901988e51e 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -626,3 +626,21 @@ pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpRes
))
.await
}
+
+pub async fn totp_verify(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<user_api::VerifyTotpRequest>,
+) -> HttpResponse {
+ let flow = Flow::TotpVerify;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ |state, user, req_body, _| user_core::verify_totp(state, user, req_body),
+ &auth::SinglePurposeJWTAuth(common_enums::TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 00881626c1c..45f5d74d6f6 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -4,7 +4,7 @@ use api_models::{
admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api,
};
use common_enums::TokenPurpose;
-use common_utils::{errors::CustomResult, pii};
+use common_utils::{crypto::Encryptable, errors::CustomResult, pii};
use diesel_models::{
enums::{TotpStatus, UserStatus},
organization as diesel_org,
@@ -909,6 +909,32 @@ impl UserFromStorage {
pub fn get_totp_status(&self) -> TotpStatus {
self.0.totp_status
}
+
+ pub async fn decrypt_and_get_totp_secret(
+ &self,
+ state: &AppState,
+ ) -> UserResult<Option<Secret<String>>> {
+ if self.0.totp_secret.is_none() {
+ return Ok(None);
+ }
+
+ let user_key_store = state
+ .store
+ .get_user_key_store_by_user_id(
+ self.get_user_id(),
+ &state.store.get_master_key().to_vec().into(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(domain_types::decrypt::<String, masking::WithType>(
+ self.0.totp_secret.clone(),
+ user_key_store.key.peek(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .map(Encryptable::into_inner))
+ }
}
impl From<info::ModuleInfo> for user_role_api::ModuleInfo {
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b3252302413..9ea86167fcf 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -398,6 +398,8 @@ pub enum Flow {
UserFromEmail,
/// Begin TOTP
TotpBegin,
+ /// Verify TOTP
+ TotpVerify,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
2024-05-08T18:01:14Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR allows users to complete the TOTP flow.
It adds a new api `/user/totp/verify`, which will verify the totp entered by the user and mark the user totp status as set if it is in `InProgress`.
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
Closes #4596.
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
```
curl --location 'http://localhost:8080/user/totp/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
--data '{
"totp": "189646"
}'
```
If the TOTP is correct, the the API should return the next token that is in the current flow.
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZjYwOWFiMDAtNzg5Ny00NTU2LWFlMGMtNGQ4MDZmZGFkZTkxIiwicHVycG9zZSI6ImZvcmNlX3NldF9wYXNzd29yZCIsIm9yaWdpbiI6InNpZ25fdXAiLCJleHAiOjE3MTUyNjQ0NTF9.jkhMT8x1o5WhzNxqBbBwX4jS0TQuSpemlg9_5K5Kgk8",
"token_type": "force_set_password"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
ec3b60e37c0b178c3e5e3fe79db88f83fd195722
|
```
curl --location 'http://localhost:8080/user/totp/verify' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer SPT with Purpose as TOTP' \
--data '{
"totp": "189646"
}'
```
If the TOTP is correct, the the API should return the next token that is in the current flow.
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZjYwOWFiMDAtNzg5Ny00NTU2LWFlMGMtNGQ4MDZmZGFkZTkxIiwicHVycG9zZSI6ImZvcmNlX3NldF9wYXNzd29yZCIsIm9yaWdpbiI6InNpZ25fdXAiLCJleHAiOjE3MTUyNjQ0NTF9.jkhMT8x1o5WhzNxqBbBwX4jS0TQuSpemlg9_5K5Kgk8",
"token_type": "force_set_password"
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4615
|
Bug: Pass `required_shipping_contact_fields` field in apple pay session call based on `business_profile` config
This change is required as part of the one click checkout where in which we expect apple pay to collect the shipping details from the customer and pass it in the confirm call with the payment_data.
In order for apple pay to collect the shipping details from customer we need to pass `"requiredShippingContactFields": ["postalAddress", "phone", "email"]` in the `/session` call. Hence we need to have a validation in the backend that checks for the business profile config (`collect_shipping_details_from_wallet_connector`) fields and pass the `required_shipping_contact_fields` to sdk.
Similarly for google pay we need to pass the below mentioned fields for the shipping details.
```
"shipping_address_required": true,
"email_required": true,
"shipping_address_parameters": {
"phone_number_required": true
},
```
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 25de8821263..93cf7574d98 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -916,6 +916,9 @@ pub struct BusinessProfileCreate {
/// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
+
+ /// A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments
+ pub collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[derive(Clone, Debug, ToSchema, Serialize)]
@@ -1055,6 +1058,9 @@ pub struct BusinessProfileUpdate {
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
+
+ /// A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments
+ pub collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 37d17dcff17..866db8cc18d 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -422,6 +422,13 @@ pub enum FieldType {
UserAddressPincode,
UserAddressState,
UserAddressCountry { options: Vec<String> },
+ UserShippingName,
+ UserShippingAddressLine1,
+ UserShippingAddressLine2,
+ UserShippingAddressCity,
+ UserShippingAddressPincode,
+ UserShippingAddressState,
+ UserShippingAddressCountry { options: Vec<String> },
UserBlikCode,
UserBank,
Text,
@@ -440,6 +447,18 @@ impl FieldType {
Self::UserAddressCountry { options: vec![] },
]
}
+
+ pub fn get_shipping_variants() -> Vec<Self> {
+ vec![
+ Self::UserShippingName,
+ Self::UserShippingAddressLine1,
+ Self::UserShippingAddressLine2,
+ Self::UserShippingAddressCity,
+ Self::UserShippingAddressPincode,
+ Self::UserShippingAddressState,
+ Self::UserShippingAddressCountry { options: vec![] },
+ ]
+ }
}
/// This implementatiobn is to ignore the inner value of UserAddressCountry enum while comparing
@@ -477,6 +496,15 @@ impl PartialEq for FieldType {
(Self::UserAddressPincode, Self::UserAddressPincode) => true,
(Self::UserAddressState, Self::UserAddressState) => true,
(Self::UserAddressCountry { .. }, Self::UserAddressCountry { .. }) => true,
+ (Self::UserShippingName, Self::UserShippingName) => true,
+ (Self::UserShippingAddressLine1, Self::UserShippingAddressLine1) => true,
+ (Self::UserShippingAddressLine2, Self::UserShippingAddressLine2) => true,
+ (Self::UserShippingAddressCity, Self::UserShippingAddressCity) => true,
+ (Self::UserShippingAddressPincode, Self::UserShippingAddressPincode) => true,
+ (Self::UserShippingAddressState, Self::UserShippingAddressState) => true,
+ (Self::UserShippingAddressCountry { .. }, Self::UserShippingAddressCountry { .. }) => {
+ true
+ }
(Self::UserBlikCode, Self::UserBlikCode) => true,
(Self::UserBank, Self::UserBank) => true,
(Self::Text, Self::Text) => true,
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 20b94811ab2..343763321da 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4098,6 +4098,12 @@ pub struct GooglePayThirdPartySdk {
pub struct GooglePaySessionResponse {
/// The merchant info
pub merchant_info: GpayMerchantInfo,
+ /// Is shipping address required
+ pub shipping_address_required: bool,
+ /// Is email required
+ pub email_required: bool,
+ /// Shipping address parameters
+ pub shipping_address_parameters: GpayShippingAddressParameters,
/// List of the allowed payment meythods
pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>,
/// The transaction info Google Pay requires
@@ -4112,6 +4118,13 @@ pub struct GooglePaySessionResponse {
pub secrets: Option<SecretInfoToInitiateSdk>,
}
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(rename_all = "lowercase")]
+pub struct GpayShippingAddressParameters {
+ /// Is shipping phone number required
+ pub phone_number_required: bool,
+}
+
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
pub struct KlarnaSessionTokenResponse {
@@ -4234,7 +4247,22 @@ pub struct ApplePayPaymentRequest {
pub supported_networks: Option<Vec<String>>,
pub merchant_identifier: Option<String>,
/// The required billing contact fields for connector
- pub required_billing_contact_fields: Option<Vec<String>>,
+ pub required_billing_contact_fields: Option<ApplePayBillingContactFields>,
+ /// The required shipping contacht fields for connector
+ pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)]
+pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>);
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)]
+pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>);
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ApplePayAddressParameters {
+ PostalAddress,
+ Phone,
+ Email,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)]
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 41a938d83ed..fb1b62e5436 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -39,6 +39,7 @@ pub struct BusinessProfile {
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
+ pub collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -69,6 +70,7 @@ pub struct BusinessProfileNew {
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
+ pub collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -96,6 +98,7 @@ pub struct BusinessProfileUpdateInternal {
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
+ pub collect_shipping_details_from_wallet_connector: Option<bool>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -120,6 +123,7 @@ pub enum BusinessProfileUpdate {
authentication_connector_details: Option<serde_json::Value>,
extended_card_info_config: Option<pii::SecretSerdeValue>,
use_billing_as_payment_method_billing: Option<bool>,
+ collect_shipping_details_from_wallet_connector: Option<bool>,
},
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: Option<bool>,
@@ -152,6 +156,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
authentication_connector_details,
extended_card_info_config,
use_billing_as_payment_method_billing,
+ collect_shipping_details_from_wallet_connector,
} => Self {
profile_name,
modified_at,
@@ -172,6 +177,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
authentication_connector_details,
extended_card_info_config,
use_billing_as_payment_method_billing,
+ collect_shipping_details_from_wallet_connector,
..Default::default()
},
BusinessProfileUpdate::ExtendedCardInfoUpdate {
@@ -217,6 +223,8 @@ impl From<BusinessProfileNew> for BusinessProfile {
is_extended_card_info_enabled: new.is_extended_card_info_enabled,
extended_card_info_config: new.extended_card_info_config,
use_billing_as_payment_method_billing: new.use_billing_as_payment_method_billing,
+ collect_shipping_details_from_wallet_connector: new
+ .collect_shipping_details_from_wallet_connector,
}
}
}
@@ -245,6 +253,7 @@ impl BusinessProfileUpdate {
extended_card_info_config,
is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing,
+ collect_shipping_details_from_wallet_connector,
} = self.into();
BusinessProfile {
profile_name: profile_name.unwrap_or(source.profile_name),
@@ -270,6 +279,7 @@ impl BusinessProfileUpdate {
is_connector_agnostic_mit_enabled,
extended_card_info_config,
use_billing_as_payment_method_billing,
+ collect_shipping_details_from_wallet_connector,
..source
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index a81c240e8b0..e63c14eef15 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -195,6 +195,7 @@ diesel::table! {
extended_card_info_config -> Nullable<Jsonb>,
is_connector_agnostic_mit_enabled -> Nullable<Bool>,
use_billing_as_payment_method_billing -> Nullable<Bool>,
+ collect_shipping_details_from_wallet_connector -> Nullable<Bool>,
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 12a507ffed9..5f5597387b1 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -344,6 +344,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::NoThirdPartySdkSessionResponse,
api_models::payments::SecretInfoToInitiateSdk,
api_models::payments::ApplePayPaymentRequest,
+ api_models::payments::ApplePayBillingContactFields,
+ api_models::payments::ApplePayShippingContactFields,
+ api_models::payments::ApplePayAddressParameters,
api_models::payments::AmountInfo,
api_models::payments::ProductType,
api_models::payments::GooglePayWalletData,
@@ -388,6 +391,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::payments::GooglePaySessionResponse,
+ api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
api_models::payments::SepaBankTransferInstructions,
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 4fcdd76992e..667bc90fe45 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -6995,6 +6995,73 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
+ (
+ "shipping.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.first_name".to_string(),
+ display_name: "shipping_first_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.last_name".to_string(),
+ display_name: "shipping_last_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserShippingAddressState,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserShippingAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserShippingAddressLine1,
+ value: None,
+ }
+ ),
]
),
common: HashMap::new(),
@@ -7082,6 +7149,73 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
+ (
+ "shipping.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.first_name".to_string(),
+ display_name: "shipping_first_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.last_name".to_string(),
+ display_name: "shipping_last_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserShippingAddressState,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserShippingAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserShippingAddressLine1,
+ value: None,
+ }
+ ),
]
),
common: HashMap::new(),
@@ -7184,6 +7318,73 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
+ (
+ "shipping.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.first_name".to_string(),
+ display_name: "shipping_first_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.last_name".to_string(),
+ display_name: "shipping_last_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserShippingAddressState,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserShippingAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserShippingAddressLine1,
+ value: None,
+ }
+ ),
]
),
common: HashMap::new(),
@@ -7411,6 +7612,73 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
+ (
+ "shipping.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.first_name".to_string(),
+ display_name: "shipping_first_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.last_name".to_string(),
+ display_name: "shipping_last_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserShippingAddressState,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserShippingAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserShippingAddressLine1,
+ value: None,
+ }
+ ),
]
),
common: HashMap::new(),
@@ -7436,7 +7704,77 @@ impl Default for super::settings::RequiredFields {
enums::Connector::Stripe,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "shipping.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.first_name".to_string(),
+ display_name: "shipping_first_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.last_name".to_string(),
+ display_name: "shipping_last_name".to_string(),
+ field_type: enums::FieldType::UserShippingName,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserShippingAddressState,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserShippingAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserShippingAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "shipping.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "shipping.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserShippingAddressLine1,
+ value: None,
+ }
+ ),
+ ]
+ ),
common: HashMap::new(),
}
),
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index 251a928c09e..d1dbb9d92e7 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -539,6 +539,7 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<BluesnapWalletTokenRespons
supported_networks: Some(payment_request_data.supported_networks),
merchant_identifier: Some(session_token_data.merchant_identifier),
required_billing_contact_fields: None,
+ required_shipping_contact_fields: None,
}),
connector: "bluesnap".to_string(),
delayed_session_token: false,
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 686858008b6..b04b8cb4745 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -551,6 +551,7 @@ impl<F>
supported_networks: None,
merchant_identifier: None,
required_billing_contact_fields: None,
+ required_shipping_contact_fields: None,
},
),
connector: "payme".to_string(),
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index 7f84e301916..db225585f41 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -1224,6 +1224,7 @@ pub fn get_apple_pay_session<F, T>(
total: apple_pay_init_result.total.into(),
merchant_identifier: None,
required_billing_contact_fields: None,
+ required_shipping_contact_fields: None,
}),
connector: "trustpay".to_string(),
delayed_session_token: true,
@@ -1281,6 +1282,12 @@ pub fn get_google_pay_session<F, T>(
.collect(),
transaction_info: google_pay_init_result.transaction_info.into(),
secrets: Some((*secrets).clone().into()),
+ shipping_address_required: false,
+ email_required: false,
+ shipping_address_parameters:
+ api_models::payments::GpayShippingAddressParameters {
+ phone_number_required: false,
+ },
},
),
))),
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 422b88ee9ef..288de66de07 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -441,6 +441,7 @@ pub async fn update_business_profile_cascade(
authentication_connector_details: None,
extended_card_info_config: None,
use_billing_as_payment_method_billing: None,
+ collect_shipping_details_from_wallet_connector: None,
};
let update_futures = business_profiles.iter().map(|business_profile| async {
@@ -1693,6 +1694,8 @@ pub async fn update_business_profile(
})?,
extended_card_info_config,
use_billing_as_payment_method_billing: request.use_billing_as_payment_method_billing,
+ collect_shipping_details_from_wallet_connector: request
+ .collect_shipping_details_from_wallet_connector,
};
let updated_business_profile = db
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 8c946630c8a..833f18f6afd 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2192,6 +2192,7 @@ pub async fn list_payment_methods(
let mut bank_transfer_consolidated_hm =
HashMap::<api_enums::PaymentMethodType, Vec<String>>::new();
+ // All the required fields will be stored here and later filtered out based on business profile config
let mut required_fields_hm = HashMap::<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<String, RequiredFieldInfo>>,
@@ -2230,6 +2231,31 @@ pub async fn list_payment_methods(
}
}
+ let should_send_shipping_details =
+ business_profile.clone().and_then(|business_profile| {
+ business_profile
+ .collect_shipping_details_from_wallet_connector
+ });
+
+ // Remove shipping fields from required fields based on business profile configuration
+ if should_send_shipping_details != Some(true) {
+ let shipping_variants =
+ api_enums::FieldType::get_shipping_variants();
+
+ let keys_to_be_removed = required_fields_hs
+ .iter()
+ .filter(|(_key, value)| {
+ shipping_variants.contains(&value.field_type)
+ })
+ .map(|(key, _value)| key.to_string())
+ .collect::<Vec<_>>();
+
+ keys_to_be_removed.iter().for_each(|key_to_be_removed| {
+ required_fields_hs.remove(key_to_be_removed);
+ });
+ }
+
+ // get the config, check the enums while adding
{
for (key, val) in &mut required_fields_hs {
let temp = req_val
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 578b8d80302..af286984d61 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -298,6 +298,7 @@ where
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
+ &business_profile,
)
.await?;
@@ -367,6 +368,7 @@ where
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
+ &business_profile,
)
.await?;
@@ -399,6 +401,7 @@ where
frm_info.as_ref().and_then(|fi| fi.suggested_action),
#[cfg(not(feature = "frm"))]
None,
+ &business_profile,
)
.await?;
};
@@ -452,6 +455,7 @@ where
payment_data,
&customer,
session_surcharge_details,
+ &business_profile,
))
.await?
}
@@ -1400,6 +1404,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, Ctx>(
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
@@ -1598,7 +1603,13 @@ where
// and rely on previous status set in router_data
router_data.status = payment_data.payment_attempt.status;
router_data
- .decide_flows(state, &connector, call_connector_action, connector_request)
+ .decide_flows(
+ state,
+ &connector,
+ call_connector_action,
+ connector_request,
+ business_profile,
+ )
.await
} else {
Ok(router_data)
@@ -1660,6 +1671,7 @@ pub async fn call_multiple_connectors_service<F, Op, Req, Ctx>(
mut payment_data: PaymentData<F>,
customer: &Option<domain::Customer>,
session_surcharge_details: Option<api::SessionSurchargeDetails>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<PaymentData<F>>
where
Op: Debug,
@@ -1723,6 +1735,7 @@ where
&session_connector_data.connector,
CallConnectorAction::Trigger,
None,
+ business_profile,
);
join_handlers.push(res);
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index e1bd785830e..a8425896dd7 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -21,7 +21,7 @@ use crate::{
},
routes::AppState,
services,
- types::{self, api, domain},
+ types::{self, api, domain, storage},
};
#[async_trait]
@@ -46,6 +46,7 @@ pub trait Feature<F, T> {
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self>
where
Self: Sized,
diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs
index ffa11fdb0f5..92f815f6b5f 100644
--- a/crates/router/src/core/payments/flows/approve_flow.rs
+++ b/crates/router/src/core/payments/flows/approve_flow.rs
@@ -8,7 +8,7 @@ use crate::{
},
routes::AppState,
services,
- types::{self, api, domain},
+ types::{self, api, domain, storage},
};
#[async_trait]
@@ -51,6 +51,7 @@ impl Feature<api::Approve, types::PaymentsApproveData>
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index b2773ea9aaf..a770454b204 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -14,7 +14,7 @@ use crate::{
logger,
routes::{metrics, AppState},
services,
- types::{self, api, domain},
+ types::{self, api, domain, storage},
};
#[async_trait]
@@ -63,6 +63,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index 5f802a0bbe8..0e90ab40b69 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -8,7 +8,7 @@ use crate::{
},
routes::{metrics, AppState},
services,
- types::{self, api, domain},
+ types::{self, api, domain, storage},
};
#[async_trait]
@@ -50,6 +50,7 @@ impl Feature<api::Void, types::PaymentsCancelData>
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
metrics::PAYMENT_CANCEL_COUNT.add(
&metrics::CONTEXT,
diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs
index 56ae6500c35..b979eb2a337 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -8,7 +8,7 @@ use crate::{
},
routes::AppState,
services,
- types::{self, api, domain},
+ types::{self, api, domain, storage},
};
#[async_trait]
@@ -51,6 +51,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData>
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
diff --git a/crates/router/src/core/payments/flows/complete_authorize_flow.rs b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
index 667fa3feed0..4e9bf47232f 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -8,7 +8,7 @@ use crate::{
},
routes::{metrics, AppState},
services,
- types::{self, api, domain},
+ types::{self, api, domain, storage},
utils::OptionExt,
};
@@ -65,6 +65,7 @@ impl Feature<api::CompleteAuthorize, types::CompleteAuthorizeData>
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
diff --git a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
index e702483022c..716228d73f7 100644
--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
@@ -8,7 +8,7 @@ use crate::{
},
routes::AppState,
services,
- types::{self, api, domain},
+ types::{self, api, domain, storage},
};
#[async_trait]
@@ -58,6 +58,7 @@ impl Feature<api::IncrementalAuthorization, types::PaymentsIncrementalAuthorizat
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index f410b65f076..d1e2e4b0abe 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -10,7 +10,7 @@ use crate::{
},
routes::AppState,
services::{self, logger},
- types::{self, api, domain},
+ types::{self, api, domain, storage},
};
#[async_trait]
@@ -54,6 +54,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs
index 89c1585fca1..726993aa7fa 100644
--- a/crates/router/src/core/payments/flows/reject_flow.rs
+++ b/crates/router/src/core/payments/flows/reject_flow.rs
@@ -8,7 +8,7 @@ use crate::{
},
routes::AppState,
services,
- types::{self, api, domain},
+ types::{self, api, domain, storage},
};
#[async_trait]
@@ -50,6 +50,7 @@ impl Feature<api::Reject, types::PaymentsRejectData>
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index c83c73f7624..e0837be2512 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -16,7 +16,7 @@ use crate::{
types::{
self,
api::{self, enums},
- domain,
+ domain, storage,
},
utils::OptionExt,
};
@@ -59,6 +59,7 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
metrics::SESSION_TOKEN_CREATED.add(
&metrics::CONTEXT,
@@ -68,8 +69,14 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio
connector.connector_name.to_string(),
)],
);
- self.decide_flow(state, connector, Some(true), call_connector_action)
- .await
+ self.decide_flow(
+ state,
+ connector,
+ Some(true),
+ call_connector_action,
+ business_profile,
+ )
+ .await
}
async fn add_access_token<'a>(
@@ -173,6 +180,7 @@ async fn create_applepay_session_token(
state: &routes::AppState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<types::PaymentsSessionRouterData> {
let delayed_response = is_session_response_delayed(state, connector);
if delayed_response {
@@ -286,17 +294,36 @@ async fn create_applepay_session_token(
let billing_variants = enums::FieldType::get_billing_variants();
- let required_billing_contact_fields = if is_dynamic_fields_required(
+ let required_billing_contact_fields = is_dynamic_fields_required(
&state.conf.required_fields,
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
&connector.connector_name,
billing_variants,
- ) {
- Some(vec!["postalAddress".to_string()])
- } else {
- None
- };
+ )
+ .then_some(payment_types::ApplePayBillingContactFields(vec![
+ payment_types::ApplePayAddressParameters::PostalAddress,
+ ]));
+
+ let required_shipping_contact_fields =
+ if business_profile.collect_shipping_details_from_wallet_connector == Some(true) {
+ let shipping_variants = enums::FieldType::get_shipping_variants();
+
+ is_dynamic_fields_required(
+ &state.conf.required_fields,
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::ApplePay,
+ &connector.connector_name,
+ shipping_variants,
+ )
+ .then_some(payment_types::ApplePayShippingContactFields(vec![
+ payment_types::ApplePayAddressParameters::PostalAddress,
+ payment_types::ApplePayAddressParameters::Phone,
+ payment_types::ApplePayAddressParameters::Email,
+ ]))
+ } else {
+ None
+ };
// Get apple pay payment request
let applepay_payment_request = get_apple_pay_payment_request(
@@ -306,6 +333,7 @@ async fn create_applepay_session_token(
apple_pay_session_request.merchant_identifier.as_str(),
merchant_business_country,
required_billing_contact_fields,
+ required_shipping_contact_fields,
)?;
let applepay_session_request = build_apple_pay_session_request(
@@ -406,7 +434,8 @@ fn get_apple_pay_payment_request(
session_data: types::PaymentsSessionData,
merchant_identifier: &str,
merchant_business_country: Option<api_models::enums::CountryAlpha2>,
- required_billing_contact_fields: Option<Vec<String>>,
+ required_billing_contact_fields: Option<payment_types::ApplePayBillingContactFields>,
+ required_shipping_contact_fields: Option<payment_types::ApplePayShippingContactFields>,
) -> RouterResult<payment_types::ApplePayPaymentRequest> {
let applepay_payment_request = payment_types::ApplePayPaymentRequest {
country_code: merchant_business_country.or(session_data.country).ok_or(
@@ -420,6 +449,7 @@ fn get_apple_pay_payment_request(
supported_networks: Some(payment_request_data.supported_networks),
merchant_identifier: Some(merchant_identifier.to_string()),
required_billing_contact_fields,
+ required_shipping_contact_fields,
};
Ok(applepay_payment_request)
}
@@ -463,6 +493,7 @@ fn create_gpay_session_token(
state: &routes::AppState,
router_data: &types::PaymentsSessionRouterData,
connector: &api::ConnectorData,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<types::PaymentsSessionRouterData> {
let connector_metadata = router_data.connector_meta_data.clone();
let delayed_response = is_session_response_delayed(state, connector);
@@ -546,6 +577,21 @@ fn create_gpay_session_token(
})?,
};
+ let required_shipping_contact_fields =
+ if business_profile.collect_shipping_details_from_wallet_connector == Some(true) {
+ let shipping_variants = enums::FieldType::get_shipping_variants();
+
+ is_dynamic_fields_required(
+ &state.conf.required_fields,
+ enums::PaymentMethod::Wallet,
+ enums::PaymentMethodType::GooglePay,
+ &connector.connector_name,
+ shipping_variants,
+ )
+ } else {
+ false
+ };
+
Ok(types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: payment_types::SessionToken::GooglePay(Box::new(
@@ -560,6 +606,12 @@ fn create_gpay_session_token(
},
delayed_session_token: false,
secrets: None,
+ shipping_address_required: required_shipping_contact_fields,
+ email_required: required_shipping_contact_fields,
+ shipping_address_parameters:
+ api_models::payments::GpayShippingAddressParameters {
+ phone_number_required: required_shipping_contact_fields,
+ },
},
),
)),
@@ -597,11 +649,14 @@ impl types::PaymentsSessionRouterData {
connector: &api::ConnectorData,
_confirm: Option<bool>,
call_connector_action: payments::CallConnectorAction,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
match connector.get_token {
- api::GetToken::GpayMetadata => create_gpay_session_token(state, self, connector),
+ api::GetToken::GpayMetadata => {
+ create_gpay_session_token(state, self, connector, business_profile)
+ }
api::GetToken::ApplePayMetadata => {
- create_applepay_session_token(state, self, connector).await
+ create_applepay_session_token(state, self, connector, business_profile).await
}
api::GetToken::Connector => {
let connector_integration: services::BoxedConnectorIntegration<
diff --git a/crates/router/src/core/payments/flows/setup_mandate_flow.rs b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
index 59f7ee17551..cdadb355d4a 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -11,7 +11,7 @@ use crate::{
},
routes::AppState,
services,
- types::{self, api, domain},
+ types::{self, api, domain, storage},
};
#[async_trait]
@@ -55,6 +55,7 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
+ _business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<Self> {
let connector_integration: services::BoxedConnectorIntegration<
'_,
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 58c58ffaef8..489580e5b7f 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -45,6 +45,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData, Ctx>(
validate_result: &operations::ValidateResult<'_>,
schedule_time: Option<time::PrimitiveDateTime>,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
F: Clone + Send + Sync,
@@ -97,6 +98,7 @@ where
schedule_time,
true,
frm_suggestion,
+ business_profile,
)
.await?;
}
@@ -142,6 +144,7 @@ where
//this is an auto retry payment, but not step-up
false,
frm_suggestion,
+ business_profile,
)
.await?;
@@ -281,6 +284,7 @@ pub async fn do_retry<F, ApiRequest, FData, Ctx>(
schedule_time: Option<time::PrimitiveDateTime>,
is_step_up: bool,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
+ business_profile: &storage::business_profile::BusinessProfile,
) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
where
F: Clone + Send + Sync,
@@ -318,6 +322,7 @@ where
schedule_time,
api::HeaderPayload::default(),
frm_suggestion,
+ business_profile,
)
.await
}
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 3449838164b..894e09ab60e 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -265,6 +265,7 @@ pub async fn update_business_profile_active_algorithm_ref(
authentication_connector_details: None,
extended_card_info_config: None,
use_billing_as_payment_method_billing: None,
+ collect_shipping_details_from_wallet_connector: None,
};
db.update_business_profile_by_profile_id(current_business_profile, business_profile_update)
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 262999af949..fcbd97d5cb1 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -182,6 +182,8 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
use_billing_as_payment_method_billing: request
.use_billing_as_payment_method_billing
.or(Some(true)),
+ collect_shipping_details_from_wallet_connector: request
+ .collect_shipping_details_from_wallet_connector,
})
}
}
diff --git a/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/down.sql b/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/down.sql
new file mode 100644
index 00000000000..c2ffc7cff85
--- /dev/null
+++ b/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE business_profile DROP COLUMN IF EXISTS collect_shipping_details_from_wallet_connector;
\ No newline at end of file
diff --git a/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/up.sql b/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/up.sql
new file mode 100644
index 00000000000..f949c81213c
--- /dev/null
+++ b/migrations/2024-05-09-130152_collect_shipping_details_from_wallet_connector/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS collect_shipping_details_from_wallet_connector BOOLEAN DEFAULT FALSE;
\ No newline at end of file
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index d9061baebb3..b5c453c2397 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -4963,6 +4963,20 @@
}
]
},
+ "ApplePayAddressParameters": {
+ "type": "string",
+ "enum": [
+ "postalAddress",
+ "phone",
+ "email"
+ ]
+ },
+ "ApplePayBillingContactFields": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApplePayAddressParameters"
+ }
+ },
"ApplePayPaymentRequest": {
"type": "object",
"required": [
@@ -5001,11 +5015,19 @@
"nullable": true
},
"required_billing_contact_fields": {
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "The required billing contact fields for connector",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ApplePayBillingContactFields"
+ }
+ ],
+ "nullable": true
+ },
+ "required_shipping_contact_fields": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ApplePayShippingContactFields"
+ }
+ ],
"nullable": true
}
}
@@ -5028,6 +5050,12 @@
}
]
},
+ "ApplePayShippingContactFields": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/ApplePayAddressParameters"
+ }
+ },
"ApplePayThirdPartySdkData": {
"type": "object"
},
@@ -6735,6 +6763,11 @@
"type": "boolean",
"description": "Whether to use the billing details passed when creating the intent as payment method billing",
"nullable": true
+ },
+ "collect_shipping_details_from_wallet_connector": {
+ "type": "boolean",
+ "description": "A boolean value to indicate if cusomter shipping details needs to be sent for wallets payments",
+ "nullable": true
}
},
"additionalProperties": false
@@ -9094,6 +9127,64 @@
}
}
},
+ {
+ "type": "string",
+ "enum": [
+ "user_shipping_name"
+ ]
+ },
+ {
+ "type": "string",
+ "enum": [
+ "user_shipping_address_line1"
+ ]
+ },
+ {
+ "type": "string",
+ "enum": [
+ "user_shipping_address_line2"
+ ]
+ },
+ {
+ "type": "string",
+ "enum": [
+ "user_shipping_address_city"
+ ]
+ },
+ {
+ "type": "string",
+ "enum": [
+ "user_shipping_address_pincode"
+ ]
+ },
+ {
+ "type": "string",
+ "enum": [
+ "user_shipping_address_state"
+ ]
+ },
+ {
+ "type": "object",
+ "required": [
+ "user_shipping_address_country"
+ ],
+ "properties": {
+ "user_shipping_address_country": {
+ "type": "object",
+ "required": [
+ "options"
+ ],
+ "properties": {
+ "options": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ },
{
"type": "string",
"enum": [
@@ -9335,6 +9426,9 @@
"type": "object",
"required": [
"merchant_info",
+ "shipping_address_required",
+ "email_required",
+ "shipping_address_parameters",
"allowed_payment_methods",
"transaction_info",
"delayed_session_token",
@@ -9345,6 +9439,17 @@
"merchant_info": {
"$ref": "#/components/schemas/GpayMerchantInfo"
},
+ "shipping_address_required": {
+ "type": "boolean",
+ "description": "Is shipping address required"
+ },
+ "email_required": {
+ "type": "boolean",
+ "description": "Is email required"
+ },
+ "shipping_address_parameters": {
+ "$ref": "#/components/schemas/GpayShippingAddressParameters"
+ },
"allowed_payment_methods": {
"type": "array",
"items": {
@@ -9531,6 +9636,18 @@
}
]
},
+ "GpayShippingAddressParameters": {
+ "type": "object",
+ "required": [
+ "phone_number_required"
+ ],
+ "properties": {
+ "phone_number_required": {
+ "type": "boolean",
+ "description": "Is shipping phone number required"
+ }
+ }
+ },
"GpayTokenParameters": {
"type": "object",
"required": [
|
2024-05-09T18:15:24Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
This change is required as part of the one click checkout where in which we expect apple pay to collect the shipping details from the customer and pass it in the confirm call with the payment_data.
In order for apple pay to collect the shipping details from customer we need to pass `"requiredShippingContactFields": ["postalAddress", "phone", "email"]` in the `/session` call. Hence we need to have a validation in the backend that checks for the business profile config (`collect_shipping_details_from_wallet_connector`) fields and pass the `required_shipping_contact_fields` to sdk.
Similarly for google_pay we need to pass the below fields for shipping details.
```
"shipping_address_required": true,
"email_required": true,
"shipping_address_parameters": {
"phone_number_required": true
},
```
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
-> Create a MCA for cybersource enable `google_pay` and `apple_pay`
-> Update a field in `business_profile`
```
curl --location 'http://localhost:8080/account/merchant_1715276947/business_profile/pro_DnFkGi1RPLPSmJKy54Ib' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"collect_shipping_details_from_wallet_connector": true
}'
```
-> Apple pay payment create with confirm false
```
{
"amount": 650,
"currency": "USD",
"confirm": false,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "custhype1232",
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://google.com",
"email": "something@gmail.com",
"name": "Joseph Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "wallet",
"payment_method_type": "apple_pay",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data":"eyJkYXRhIjoiQ1ZoTGd5RGU3TzZjdFlhWHFiVWFONFZvRjBCQjhTbDZsenlXYUdCKzhKcXlic2hYVGxoNEFEcTZYb0t6ZWVSVGwvcUp6NDIvUFMwcmMxMCtqSyt5Z1F5NnlkT25EcnVDeVpkaVU4SWFGOEtOS2hJMFFKOU9JTk9aWFlYR0VzZEczNXlVNzcrQ0k1dk5lUjJiK1gyUXZTVTMzSjlOczJuTFRXZHpwb1VUSHJKU1RiSmFmTTlxYjlZOHZuZS9vZUdHQkV1ZU9DQWQxcFhjRE54SEl2dlc5Z0x3WXRPVldKZUEvUnh5MEdsb0VISng3VEhqUEVQUGJwMkVVZjRMQXZQOGlJSEpmUjM0THdEUVBIdmNSeW9nalRJSzJqOXZjUGRqS2xBSG1LUm5wZlhvWkY4VE16ZUJ6eWhGb0dKY3ZRa3JMc216OEcxTXowZGxlV2VmU2V0TkYxT1NMaldCdExrUXpvWG5xdU1ZeExMenU2SkxPZ1E5ejN1OStFNGQ2NHRZS1NYYlZBWGRKNXRMNTdvbSIsInNpZ25hdHVyZSI6Ik1JQUdDU3FHU0liM0RRRUhBcUNBTUlBQ0FRRXhEVEFMQmdsZ2hrZ0JaUU1FQWdFd2dBWUpLb1pJaHZjTkFRY0JBQUNnZ0RDQ0ErTXdnZ09Jb0FNQ0FRSUNDRXd3UVVsUm5WUTJNQW9HQ0NxR1NNNDlCQU1DTUhveExqQXNCZ05WQkFNTUpVRndjR3hsSUVGd2NHeHBZMkYwYVc5dUlFbHVkR1ZuY21GMGFXOXVJRU5CSUMwZ1J6TXhKakFrQmdOVkJBc01IVUZ3Y0d4bElFTmxjblJwWm1sallYUnBiMjRnUVhWMGFHOXlhWFI1TVJNd0VRWURWUVFLREFwQmNIQnNaU0JKYm1NdU1Rc3dDUVlEVlFRR0V3SlZVekFlRncweE9UQTFNVGd3TVRNeU5UZGFGdzB5TkRBMU1UWXdNVE15TlRkYU1GOHhKVEFqQmdOVkJBTU1IR1ZqWXkxemJYQXRZbkp2YTJWeUxYTnBaMjVmVlVNMExWQlNUMFF4RkRBU0JnTlZCQXNNQzJsUFV5QlRlWE4wWlcxek1STXdFUVlEVlFRS0RBcEJjSEJzWlNCSmJtTXVNUXN3Q1FZRFZRUUdFd0pWVXpCWk1CTUdCeXFHU000OUFnRUdDQ3FHU000OUF3RUhBMElBQk1JVmQrM3Ixc2V5SVk5bzNYQ1FvU0dOeDdDOWJ5d29QWVJnbGRsSzlLVkJHNE5DRHRnUjgwQitnek1mSEZURDkrc3lJTmE2MWRUdjlKS0ppVDU4RHhPamdnSVJNSUlDRFRBTUJnTlZIUk1CQWY4RUFqQUFNQjhHQTFVZEl3UVlNQmFBRkNQeVNjUlBrK1R2SitiRTlpaHNQNks3L1M1TE1FVUdDQ3NHQVFVRkJ3RUJCRGt3TnpBMUJnZ3JCZ0VGQlFjd0FZWXBhSFIwY0RvdkwyOWpjM0F1WVhCd2JHVXVZMjl0TDI5amMzQXdOQzFoY0hCc1pXRnBZMkV6TURJd2dnRWRCZ05WSFNBRWdnRVVNSUlCRURDQ0FRd0dDU3FHU0liM1kyUUZBVENCL2pDQnd3WUlLd1lCQlFVSEFnSXdnYllNZ2JOU1pXeHBZVzVqWlNCdmJpQjBhR2x6SUdObGNuUnBabWxqWVhSbElHSjVJR0Z1ZVNCd1lYSjBlU0JoYzNOMWJXVnpJR0ZqWTJWd2RHRnVZMlVnYjJZZ2RHaGxJSFJvWlc0Z1lYQndiR2xqWVdKc1pTQnpkR0Z1WkdGeVpDQjBaWEp0Y3lCaGJtUWdZMjl1WkdsMGFXOXVjeUJ2WmlCMWMyVXNJR05sY25ScFptbGpZWFJsSUhCdmJHbGplU0JoYm1RZ1kyVnlkR2xtYVdOaGRHbHZiaUJ3Y21GamRHbGpaU0J6ZEdGMFpXMWxiblJ6TGpBMkJnZ3JCZ0VGQlFjQ0FSWXFhSFIwY0RvdkwzZDNkeTVoY0hCc1pTNWpiMjB2WTJWeWRHbG1hV05oZEdWaGRYUm9iM0pwZEhrdk1EUUdBMVVkSHdRdE1Dc3dLYUFub0NXR0kyaDBkSEE2THk5amNtd3VZWEJ3YkdVdVkyOXRMMkZ3Y0d4bFlXbGpZVE11WTNKc01CMEdBMVVkRGdRV0JCU1VWOXR2MVhTQmhvbUpkaTkrVjRVSDU1dFlKREFPQmdOVkhROEJBZjhFQkFNQ0I0QXdEd1lKS29aSWh2ZGpaQVlkQkFJRkFEQUtCZ2dxaGtqT1BRUURBZ05KQURCR0FpRUF2Z2xYSCtjZUhuTmJWZVd2ckxUSEwrdEVYekFZVWlMSEpSQUN0aDY5YjFVQ0lRRFJpelVLWGRiZGJyRjBZRFd4SHJMT2g4K2o1cTlzdllPQWlRM0lMTjJxWXpDQ0F1NHdnZ0oxb0FNQ0FRSUNDRWx0TDc4Nm1OcVhNQW9HQ0NxR1NNNDlCQU1DTUdjeEd6QVpCZ05WQkFNTUVrRndjR3hsSUZKdmIzUWdRMEVnTFNCSE16RW1NQ1FHQTFVRUN3d2RRWEJ3YkdVZ1EyVnlkR2xtYVdOaGRHbHZiaUJCZFhSb2IzSnBkSGt4RXpBUkJnTlZCQW9NQ2tGd2NHeGxJRWx1WXk0eEN6QUpCZ05WQkFZVEFsVlRNQjRYRFRFME1EVXdOakl6TkRZek1Gb1hEVEk1TURVd05qSXpORFl6TUZvd2VqRXVNQ3dHQTFVRUF3d2xRWEJ3YkdVZ1FYQndiR2xqWVhScGIyNGdTVzUwWldkeVlYUnBiMjRnUTBFZ0xTQkhNekVtTUNRR0ExVUVDd3dkUVhCd2JHVWdRMlZ5ZEdsbWFXTmhkR2x2YmlCQmRYUm9iM0pwZEhreEV6QVJCZ05WQkFvTUNrRndjR3hsSUVsdVl5NHhDekFKQmdOVkJBWVRBbFZUTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFOEJjUmhCblhaSVhWR2w0bGdRZDI2SUNpNzk1N3JrM2dqZnhMaytFelZ0Vm1Xeld1SXRDWGRnMGlUbnU2Q1AxMkY4Nkl5M2E3Wm5DK3lPZ3BoUDlVUmFPQjl6Q0I5REJHQmdnckJnRUZCUWNCQVFRNk1EZ3dOZ1lJS3dZQkJRVUhNQUdHS21oMGRIQTZMeTl2WTNOd0xtRndjR3hsTG1OdmJTOXZZM053TURRdFlYQndiR1Z5YjI5MFkyRm5NekFkQmdOVkhRNEVGZ1FVSS9KSnhFK1Q1TzhuNXNUMktHdy9vcnY5TGtzd0R3WURWUjBUQVFIL0JBVXdBd0VCL3pBZkJnTlZIU01FR0RBV2dCUzdzTjZoV0RPSW1xU0ttZDYrdmV1djJzc2txekEzQmdOVkhSOEVNREF1TUN5Z0txQW9oaVpvZEhSd09pOHZZM0pzTG1Gd2NHeGxMbU52YlM5aGNIQnNaWEp2YjNSallXY3pMbU55YkRBT0JnTlZIUThCQWY4RUJBTUNBUVl3RUFZS0tvWklodmRqWkFZQ0RnUUNCUUF3Q2dZSUtvWkl6ajBFQXdJRFp3QXdaQUl3T3M5eWcxRVdtYkdHK3pYRFZzcGl2L1FYN2RrUGRVMmlqcjd4bklGZVFyZUorSmozbTFtZm1OVkJEWStkNmNMK0FqQXlMZFZFSWJDakJYZHNYZk00TzVCbi9SZDhMQ0Z0bGsvR2NtbUNFbTlVK0hwOUc1bkxtd21KSVdFR21ROEpraDBBQURHQ0FZZ3dnZ0dFQWdFQk1JR0dNSG94TGpBc0JnTlZCQU1NSlVGd2NHeGxJRUZ3Y0d4cFkyRjBhVzl1SUVsdWRHVm5jbUYwYVc5dUlFTkJJQzBnUnpNeEpqQWtCZ05WQkFzTUhVRndjR3hsSUVObGNuUnBabWxqWVhScGIyNGdRWFYwYUc5eWFYUjVNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVFzd0NRWURWUVFHRXdKVlV3SUlUREJCU1ZHZFZEWXdDd1lKWUlaSUFXVURCQUlCb0lHVE1CZ0dDU3FHU0liM0RRRUpBekVMQmdrcWhraUc5dzBCQndFd0hBWUpLb1pJaHZjTkFRa0ZNUThYRFRJME1ETXhOREE1TkRNeU0xb3dLQVlKS29aSWh2Y05BUWswTVJzdNTdMRElUVUQwcVI3RHd5SGx1VG0xMjJCejA5c2FzMkJVWitFRTlVPSIsImVwaGVtZXJhbFB1YmxpY0tleSI6Ik1Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBoMkNUKytubXZpYjU3YWNJZmVKTjFCQmJyZUEveG84N2p1b0xETDFnS1IvYy9wRDZYK0xKSGRYUGJnMFBIT3pYYjJFYm5RR1ZWYmZIWHRkQzBYTTdBPT0iLCJ0cmFuc2FjdGlvbklkIjoiMjBlYzhlM2I2N2YyYmNmMDExMDVmODAwNmEwNWFmNTRiNjBkZDIwMzgyOTdlMmExMmI0Y2FlNDY0ODhjYjZhOSJ9LCJ2ZXJzaW9uIjoiRUNfdjEifQ==",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "55CC32D7BF7890B9064433F15B9F23F849CF84AFD01E4E65DD8ADE306300E9D8"
}
}
}
}
```
-> Make a `/session` call
```
curl --location 'http://localhost:8080/payments/session_tokens' \
--header 'Content-Type: application/json' \
--header 'api-key: api_key' \
--data '{
"payment_id": "pay_oit9SUYrdsYlI0WvCh1L",
"wallets": [],
"client_secret": "pay_oit9SUYrdsYlI0WvCh1L_secret_N61PV7OLGKa7PI0dv2Wo"
}'
```
Required shipping details set for `apple_pay` in the session call
<img width="1146" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/37e47236-0d72-4a5b-9c29-22bb64c049c1">
Required shipping details set for `google_pay` in the session call
<img width="1180" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/160df64f-17ed-46a1-b258-912fdf940a59">
List payment method list for merchant
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=pay_vJbV82f2bSFHZyTTex4X_secret_sSognYwAhzqMANozUw34' \
--header 'Accept: application/json' \
--header 'api-key: api_key'
```
<img width="1170" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/bada5464-7c09-4868-a4d2-57141af19608">
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f5d1201ac9e99ba5f8af7bb44504d6392744eb10
| ||
juspay/hyperswitch
|
juspay__hyperswitch-4595
|
Bug: [Feature] Add tenant-ID as a field to all KafkaStore events
### Context
In-order to support multi-tenancy we need to store data partioned via tenant-id.
In order to do that for kafka events we need to pass tenant-id as a field in the generated kafka events
We can use the KafkaStore field added in #4512 to add them to events in Kafka
### Approach
1. Add a new field in `KafkaEvent` struct representing tenant_id
```rust
#[derive(serde::Serialize, Debug)]
struct KafkaEvent<'a, T: KafkaMessage> {
#[serde(flatten)]
event: &'a T,
sign_flag: i32,
tenant_id: TenantID
}
```
Alternate approaches can be discussed in the issue
|
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index a64e3cc7e38..15a0b2e2046 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -76,7 +76,7 @@ use crate::{
},
};
-#[derive(Clone, Serialize)]
+#[derive(Debug, Clone, Serialize)]
pub struct TenantID(pub String);
#[derive(Clone)]
@@ -413,7 +413,11 @@ impl DisputeInterface for KafkaStore {
) -> CustomResult<storage::Dispute, errors::StorageError> {
let dispute = self.diesel_store.insert_dispute(dispute_new).await?;
- if let Err(er) = self.kafka_producer.log_dispute(&dispute, None).await {
+ if let Err(er) = self
+ .kafka_producer
+ .log_dispute(&dispute, None, self.tenant_id.clone())
+ .await
+ {
logger::error!(message="Failed to add analytics entry for Dispute {dispute:?}", error_message=?er);
};
@@ -466,7 +470,7 @@ impl DisputeInterface for KafkaStore {
.await?;
if let Err(er) = self
.kafka_producer
- .log_dispute(&dispute_new, Some(this))
+ .log_dispute(&dispute_new, Some(this), self.tenant_id.clone())
.await
{
logger::error!(message="Failed to add analytics entry for Dispute {dispute_new:?}", error_message=?er);
@@ -1109,7 +1113,7 @@ impl PaymentAttemptInterface for KafkaStore {
if let Err(er) = self
.kafka_producer
- .log_payment_attempt(&attempt, None)
+ .log_payment_attempt(&attempt, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er)
@@ -1131,7 +1135,7 @@ impl PaymentAttemptInterface for KafkaStore {
if let Err(er) = self
.kafka_producer
- .log_payment_attempt(&attempt, Some(this))
+ .log_payment_attempt(&attempt, Some(this), self.tenant_id.clone())
.await
{
logger::error!(message="Failed to log analytics event for payment attempt {attempt:?}", error_message=?er)
@@ -1311,7 +1315,7 @@ impl PaymentIntentInterface for KafkaStore {
if let Err(er) = self
.kafka_producer
- .log_payment_intent(&intent, Some(this))
+ .log_payment_intent(&intent, Some(this), self.tenant_id.clone())
.await
{
logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er);
@@ -1331,7 +1335,11 @@ impl PaymentIntentInterface for KafkaStore {
.insert_payment_intent(new, storage_scheme)
.await?;
- if let Err(er) = self.kafka_producer.log_payment_intent(&intent, None).await {
+ if let Err(er) = self
+ .kafka_producer
+ .log_payment_intent(&intent, None, self.tenant_id.clone())
+ .await
+ {
logger::error!(message="Failed to add analytics entry for Payment Intent {intent:?}", error_message=?er);
};
@@ -1558,6 +1566,7 @@ impl PayoutAttemptInterface for KafkaStore {
.log_payout(
&KafkaPayout::from_storage(payouts, &updated_payout_attempt),
Some(KafkaPayout::from_storage(payouts, this)),
+ self.tenant_id.clone(),
)
.await
{
@@ -1582,6 +1591,7 @@ impl PayoutAttemptInterface for KafkaStore {
.log_payout(
&KafkaPayout::from_storage(payouts, &payout_attempt_new),
None,
+ self.tenant_id.clone(),
)
.await
{
@@ -1639,6 +1649,7 @@ impl PayoutsInterface for KafkaStore {
.log_payout(
&KafkaPayout::from_storage(&payout, payout_attempt),
Some(KafkaPayout::from_storage(this, payout_attempt)),
+ self.tenant_id.clone(),
)
.await
{
@@ -1903,7 +1914,11 @@ impl RefundInterface for KafkaStore {
.update_refund(this.clone(), refund, storage_scheme)
.await?;
- if let Err(er) = self.kafka_producer.log_refund(&refund, Some(this)).await {
+ if let Err(er) = self
+ .kafka_producer
+ .log_refund(&refund, Some(this), self.tenant_id.clone())
+ .await
+ {
logger::error!(message="Failed to insert analytics event for Refund Update {refund?}", error_message=?er);
}
Ok(refund)
@@ -1931,7 +1946,11 @@ impl RefundInterface for KafkaStore {
) -> CustomResult<storage::Refund, errors::StorageError> {
let refund = self.diesel_store.insert_refund(new, storage_scheme).await?;
- if let Err(er) = self.kafka_producer.log_refund(&refund, None).await {
+ if let Err(er) = self
+ .kafka_producer
+ .log_refund(&refund, None, self.tenant_id.clone())
+ .await
+ {
logger::error!(message="Failed to insert analytics event for Refund Create {refund?}", error_message=?er);
}
Ok(refund)
@@ -2504,7 +2523,7 @@ impl BatchSampleDataInterface for KafkaStore {
for payment_intent in payment_intents_list.iter() {
let _ = self
.kafka_producer
- .log_payment_intent(payment_intent, None)
+ .log_payment_intent(payment_intent, None, self.tenant_id.clone())
.await;
}
Ok(payment_intents_list)
@@ -2525,7 +2544,7 @@ impl BatchSampleDataInterface for KafkaStore {
for payment_attempt in payment_attempts_list.iter() {
let _ = self
.kafka_producer
- .log_payment_attempt(payment_attempt, None)
+ .log_payment_attempt(payment_attempt, None, self.tenant_id.clone())
.await;
}
Ok(payment_attempts_list)
@@ -2542,7 +2561,10 @@ impl BatchSampleDataInterface for KafkaStore {
.await?;
for refund in refunds_list.iter() {
- let _ = self.kafka_producer.log_refund(refund, None).await;
+ let _ = self
+ .kafka_producer
+ .log_refund(refund, None, self.tenant_id.clone())
+ .await;
}
Ok(refunds_list)
}
@@ -2562,7 +2584,7 @@ impl BatchSampleDataInterface for KafkaStore {
for payment_intent in payment_intents_list.iter() {
let _ = self
.kafka_producer
- .log_payment_intent_delete(payment_intent)
+ .log_payment_intent_delete(payment_intent, self.tenant_id.clone())
.await;
}
Ok(payment_intents_list)
@@ -2583,7 +2605,7 @@ impl BatchSampleDataInterface for KafkaStore {
for payment_attempt in payment_attempts_list.iter() {
let _ = self
.kafka_producer
- .log_payment_attempt_delete(payment_attempt)
+ .log_payment_attempt_delete(payment_attempt, self.tenant_id.clone())
.await;
}
@@ -2601,7 +2623,10 @@ impl BatchSampleDataInterface for KafkaStore {
.await?;
for refund in refunds_list.iter() {
- let _ = self.kafka_producer.log_refund_delete(refund).await;
+ let _ = self
+ .kafka_producer
+ .log_refund_delete(refund, self.tenant_id.clone())
+ .await;
}
Ok(refunds_list)
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index ba9806b29d1..58657c59fd8 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -30,6 +30,7 @@ use crate::types::storage::Dispute;
// Using message queue result here to avoid confusion with Kafka result provided by library
pub type MQResult<T> = CustomResult<T, KafkaError>;
+use crate::db::kafka_store::TenantID;
pub trait KafkaMessage
where
@@ -54,19 +55,22 @@ struct KafkaEvent<'a, T: KafkaMessage> {
#[serde(flatten)]
event: &'a T,
sign_flag: i32,
+ tenant_id: TenantID,
}
impl<'a, T: KafkaMessage> KafkaEvent<'a, T> {
- fn new(event: &'a T) -> Self {
+ fn new(event: &'a T, tenant_id: TenantID) -> Self {
Self {
event,
sign_flag: 1,
+ tenant_id,
}
}
- fn old(event: &'a T) -> Self {
+ fn old(event: &'a T, tenant_id: TenantID) -> Self {
Self {
event,
sign_flag: -1,
+ tenant_id,
}
}
}
@@ -266,28 +270,33 @@ impl KafkaProducer {
&self,
attempt: &PaymentAttempt,
old_attempt: Option<PaymentAttempt>,
+ tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_attempt {
- self.log_event(&KafkaEvent::old(&KafkaPaymentAttempt::from_storage(
- &negative_event,
- )))
+ self.log_event(&KafkaEvent::old(
+ &KafkaPaymentAttempt::from_storage(&negative_event),
+ tenant_id.clone(),
+ ))
.attach_printable_lazy(|| {
format!("Failed to add negative attempt event {negative_event:?}")
})?;
};
- self.log_event(&KafkaEvent::new(&KafkaPaymentAttempt::from_storage(
- attempt,
- )))
+ self.log_event(&KafkaEvent::new(
+ &KafkaPaymentAttempt::from_storage(attempt),
+ tenant_id.clone(),
+ ))
.attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}"))
}
pub async fn log_payment_attempt_delete(
&self,
delete_old_attempt: &PaymentAttempt,
+ tenant_id: TenantID,
) -> MQResult<()> {
- self.log_event(&KafkaEvent::old(&KafkaPaymentAttempt::from_storage(
- delete_old_attempt,
- )))
+ self.log_event(&KafkaEvent::old(
+ &KafkaPaymentAttempt::from_storage(delete_old_attempt),
+ tenant_id.clone(),
+ ))
.attach_printable_lazy(|| {
format!("Failed to add negative attempt event {delete_old_attempt:?}")
})
@@ -297,48 +306,69 @@ impl KafkaProducer {
&self,
intent: &PaymentIntent,
old_intent: Option<PaymentIntent>,
+ tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_intent {
- self.log_event(&KafkaEvent::old(&KafkaPaymentIntent::from_storage(
- &negative_event,
- )))
+ self.log_event(&KafkaEvent::old(
+ &KafkaPaymentIntent::from_storage(&negative_event),
+ tenant_id.clone(),
+ ))
.attach_printable_lazy(|| {
format!("Failed to add negative intent event {negative_event:?}")
})?;
};
- self.log_event(&KafkaEvent::new(&KafkaPaymentIntent::from_storage(intent)))
- .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))
+ self.log_event(&KafkaEvent::new(
+ &KafkaPaymentIntent::from_storage(intent),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))
}
pub async fn log_payment_intent_delete(
&self,
delete_old_intent: &PaymentIntent,
+ tenant_id: TenantID,
) -> MQResult<()> {
- self.log_event(&KafkaEvent::old(&KafkaPaymentIntent::from_storage(
- delete_old_intent,
- )))
+ self.log_event(&KafkaEvent::old(
+ &KafkaPaymentIntent::from_storage(delete_old_intent),
+ tenant_id.clone(),
+ ))
.attach_printable_lazy(|| {
format!("Failed to add negative intent event {delete_old_intent:?}")
})
}
- pub async fn log_refund(&self, refund: &Refund, old_refund: Option<Refund>) -> MQResult<()> {
+ pub async fn log_refund(
+ &self,
+ refund: &Refund,
+ old_refund: Option<Refund>,
+ tenant_id: TenantID,
+ ) -> MQResult<()> {
if let Some(negative_event) = old_refund {
- self.log_event(&KafkaEvent::old(&KafkaRefund::from_storage(
- &negative_event,
- )))
+ self.log_event(&KafkaEvent::old(
+ &KafkaRefund::from_storage(&negative_event),
+ tenant_id.clone(),
+ ))
.attach_printable_lazy(|| {
format!("Failed to add negative refund event {negative_event:?}")
})?;
};
- self.log_event(&KafkaEvent::new(&KafkaRefund::from_storage(refund)))
- .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))
+ self.log_event(&KafkaEvent::new(
+ &KafkaRefund::from_storage(refund),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))
}
- pub async fn log_refund_delete(&self, delete_old_refund: &Refund) -> MQResult<()> {
- self.log_event(&KafkaEvent::old(&KafkaRefund::from_storage(
- delete_old_refund,
- )))
+ pub async fn log_refund_delete(
+ &self,
+ delete_old_refund: &Refund,
+ tenant_id: TenantID,
+ ) -> MQResult<()> {
+ self.log_event(&KafkaEvent::old(
+ &KafkaRefund::from_storage(delete_old_refund),
+ tenant_id.clone(),
+ ))
.attach_printable_lazy(|| {
format!("Failed to add negative refund event {delete_old_refund:?}")
})
@@ -348,17 +378,22 @@ impl KafkaProducer {
&self,
dispute: &Dispute,
old_dispute: Option<Dispute>,
+ tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_dispute {
- self.log_event(&KafkaEvent::old(&KafkaDispute::from_storage(
- &negative_event,
- )))
+ self.log_event(&KafkaEvent::old(
+ &KafkaDispute::from_storage(&negative_event),
+ tenant_id.clone(),
+ ))
.attach_printable_lazy(|| {
format!("Failed to add negative dispute event {negative_event:?}")
})?;
};
- self.log_event(&KafkaEvent::new(&KafkaDispute::from_storage(dispute)))
- .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))
+ self.log_event(&KafkaEvent::new(
+ &KafkaDispute::from_storage(dispute),
+ tenant_id.clone(),
+ ))
+ .attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))
}
#[cfg(feature = "payouts")]
@@ -366,20 +401,25 @@ impl KafkaProducer {
&self,
payout: &KafkaPayout<'_>,
old_payout: Option<KafkaPayout<'_>>,
+ tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_payout {
- self.log_event(&KafkaEvent::old(&negative_event))
+ self.log_event(&KafkaEvent::old(&negative_event, tenant_id.clone()))
.attach_printable_lazy(|| {
format!("Failed to add negative payout event {negative_event:?}")
})?;
};
- self.log_event(&KafkaEvent::new(payout))
+ self.log_event(&KafkaEvent::new(payout, tenant_id.clone()))
.attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}"))
}
#[cfg(feature = "payouts")]
- pub async fn log_payout_delete(&self, delete_old_payout: &KafkaPayout<'_>) -> MQResult<()> {
- self.log_event(&KafkaEvent::old(delete_old_payout))
+ pub async fn log_payout_delete(
+ &self,
+ delete_old_payout: &KafkaPayout<'_>,
+ tenant_id: TenantID,
+ ) -> MQResult<()> {
+ self.log_event(&KafkaEvent::old(delete_old_payout, tenant_id.clone()))
.attach_printable_lazy(|| {
format!("Failed to add negative payout event {delete_old_payout:?}")
})
|
2024-05-09T04:56:02Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
#4595
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Add TenantID to the KafkaEvent struct and add the extra param to the KafkaEvent constructor
- Made changes to the required placed
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
- Supporting multi-tenancy
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
<img width="973" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/aaed9da0-ab3c-4161-afb2-51a752fdf2f3">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f3115c45114c1445456af229f11ca19459c9536d
|
<img width="973" alt="image" src="https://github.com/juspay/hyperswitch/assets/21202349/aaed9da0-ab3c-4161-afb2-51a752fdf2f3">
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4605
|
Bug: [FEATURE] [BAMBORA] Audit Fixes for connector Bambora
### Feature Description
Following code improvements need to be done for connector Bambora:
- Optional fields that are being passed for payments request need to be removed
- 2XX and 4XX Error response should be handled properly
- Separate try_from should be used for all the flows
- Unwanted configs need to be removed
- Default case handling needs to be removed
### Possible Implementation
Following code improvements need to be done for connector Bambora:
- Optional fields that are being passed for payments request need to be removed
- 2XX and 4XX Error response should be handled properly
- Separate try_from should be used for all the flows
- Unwanted configs need to be removed
- Default case handling needs to be removed
### Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### Are you willing to submit a PR?
Yes, I am willing to submit a PR!
|
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 61d74863422..d9e7ec58f75 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -398,26 +398,9 @@ merchant_secret="Source verification key"
payment_method_type = "CartesBancaires"
[[bambora.debit]]
payment_method_type = "UnionPay"
-[[bambora.wallet]]
- payment_method_type = "apple_pay"
-[[bambora.wallet]]
- payment_method_type = "paypal"
[bambora.connector_auth.BodyKey]
api_key="Passcode"
key1="Merchant Id"
-[bambora.connector_webhook_details]
-merchant_secret="Source verification key"
-[bambora.metadata.apple_pay.session_token_data]
-certificate="Merchant Certificate (Base64 Encoded)"
-certificate_keys="Merchant PrivateKey (Base64 Encoded)"
-merchant_identifier="Apple Merchant Identifier"
-display_name="Display Name"
-initiative="Domain"
-initiative_context="Domain Name"
-[bambora.metadata.apple_pay.payment_request_data]
-supported_networks=["visa","masterCard","amex","discover"]
-merchant_capabilities=["supports3DS"]
-label="apple"
[bankofamerica]
[[bankofamerica.credit]]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 10cd9d6f7cf..202bce64c1f 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -416,27 +416,9 @@ merchant_config_currency="Currency"
payment_method_type = "CartesBancaires"
[[bambora.debit]]
payment_method_type = "UnionPay"
-[[bambora.wallet]]
- payment_method_type = "apple_pay"
-[[bambora.wallet]]
- payment_method_type = "paypal"
[bambora.connector_auth.BodyKey]
api_key="Passcode"
key1="Merchant Id"
-[bambora.connector_webhook_details]
-merchant_secret="Source verification key"
-
-[bambora.metadata.apple_pay.session_token_data]
-certificate="Merchant Certificate (Base64 Encoded)"
-certificate_keys="Merchant PrivateKey (Base64 Encoded)"
-merchant_identifier="Apple Merchant Identifier"
-display_name="Display Name"
-initiative="Domain"
-initiative_context="Domain Name"
-[bambora.metadata.apple_pay.payment_request_data]
-supported_networks=["visa","masterCard","amex","discover"]
-merchant_capabilities=["supports3DS"]
-label="apple"
[bankofamerica]
[[bankofamerica.credit]]
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 7f4935d4887..450e14d1080 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -398,26 +398,9 @@ merchant_secret="Source verification key"
payment_method_type = "CartesBancaires"
[[bambora.debit]]
payment_method_type = "UnionPay"
-[[bambora.wallet]]
- payment_method_type = "apple_pay"
-[[bambora.wallet]]
- payment_method_type = "paypal"
[bambora.connector_auth.BodyKey]
api_key="Passcode"
key1="Merchant Id"
-[bambora.connector_webhook_details]
-merchant_secret="Source verification key"
-[bambora.metadata.apple_pay.session_token_data]
-certificate="Merchant Certificate (Base64 Encoded)"
-certificate_keys="Merchant PrivateKey (Base64 Encoded)"
-merchant_identifier="Apple Merchant Identifier"
-display_name="Display Name"
-initiative="Domain"
-initiative_context="Domain Name"
-[bambora.metadata.apple_pay.payment_request_data]
-supported_networks=["visa","masterCard","amex","discover"]
-merchant_capabilities=["supports3DS"]
-label="apple"
[bankofamerica]
[[bankofamerica.credit]]
diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs
index 7ff352416cd..684c5ddc1ce 100644
--- a/crates/router/src/connector/bambora.rs
+++ b/crates/router/src/connector/bambora.rs
@@ -10,10 +10,7 @@ use transformers as bambora;
use super::utils::RefundsRequestData;
use crate::{
configs::settings,
- connector::{
- utils as connector_utils,
- utils::{to_connector_meta, PaymentsAuthorizeRequestData, PaymentsSyncRequestData},
- },
+ connector::{utils as connector_utils, utils::to_connector_meta},
core::{
errors::{self, CustomResult},
payments,
@@ -36,6 +33,20 @@ use crate::{
#[derive(Debug, Clone)]
pub struct Bambora;
+impl api::Payment for Bambora {}
+impl api::PaymentToken for Bambora {}
+impl api::PaymentAuthorize for Bambora {}
+impl api::PaymentVoid for Bambora {}
+impl api::MandateSetup for Bambora {}
+impl api::ConnectorAccessToken for Bambora {}
+impl api::PaymentSync for Bambora {}
+impl api::PaymentCapture for Bambora {}
+impl api::PaymentSession for Bambora {}
+impl api::Refund for Bambora {}
+impl api::RefundExecute for Bambora {}
+impl api::RefundSync for Bambora {}
+impl api::PaymentsCompleteAuthorize for Bambora {}
+
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bambora
where
Self: ConnectorIntegration<Flow, Request, Response>,
@@ -102,8 +113,9 @@ impl ConnectorCommon for Bambora {
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
- message: response.message,
- reason: Some(serde_json::to_string(&response.details).unwrap_or_default()),
+ message: serde_json::to_string(&response.details)
+ .unwrap_or(crate::consts::NO_ERROR_MESSAGE.to_string()),
+ reason: Some(response.message),
attempt_status: None,
connector_transaction_id: None,
})
@@ -126,10 +138,6 @@ impl ConnectorValidation for Bambora {
}
}
-impl api::Payment for Bambora {}
-
-impl api::PaymentToken for Bambora {}
-
impl
ConnectorIntegration<
api::PaymentMethodToken,
@@ -140,7 +148,17 @@ impl
// Not Implemented (R)
}
-impl api::MandateSetup for Bambora {}
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Bambora
+{
+}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Bambora
+{
+ //TODO: implement sessions flow
+}
+
impl
ConnectorIntegration<
api::SetupMandate,
@@ -164,14 +182,12 @@ impl
}
}
-impl api::PaymentVoid for Bambora {}
-
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
for Bambora
{
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
+ req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
@@ -183,82 +199,68 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
+ _req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let connector_payment_id = req.request.connector_transaction_id.clone();
- Ok(format!(
- "{}/v1/payments/{}{}",
- self.base_url(connectors),
- connector_payment_id,
- "/void"
- ))
+ Ok(format!("{}{}", self.base_url(connectors), "/v1/payments"))
}
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
+ req: &types::PaymentsAuthorizeRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = bambora::BamboraRouterData::try_from((
&self.get_currency_unit(),
- req.request
- .currency
- .ok_or(errors::ConnectorError::MissingRequiredField {
- field_name: "Currency",
- })?,
- req.request
- .amount
- .ok_or(errors::ConnectorError::MissingRequiredField {
- field_name: "Amount",
- })?,
+ req.request.currency,
+ req.request.amount,
req,
))?;
- let connector_req = bambora::BamboraVoidRequest::try_from(connector_router_data)?;
-
+ let connector_req = bambora::BamboraPaymentsRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
+ req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
.attach_default_headers()
- .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
- .set_body(self.get_request_body(req, connectors)?)
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &types::PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: bambora::BamboraResponse = res
.response
- .parse_struct("bambora PaymentsResponse")
+ .parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
-
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
- types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- },
- bambora::PaymentFlow::Void,
- ))
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
}
fn get_error_response(
@@ -270,14 +272,99 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl api::ConnectorAccessToken for Bambora {}
-
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Bambora
+impl
+ ConnectorIntegration<
+ api::CompleteAuthorize,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ > for Bambora
{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let meta: bambora::BamboraMeta = to_connector_meta(req.request.connector_meta.clone())?;
+ Ok(format!(
+ "{}/v1/payments/{}{}",
+ self.base_url(connectors),
+ meta.three_d_session_data,
+ "/continue"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = bambora::BamboraThreedsContinueRequest::try_from(&req.request)?;
+
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCompleteAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCompleteAuthorizeRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
+ let response: bambora::BamboraPaymentsResponse = res
+ .response
+ .parse_struct("BamboraPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
-impl api::PaymentSync for Bambora {}
impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
for Bambora
{
@@ -304,10 +391,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
- "{}{}{}",
+ "{}/v1/payments/{connector_payment_id}",
self.base_url(connectors),
- "/v1/payments/",
- connector_payment_id
))
}
@@ -340,7 +425,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let response: bambora::BamboraResponse = res
+ let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -348,19 +433,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
- types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- },
- get_payment_flow(data.request.is_auto_capture()?),
- ))
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
-impl api::PaymentCapture for Bambora {}
impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
for Bambora
{
@@ -382,11 +463,9 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
- "{}{}{}{}",
+ "{}/v1/payments/{}/completions",
self.base_url(connectors),
- "/v1/payments/",
req.request.connector_transaction_id,
- "/completions"
))
}
@@ -431,7 +510,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: bambora::BamboraResponse = res
+ let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("Bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -439,14 +518,11 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
- types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- },
- bambora::PaymentFlow::Capture,
- ))
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
@@ -459,22 +535,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl api::PaymentSession for Bambora {}
-
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Bambora
-{
- //TODO: implement sessions flow
-}
-
-impl api::PaymentAuthorize for Bambora {}
-
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
for Bambora
{
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
@@ -486,72 +552,77 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
+ req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(format!("{}{}", self.base_url(connectors), "/v1/payments"))
+ let connector_payment_id = req.request.connector_transaction_id.clone();
+ Ok(format!(
+ "{}/v1/payments/{}/void",
+ self.base_url(connectors),
+ connector_payment_id,
+ ))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ req: &types::PaymentsCancelRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = bambora::BamboraRouterData::try_from((
&self.get_currency_unit(),
- req.request.currency,
- req.request.amount,
+ req.request
+ .currency
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "Currency",
+ })?,
+ req.request
+ .amount
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "Amount",
+ })?,
req,
))?;
- let connector_req = bambora::BamboraPaymentsRequest::try_from(connector_router_data)?;
+ let connector_req = bambora::BamboraVoidRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
+ req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
.method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &types::PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
- let response: bambora::BamboraResponse = res
+ ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: bambora::BamboraPaymentsResponse = res
.response
- .parse_struct("PaymentIntentResponse")
+ .parse_struct("bambora PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from((
- types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- },
- get_payment_flow(data.request.is_auto_capture()?),
- ))
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
@@ -564,9 +635,22 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl api::Refund for Bambora {}
-impl api::RefundExecute for Bambora {}
-impl api::RefundSync for Bambora {}
+impl services::ConnectorRedirectResponse for Bambora {
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ _json_payload: Option<serde_json::Value>,
+ action: services::PaymentAction,
+ ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ match action {
+ services::PaymentAction::PSync
+ | services::PaymentAction::CompleteAuthorize
+ | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ Ok(payments::CallConnectorAction::Trigger)
+ }
+ }
+ }
+}
impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
for Bambora
@@ -590,11 +674,9 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
- "{}{}{}{}",
+ "{}/v1/payments/{}/returns",
self.base_url(connectors),
- "/v1/payments/",
connector_payment_id,
- "/returns"
))
}
@@ -684,9 +766,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
let _connector_payment_id = req.request.connector_transaction_id.clone();
let connector_refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
- "{}{}{}",
+ "{}/v1/payments/{}",
self.base_url(connectors),
- "/v1/payments/",
connector_refund_id
))
}
@@ -760,126 +841,3 @@ impl api::IncomingWebhook for Bambora {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
-
-pub fn get_payment_flow(is_auto_capture: bool) -> bambora::PaymentFlow {
- if is_auto_capture {
- bambora::PaymentFlow::Capture
- } else {
- bambora::PaymentFlow::Authorize
- }
-}
-
-impl services::ConnectorRedirectResponse for Bambora {
- fn get_flow_type(
- &self,
- _query_params: &str,
- _json_payload: Option<serde_json::Value>,
- action: services::PaymentAction,
- ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
- match action {
- services::PaymentAction::PSync
- | services::PaymentAction::CompleteAuthorize
- | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
- Ok(payments::CallConnectorAction::Trigger)
- }
- }
- }
-}
-
-impl api::PaymentsCompleteAuthorize for Bambora {}
-
-impl
- ConnectorIntegration<
- api::CompleteAuthorize,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- > for Bambora
-{
- fn get_headers(
- &self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- self.build_headers(req, connectors)
- }
-
- fn get_content_type(&self) -> &'static str {
- self.common_get_content_type()
- }
-
- fn get_url(
- &self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- let meta: bambora::BamboraMeta = to_connector_meta(req.request.connector_meta.clone())?;
- Ok(format!(
- "{}/v1/payments/{}{}",
- self.base_url(connectors),
- meta.three_d_session_data,
- "/continue"
- ))
- }
-
- fn get_request_body(
- &self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<RequestContent, errors::ConnectorError> {
- let connector_req = bambora::BamboraThreedsContinueRequest::try_from(&req.request)?;
-
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
-
- fn build_request(
- &self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCompleteAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .headers(types::PaymentsCompleteAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
- self, req, connectors,
- )?)
- .build();
- Ok(Some(request))
- }
-
- fn handle_response(
- &self,
- data: &types::PaymentsCompleteAuthorizeRouterData,
- event_builder: Option<&mut ConnectorEvent>,
- res: Response,
- ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
- let response: bambora::BamboraResponse = res
- .response
- .parse_struct("Bambora PaymentsResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
-
- types::RouterData::try_from((
- types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- },
- bambora::PaymentFlow::Capture,
- ))
- .change_context(errors::ConnectorError::ResponseHandlingFailed)
- }
-
- fn get_error_response(
- &self,
- res: Response,
- event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res, event_builder)
- }
-}
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index 77c91af709d..61ed8bd1ee4 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -7,7 +7,8 @@ use serde::{Deserialize, Deserializer, Serialize};
use crate::{
connector::utils::{
AddressDetailsData, BrowserInformationData, CardData as OtherCardData,
- PaymentsAuthorizeRequestData, RouterData,
+ PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
+ PaymentsSyncRequestData, RouterData,
},
consts,
core::errors,
@@ -135,16 +136,24 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
domain::PaymentMethodData::Card(req_card) => {
- let three_ds = match item.router_data.auth_type {
- enums::AuthenticationType::ThreeDs => Some(ThreeDSecure {
- enabled: true,
- browser: get_browser_info(item.router_data)?,
- version: Some(2),
- auth_required: Some(true),
- }),
- enums::AuthenticationType::NoThreeDs => None,
+ let (three_ds, customer_ip) = match item.router_data.auth_type {
+ enums::AuthenticationType::ThreeDs => (
+ Some(ThreeDSecure {
+ enabled: true,
+ browser: get_browser_info(item.router_data)?,
+ version: Some(2),
+ auth_required: Some(true),
+ }),
+ Some(
+ item.router_data
+ .request
+ .get_browser_info()?
+ .get_ip_address()?,
+ ),
+ ),
+ enums::AuthenticationType::NoThreeDs => (None, None),
};
- let bambora_card = BamboraCard {
+ let card = BamboraCard {
name: item.router_data.get_billing_address()?.get_full_name()?,
expiry_year: req_card.get_card_expiry_year_2_digit()?,
number: req_card.card_number,
@@ -153,19 +162,31 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora
three_d_secure: three_ds,
complete: item.router_data.request.is_auto_capture()?,
};
- let browser_info = item.router_data.request.get_browser_info()?;
+
Ok(Self {
order_number: item.router_data.connector_request_reference_id.clone(),
amount: item.amount,
payment_method: PaymentMethod::Card,
- card: bambora_card,
- customer_ip: browser_info
- .ip_address
- .map(|ip_address| Secret::new(format!("{ip_address}"))),
+ card,
+ customer_ip,
term_url: item.router_data.request.complete_authorize_url.clone(),
})
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ domain::PaymentMethodData::CardRedirect(_)
+ | domain::PaymentMethodData::Wallet(_)
+ | domain::PaymentMethodData::PayLater(_)
+ | domain::PaymentMethodData::BankRedirect(_)
+ | domain::PaymentMethodData::BankDebit(_)
+ | domain::PaymentMethodData::BankTransfer(_)
+ | domain::PaymentMethodData::Crypto(_)
+ | domain::PaymentMethodData::MandatePayment
+ | domain::PaymentMethodData::Reward
+ | domain::PaymentMethodData::Upi(_)
+ | domain::PaymentMethodData::Voucher(_)
+ | domain::PaymentMethodData::GiftCard(_)
+ | domain::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
+ }
}
}
}
@@ -200,87 +221,6 @@ impl TryFrom<&types::ConnectorAuthType> for BamboraAuthType {
}
}
-pub enum PaymentFlow {
- Authorize,
- Capture,
- Void,
-}
-
-// PaymentsResponse
-impl<F, T>
- TryFrom<(
- types::ResponseRouterData<F, BamboraResponse, T, types::PaymentsResponseData>,
- PaymentFlow,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- data: (
- types::ResponseRouterData<F, BamboraResponse, T, types::PaymentsResponseData>,
- PaymentFlow,
- ),
- ) -> Result<Self, Self::Error> {
- let flow = data.1;
- let item = data.0;
- match item.response {
- BamboraResponse::NormalTransaction(pg_response) => Ok(Self {
- status: match pg_response.approved.as_str() {
- "0" => match flow {
- PaymentFlow::Authorize => enums::AttemptStatus::AuthorizationFailed,
- PaymentFlow::Capture => enums::AttemptStatus::Failure,
- PaymentFlow::Void => enums::AttemptStatus::VoidFailed,
- },
- "1" => match flow {
- PaymentFlow::Authorize => enums::AttemptStatus::Authorized,
- PaymentFlow::Capture => enums::AttemptStatus::Charged,
- PaymentFlow::Void => enums::AttemptStatus::Voided,
- },
- &_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
- },
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- pg_response.id.to_string(),
- ),
- redirection_data: None,
- mandate_reference: None,
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: Some(pg_response.order_number.to_string()),
- incremental_authorization_allowed: None,
- }),
- ..item.data
- }),
-
- BamboraResponse::ThreeDsResponse(response) => {
- let value = url::form_urlencoded::parse(response.contents.as_bytes())
- .map(|(key, val)| [key, val].concat())
- .collect();
- let redirection_data = Some(services::RedirectForm::Html { html_data: value });
- Ok(Self {
- status: enums::AttemptStatus::AuthenticationPending,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
- redirection_data,
- mandate_reference: None,
- connector_metadata: Some(
- serde_json::to_value(BamboraMeta {
- three_d_session_data: response.three_d_session_data.expose(),
- })
- .change_context(errors::ConnectorError::ResponseHandlingFailed)?,
- ),
- network_txn_id: None,
- connector_response_reference_id: Some(
- item.data.connector_request_reference_id.to_string(),
- ),
- incremental_authorization_allowed: None,
- }),
- ..item.data
- })
- }
- }
- }
-}
-
fn str_or_i32<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
@@ -444,7 +384,7 @@ pub enum PaymentMethod {
// Capture
#[derive(Default, Debug, Clone, Serialize, PartialEq)]
pub struct BamboraPaymentsCaptureRequest {
- amount: Option<f64>,
+ amount: f64,
payment_method: PaymentMethod,
}
@@ -456,12 +396,269 @@ impl TryFrom<BamboraRouterData<&types::PaymentsCaptureRouterData>>
item: BamboraRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
Ok(Self {
- amount: Some(item.amount),
+ amount: item.amount,
payment_method: PaymentMethod::Card,
})
}
}
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BamboraResponse,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BamboraResponse,
+ types::PaymentsAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ match item.response {
+ BamboraResponse::NormalTransaction(pg_response) => Ok(Self {
+ status: if pg_response.approved.as_str() == "1" {
+ match item.data.request.is_auto_capture()? {
+ true => enums::AttemptStatus::Charged,
+ false => enums::AttemptStatus::Authorized,
+ }
+ } else {
+ match item.data.request.is_auto_capture()? {
+ true => enums::AttemptStatus::Failure,
+ false => enums::AttemptStatus::AuthorizationFailed,
+ }
+ },
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ pg_response.id.to_string(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(pg_response.order_number.to_string()),
+ incremental_authorization_allowed: None,
+ }),
+ ..item.data
+ }),
+
+ BamboraResponse::ThreeDsResponse(response) => {
+ let value = url::form_urlencoded::parse(response.contents.as_bytes())
+ .map(|(key, val)| [key, val].concat())
+ .collect();
+ let redirection_data = Some(services::RedirectForm::Html { html_data: value });
+ Ok(Self {
+ status: enums::AttemptStatus::AuthenticationPending,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::NoResponseId,
+ redirection_data,
+ mandate_reference: None,
+ connector_metadata: Some(
+ serde_json::to_value(BamboraMeta {
+ three_d_session_data: response.three_d_session_data.expose(),
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)?,
+ ),
+ network_txn_id: None,
+ connector_response_reference_id: Some(
+ item.data.connector_request_reference_id.to_string(),
+ ),
+ incremental_authorization_allowed: None,
+ }),
+ ..item.data
+ })
+ }
+ }
+ }
+}
+
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BamboraPaymentsResponse,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::CompleteAuthorizeData, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BamboraPaymentsResponse,
+ types::CompleteAuthorizeData,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: if item.response.approved.as_str() == "1" {
+ match item.data.request.is_auto_capture()? {
+ true => enums::AttemptStatus::Charged,
+ false => enums::AttemptStatus::Authorized,
+ }
+ } else {
+ match item.data.request.is_auto_capture()? {
+ true => enums::AttemptStatus::Failure,
+ false => enums::AttemptStatus::AuthorizationFailed,
+ }
+ },
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.id.to_string(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(item.response.order_number.to_string()),
+ incremental_authorization_allowed: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BamboraPaymentsResponse,
+ types::PaymentsSyncData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BamboraPaymentsResponse,
+ types::PaymentsSyncData,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: match item.data.request.is_auto_capture()? {
+ true => {
+ if item.response.approved.as_str() == "1" {
+ enums::AttemptStatus::Charged
+ } else {
+ enums::AttemptStatus::Failure
+ }
+ }
+ false => {
+ if item.response.approved.as_str() == "1" {
+ enums::AttemptStatus::Authorized
+ } else {
+ enums::AttemptStatus::AuthorizationFailed
+ }
+ }
+ },
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.id.to_string(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(item.response.order_number.to_string()),
+ incremental_authorization_allowed: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BamboraPaymentsResponse,
+ types::PaymentsCaptureData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BamboraPaymentsResponse,
+ types::PaymentsCaptureData,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: if item.response.approved.as_str() == "1" {
+ enums::AttemptStatus::Charged
+ } else {
+ enums::AttemptStatus::Failure
+ },
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.id.to_string(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(item.response.order_number.to_string()),
+ incremental_authorization_allowed: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl<F>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ BamboraPaymentsResponse,
+ types::PaymentsCancelData,
+ types::PaymentsResponseData,
+ >,
+ > for types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BamboraPaymentsResponse,
+ types::PaymentsCancelData,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: if item.response.approved.as_str() == "1" {
+ enums::AttemptStatus::Voided
+ } else {
+ enums::AttemptStatus::VoidFailed
+ },
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.id.to_string(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(item.response.order_number.to_string()),
+ incremental_authorization_allowed: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
@@ -537,10 +734,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
fn try_from(
item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
- let refund_status = match item.response.approved.as_str() {
- "0" => enums::RefundStatus::Failure,
- "1" => enums::RefundStatus::Success,
- &_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
+ let refund_status = if item.response.approved.as_str() == "1" {
+ enums::RefundStatus::Success
+ } else {
+ enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(types::RefundsResponseData {
@@ -559,10 +756,10 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
fn try_from(
item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
- let refund_status = match item.response.approved.as_str() {
- "0" => enums::RefundStatus::Failure,
- "1" => enums::RefundStatus::Success,
- &_ => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
+ let refund_status = if item.response.approved.as_str() == "1" {
+ enums::RefundStatus::Success
+ } else {
+ enums::RefundStatus::Failure
};
Ok(Self {
response: Ok(types::RefundsResponseData {
|
2024-05-09T11:01:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Following code improvements are done for connector Bambora:
- Optional fields that are being passed for payments request are removed
- 2XX and 4XX Error response are now handled properly
- Separate try_from are now used for all the flows
- Unwanted configs are removed
- Default case handling is removed
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
Following are the paths where you can find config files which have been updated:
1. `crates/connector_configs/toml/development.toml`
2. `crates/connector_configs/toml/sandbox.toml`
3. `crates/connector_configs/toml/production.toml`
## Motivation and Context
<!--
Why is this change required? What problem does it solve?
If it fixes an open issue, please link to the issue here.
If you don't have an issue, we'd recommend starting with one first so the PR
can focus on the implementation (unless it is an obvious bug or documentation fix
that will have little conversation).
-->
https://github.com/juspay/hyperswitch/issues/4605
## How did you test it?
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
All the payment flows need to be tested(except void) for cards(Non-3DS) via Bambora.
1. Payments (Automatic):
Request -
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"customer_id": "assdre1v",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"card_cvc": "123"
}
}
}'
```
Response -
```
{
"payment_id": "pay_WLq2W1Lf6nDlkSVsTfXH",
"merchant_id": "merchant_1714730521",
"status": "succeeded",
"amount": 2000,
"net_amount": 2000,
"amount_capturable": 0,
"amount_received": 2000,
"connector": "bambora",
"client_secret": "pay_WLq2W1Lf6nDlkSVsTfXH_secret_AGkc7on7LPYnS4tzNDrh",
"created": "2024-05-09T11:29:26.243Z",
"currency": "USD",
"customer_id": "assdre1v",
"customer": {
"id": "assdre1v",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "assdre1v",
"created_at": 1715254166,
"expires": 1715257766,
"secret": "epk_1b0a796b1c1d4f2ebac92c20ba7f2381"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10004856",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_WLq2W1Lf6nDlkSVsTfXH_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-09T11:44:26.243Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-09T11:29:28.588Z"
}
```
2. Payments (Manual):
Request -
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"customer_id": "assdre1v",
"capture_method": "manual",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"card_cvc": "123"
}
}
}'
```
Response -
```
{
"payment_id": "pay_xHfLlrcSjSKeOPaw1GGz",
"merchant_id": "merchant_1714730521",
"status": "requires_capture",
"amount": 2000,
"net_amount": 2000,
"amount_capturable": 2000,
"amount_received": null,
"connector": "bambora",
"client_secret": "pay_xHfLlrcSjSKeOPaw1GGz_secret_wTB68iFSUs9LuEiSJy6O",
"created": "2024-05-09T11:29:40.405Z",
"currency": "USD",
"customer_id": "assdre1v",
"customer": {
"id": "assdre1v",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "assdre1v",
"created_at": 1715254180,
"expires": 1715257780,
"secret": "epk_28013d1f51344818865586555d178f34"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10004857",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_xHfLlrcSjSKeOPaw1GGz_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-09T11:44:40.405Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-09T11:29:42.247Z"
}
```
3. Payments (Capture):
Request -
```
curl --location 'http://localhost:8080/payments/pay_Qjbk8kB5wduiuuBOvI2Y/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount_to_capture": 2000,
"statement_descriptor_name": "Joseph",
"statement_descriptor_suffix": "JS"
}'
```
Response -
```
{
"payment_id": "pay_xHfLlrcSjSKeOPaw1GGz",
"merchant_id": "merchant_1714730521",
"status": "succeeded",
"amount": 2000,
"net_amount": 2000,
"amount_capturable": 0,
"amount_received": 2000,
"connector": "bambora",
"client_secret": "pay_xHfLlrcSjSKeOPaw1GGz_secret_wTB68iFSUs9LuEiSJy6O",
"created": "2024-05-09T11:29:40.405Z",
"currency": "USD",
"customer_id": "assdre1v",
"customer": {
"id": "assdre1v",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "10004858",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_xHfLlrcSjSKeOPaw1GGz_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-09T11:44:40.405Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-09T11:30:15.379Z"
}
```
4. Refunds:
Request -
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 100,
"payment_id": "pay_xHfLlrcSjSKeOPaw1GGz",
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```
{
"refund_id": "ref_i2J7zKX1kzvU00IPSW2m",
"payment_id": "pay_xHfLlrcSjSKeOPaw1GGz",
"amount": 100,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-05-09T11:33:37.772Z",
"updated_at": "2024-05-09T11:33:37.772Z",
"connector": "bambora",
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj"
}
```
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f386f423c0e5fac55a24756d7ee7a3ce1c20fb13
|
All the payment flows need to be tested(except void) for cards(Non-3DS) via Bambora.
1. Payments (Automatic):
Request -
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"customer_id": "assdre1v",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"card_cvc": "123"
}
}
}'
```
Response -
```
{
"payment_id": "pay_WLq2W1Lf6nDlkSVsTfXH",
"merchant_id": "merchant_1714730521",
"status": "succeeded",
"amount": 2000,
"net_amount": 2000,
"amount_capturable": 0,
"amount_received": 2000,
"connector": "bambora",
"client_secret": "pay_WLq2W1Lf6nDlkSVsTfXH_secret_AGkc7on7LPYnS4tzNDrh",
"created": "2024-05-09T11:29:26.243Z",
"currency": "USD",
"customer_id": "assdre1v",
"customer": {
"id": "assdre1v",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": null,
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "assdre1v",
"created_at": 1715254166,
"expires": 1715257766,
"secret": "epk_1b0a796b1c1d4f2ebac92c20ba7f2381"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10004856",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_WLq2W1Lf6nDlkSVsTfXH_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-09T11:44:26.243Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-09T11:29:28.588Z"
}
```
2. Payments (Manual):
Request -
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"customer_id": "assdre1v",
"capture_method": "manual",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4030000010001234",
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"card_cvc": "123"
}
}
}'
```
Response -
```
{
"payment_id": "pay_xHfLlrcSjSKeOPaw1GGz",
"merchant_id": "merchant_1714730521",
"status": "requires_capture",
"amount": 2000,
"net_amount": 2000,
"amount_capturable": 2000,
"amount_received": null,
"connector": "bambora",
"client_secret": "pay_xHfLlrcSjSKeOPaw1GGz_secret_wTB68iFSUs9LuEiSJy6O",
"created": "2024-05-09T11:29:40.405Z",
"currency": "USD",
"customer_id": "assdre1v",
"customer": {
"id": "assdre1v",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "assdre1v",
"created_at": 1715254180,
"expires": 1715257780,
"secret": "epk_28013d1f51344818865586555d178f34"
},
"manual_retry_allowed": false,
"connector_transaction_id": "10004857",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_xHfLlrcSjSKeOPaw1GGz_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-09T11:44:40.405Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-09T11:29:42.247Z"
}
```
3. Payments (Capture):
Request -
```
curl --location 'http://localhost:8080/payments/pay_Qjbk8kB5wduiuuBOvI2Y/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount_to_capture": 2000,
"statement_descriptor_name": "Joseph",
"statement_descriptor_suffix": "JS"
}'
```
Response -
```
{
"payment_id": "pay_xHfLlrcSjSKeOPaw1GGz",
"merchant_id": "merchant_1714730521",
"status": "succeeded",
"amount": 2000,
"net_amount": 2000,
"amount_capturable": 0,
"amount_received": 2000,
"connector": "bambora",
"client_secret": "pay_xHfLlrcSjSKeOPaw1GGz_secret_wTB68iFSUs9LuEiSJy6O",
"created": "2024-05-09T11:29:40.405Z",
"currency": "USD",
"customer_id": "assdre1v",
"customer": {
"id": "assdre1v",
"name": null,
"email": null,
"phone": null,
"phone_country_code": null
},
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": null,
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "1234",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "403000",
"card_extended_bin": null,
"card_exp_month": "10",
"card_exp_year": "2024",
"card_holder_name": "Sundari KK",
"payment_checks": null,
"authentication_data": null
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "no_three_ds",
"statement_descriptor_name": null,
"statement_descriptor_suffix": null,
"next_action": null,
"cancellation_reason": null,
"error_code": null,
"error_message": null,
"unified_code": null,
"unified_message": null,
"payment_experience": null,
"payment_method_type": "credit",
"connector_label": null,
"business_country": null,
"business_label": "default",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": null,
"manual_retry_allowed": false,
"connector_transaction_id": "10004858",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pay_xHfLlrcSjSKeOPaw1GGz_1",
"payment_link": null,
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-05-09T11:44:40.405Z",
"fingerprint": null,
"browser_info": null,
"payment_method_id": null,
"payment_method_status": null,
"updated": "2024-05-09T11:30:15.379Z"
}
```
4. Refunds:
Request -
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 100,
"payment_id": "pay_xHfLlrcSjSKeOPaw1GGz",
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```
{
"refund_id": "ref_i2J7zKX1kzvU00IPSW2m",
"payment_id": "pay_xHfLlrcSjSKeOPaw1GGz",
"amount": 100,
"currency": "USD",
"status": "succeeded",
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"error_message": null,
"error_code": null,
"created_at": "2024-05-09T11:33:37.772Z",
"updated_at": "2024-05-09T11:33:37.772Z",
"connector": "bambora",
"profile_id": "pro_l8ERwD92l71RbPpGZZz9",
"merchant_connector_id": "mca_ybl21De1o5q31x82RpEj"
}
```
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4589
|
Bug: [Feature] Add a cargo binary for running diesel migrations locally
### Objective
Add a new binary in the `router` crate that would run migrations locally via cli i.e `cargo run migrations`.
### Context
Currently migrations are managed via the diesel_cli which rely on explicitly providing the database username/password & host,
This is a bit cumbersome when you have to provide the variables over & over again.
```bash
diesel migration --database-url postgres://$DB_USER:$DB_PASS@localhost:5432/$DB_NAME run
```
It would be somewhat easier if we could leverage [`diesel_migrations`](https://docs.rs/diesel_migrations/latest/diesel_migrations/) to read the credentials from config file / env & apply migrations.
(Open to alternative approaches as well for this)
### Outcomes
- A new rust binary that can be used for running local db migrations from file
- Updates to the local setup documentation outlining the usage of this cli tool
|
diff --git a/Cargo.lock b/Cargo.lock
index 1d6d0fc7511..8249ae4f70b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -384,12 +384,55 @@ version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
+[[package]]
+name = "anstream"
+version = "0.6.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
[[package]]
name = "anstyle"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc"
+[[package]]
+name = "anstyle-parse"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391"
+dependencies = [
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19"
+dependencies = [
+ "anstyle",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "anyhow"
version = "1.0.81"
@@ -1909,8 +1952,10 @@ version = "4.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7"
dependencies = [
+ "anstream",
"anstyle",
"clap_lex",
+ "strsim",
]
[[package]]
@@ -1940,6 +1985,12 @@ dependencies = [
"bitflags 1.3.2",
]
+[[package]]
+name = "colorchoice"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422"
+
[[package]]
name = "common_enums"
version = "0.1.0"
@@ -2016,7 +2067,7 @@ dependencies = [
"rust-ini",
"serde",
"serde_json",
- "toml",
+ "toml 0.8.12",
"yaml-rust",
]
@@ -2029,7 +2080,7 @@ dependencies = [
"indexmap 2.2.6",
"serde",
"serde_json",
- "toml",
+ "toml 0.8.12",
]
[[package]]
@@ -2039,7 +2090,7 @@ dependencies = [
"api_models",
"serde",
"serde_with",
- "toml",
+ "toml 0.8.12",
"utoipa",
]
@@ -2588,9 +2639,9 @@ checksum = "b6e854126756c496b8c81dec88f9a706b15b875c5849d4097a3854476b9fdf94"
[[package]]
name = "diesel"
-version = "2.1.5"
+version = "2.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03fc05c17098f21b89bc7d98fe1dd3cce2c11c2ad8e145f2a44fe08ed28eb559"
+checksum = "ff236accb9a5069572099f0b350a92e9560e8e63a9b8d546162f4a5e03026bb2"
dependencies = [
"bitflags 2.5.0",
"byteorder",
@@ -2604,9 +2655,9 @@ dependencies = [
[[package]]
name = "diesel_derives"
-version = "2.1.3"
+version = "2.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d02eecb814ae714ffe61ddc2db2dd03e6c49a42e269b5001355500d431cce0c"
+checksum = "14701062d6bed917b5c7103bdffaee1e4609279e240488ad24e7bd979ca6866c"
dependencies = [
"diesel_table_macro_syntax",
"proc-macro2",
@@ -2614,6 +2665,17 @@ dependencies = [
"syn 2.0.57",
]
+[[package]]
+name = "diesel_migrations"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6036b3f0120c5961381b570ee20a02432d7e2d27ea60de9578799cf9156914ac"
+dependencies = [
+ "diesel",
+ "migrations_internals",
+ "migrations_macros",
+]
+
[[package]]
name = "diesel_models"
version = "0.1.0"
@@ -3584,6 +3646,17 @@ dependencies = [
"windows-sys 0.52.0",
]
+[[package]]
+name = "hsdev"
+version = "0.1.0"
+dependencies = [
+ "clap",
+ "diesel",
+ "diesel_migrations",
+ "serde",
+ "toml 0.5.11",
+]
+
[[package]]
name = "http"
version = "0.2.12"
@@ -4020,6 +4093,12 @@ dependencies = [
"windows-sys 0.52.0",
]
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800"
+
[[package]]
name = "iso_country"
version = "0.1.4"
@@ -4396,6 +4475,27 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "migrations_internals"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f23f71580015254b020e856feac3df5878c2c7a8812297edd6c0a485ac9dada"
+dependencies = [
+ "serde",
+ "toml 0.7.8",
+]
+
+[[package]]
+name = "migrations_macros"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cce3325ac70e67bbab5bd837a31cae01f1a6db64e0e744a33cb03a543469ef08"
+dependencies = [
+ "migrations_internals",
+ "proc-macro2",
+ "quote",
+]
+
[[package]]
name = "mimalloc"
version = "0.1.39"
@@ -7370,7 +7470,7 @@ dependencies = [
"thirtyfour",
"time",
"tokio 1.37.0",
- "toml",
+ "toml 0.8.12",
]
[[package]]
@@ -7798,6 +7898,27 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "toml"
+version = "0.5.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd79e69d3b627db300ff956027cc6c3798cef26d22526befdfcd12feeb6d2257"
+dependencies = [
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_edit 0.19.15",
+]
+
[[package]]
name = "toml"
version = "0.8.12"
@@ -7827,6 +7948,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
dependencies = [
"indexmap 2.2.6",
+ "serde",
+ "serde_spanned",
"toml_datetime",
"winnow 0.5.40",
]
@@ -8243,6 +8366,12 @@ version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517"
+[[package]]
+name = "utf8parse"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
+
[[package]]
name = "utoipa"
version = "4.2.0"
diff --git a/crates/hsdev/Cargo.toml b/crates/hsdev/Cargo.toml
new file mode 100644
index 00000000000..6600d41d9fc
--- /dev/null
+++ b/crates/hsdev/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "hsdev"
+version = "0.1.0"
+license.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+description = "A simple diesel postgres migrator that uses TOML files"
+repository = "https://github.com/juspay/hyperswitch.git"
+readme = "README.md"
+
+[dependencies]
+diesel = { version = "2.1.6", features = ["postgres"] }
+diesel_migrations = "2.1.0"
+toml = "0.5"
+clap = { version = "4.1.8", features = ["derive"] }
+serde = { version = "1.0", features = ["derive"] }
diff --git a/crates/hsdev/README.md b/crates/hsdev/README.md
new file mode 100644
index 00000000000..926d9b9056f
--- /dev/null
+++ b/crates/hsdev/README.md
@@ -0,0 +1,24 @@
+# HSDEV
+
+`hsdev` is a simple diesel Postgres migration tool. It is designed to simply running a Postgres database migration with diesel.
+
+## Installing hsdev
+`hsdev` can be installed using `cargo`
+```shell
+cargo install --force --path crates/hsdev
+```
+
+## Using hsdev
+Using `hsdev` is simple. All you need to do is run the following command.
+```shell
+hsdev --toml-file [path/to/TOML/file]
+```
+
+provide `hsdev` with a TOML file containing the following keys:
+```toml
+username = "your_username"
+password = "your_password"
+dbname = "your_db_name"
+```
+
+Simply run the command and let `hsdev` handle the rest.
diff --git a/crates/hsdev/src/input_file.rs b/crates/hsdev/src/input_file.rs
new file mode 100644
index 00000000000..0d5d0a2eb0c
--- /dev/null
+++ b/crates/hsdev/src/input_file.rs
@@ -0,0 +1,26 @@
+use std::string::String;
+
+use serde::Deserialize;
+use toml::Value;
+
+#[derive(Deserialize)]
+pub struct InputData {
+ username: String,
+ password: String,
+ dbname: String,
+ host: String,
+ port: u16,
+}
+
+impl InputData {
+ pub fn read(db_table: &Value) -> Result<Self, toml::de::Error> {
+ db_table.clone().try_into()
+ }
+
+ pub fn postgres_url(&self) -> String {
+ format!(
+ "postgres://{}:{}@{}:{}/{}",
+ self.username, self.password, self.host, self.port, self.dbname
+ )
+ }
+}
diff --git a/crates/hsdev/src/main.rs b/crates/hsdev/src/main.rs
new file mode 100644
index 00000000000..e6ee9e17d44
--- /dev/null
+++ b/crates/hsdev/src/main.rs
@@ -0,0 +1,139 @@
+use clap::{Parser, ValueHint};
+use diesel::{pg::PgConnection, Connection};
+use diesel_migrations::{FileBasedMigrations, HarnessWithOutput, MigrationHarness};
+use toml::Value;
+
+mod input_file;
+
+#[derive(Parser, Debug)]
+#[command(author, version, about, long_about = None)]
+struct Args {
+ #[arg(short, long, value_hint = ValueHint::FilePath)]
+ toml_file: std::path::PathBuf,
+
+ #[arg(long, default_value_t = String::from(""))]
+ toml_table: String,
+}
+
+fn main() {
+ let args = Args::parse();
+
+ let toml_file = &args.toml_file;
+ let table_name = &args.toml_table;
+ let toml_contents = match std::fs::read_to_string(toml_file) {
+ Ok(contents) => contents,
+ Err(e) => {
+ eprintln!("Error reading TOML file: {}", e);
+ return;
+ }
+ };
+ let toml_data: Value = match toml_contents.parse() {
+ Ok(data) => data,
+ Err(e) => {
+ eprintln!("Error parsing TOML file: {}", e);
+ return;
+ }
+ };
+
+ let table = get_toml_table(table_name, &toml_data);
+
+ let input = match input_file::InputData::read(table) {
+ Ok(data) => data,
+ Err(e) => {
+ eprintln!("Error loading TOML file: {}", e);
+ return;
+ }
+ };
+
+ let db_url = input.postgres_url();
+
+ println!("Attempting to connect to {}", db_url);
+
+ let mut conn = match PgConnection::establish(&db_url) {
+ Ok(value) => value,
+ Err(_) => {
+ eprintln!("Unable to establish database connection");
+ return;
+ }
+ };
+
+ let migrations = match FileBasedMigrations::find_migrations_directory() {
+ Ok(value) => value,
+ Err(_) => {
+ eprintln!("Could not find migrations directory");
+ return;
+ }
+ };
+
+ let mut harness = HarnessWithOutput::write_to_stdout(&mut conn);
+
+ match harness.run_pending_migrations(migrations) {
+ Ok(_) => println!("Successfully ran migrations"),
+ Err(_) => eprintln!("Couldn't run migrations"),
+ };
+}
+
+pub fn get_toml_table<'a>(table_name: &'a str, toml_data: &'a Value) -> &'a Value {
+ if !table_name.is_empty() {
+ match toml_data.get(table_name) {
+ Some(value) => value,
+ None => {
+ eprintln!("Unable to find toml table: \"{}\"", &table_name);
+ std::process::abort()
+ }
+ }
+ } else {
+ toml_data
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #![allow(clippy::unwrap_used)]
+
+ use std::str::FromStr;
+
+ use toml::Value;
+
+ use crate::{get_toml_table, input_file::InputData};
+
+ #[test]
+ fn test_input_file() {
+ let toml_str = r#"username = "db_user"
+ password = "db_pass"
+ dbname = "db_name"
+ host = "localhost"
+ port = 5432"#;
+
+ let toml_value = Value::from_str(toml_str);
+ assert!(toml_value.is_ok());
+ let toml_value = toml_value.unwrap();
+
+ let toml_table = InputData::read(&toml_value);
+ assert!(toml_table.is_ok());
+ let toml_table = toml_table.unwrap();
+
+ let db_url = toml_table.postgres_url();
+ assert_eq!("postgres://db_user:db_pass@localhost:5432/db_name", db_url);
+ }
+
+ #[test]
+ fn test_given_toml() {
+ let toml_str_table = r#"[database]
+ username = "db_user"
+ password = "db_pass"
+ dbname = "db_name"
+ host = "localhost"
+ port = 5432"#;
+
+ let table_name = "database";
+ let toml_value = Value::from_str(toml_str_table).unwrap();
+ let table = get_toml_table(table_name, &toml_value);
+
+ assert!(table.is_table());
+
+ let table_name = "";
+ let table = get_toml_table(table_name, &toml_value);
+ assert!(table.is_table());
+ }
+}
|
2024-06-04T20:18:52Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR closes #4589
Created a new Rust binary in the `crates` directory which automates the Diesel migrations with Postgres. The new tool is a CLI tool that takes a path to a TOML file as an argument along with the name of a TOML table to extract Postgres database credentials from. The tool then automatically performs the migrations by utilizing `diesel_migrations` library. From our testing, we were able to set up Hyperswitch locally without using `diesel_cli` and Bash variables on WSL2 Ubuntu.
I worked on this Issue with @JamesM25 @ind1goDusk
The example below shows the application running using `cargo run` in the `hsdev` crate.
```sh
cargo run -- --toml-file ~/hyperswitch/config/development.toml --toml-table master_database
```
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Before our tool, Hyperswitch needed to be set up on local machines using a long `diesel_cli` command with Bash variables for the Postgres migration. Now we have provided a simpler and easily repeatable solution to Postgres and Diesel migrations that allows for greater modularity as you can select specific TOML files and tables to select database credentials from.
## How did you test it?
We wrote two units test on the core functionality. We tested it both on a dummy TOML file as well as in Hyperswitch repository. We were able to set up Hyperswitch locally using `hsdev` instead of `diesel_cli`.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [ ] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [x] I added unit tests for my changes where possible
|
2d31d38c1e35be99e9b0297b197bab81fa5f5030
|
We wrote two units test on the core functionality. We tested it both on a dummy TOML file as well as in Hyperswitch repository. We were able to set up Hyperswitch locally using `hsdev` instead of `diesel_cli`.
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4590
|
Bug: feat: new apis for accept invite and list merchant
- new JWT auth based api for accept invite api
- new SPT auth based api for list merchants
- send accept invite from email instead of reset password for newly invited users
|
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index 0d42d1de7d6..34375a22848 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -7,7 +7,7 @@ use crate::user_role::{
UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
- TransferOrgOwnershipRequest, UpdateUserRoleRequest,
+ MerchantSelectRequest, TransferOrgOwnershipRequest, UpdateUserRoleRequest,
};
common_utils::impl_misc_api_event_type!(
@@ -15,6 +15,7 @@ common_utils::impl_misc_api_event_type!(
GetRoleRequest,
AuthorizationInfoResponse,
UpdateUserRoleRequest,
+ MerchantSelectRequest,
AcceptInvitationRequest,
DeleteUserRoleRequest,
TransferOrgOwnershipRequest,
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 08d63d9097f..6dde3eb888a 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -97,11 +97,15 @@ pub enum UserStatus {
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct AcceptInvitationRequest {
+pub struct MerchantSelectRequest {
pub merchant_ids: Vec<String>,
// TODO: Remove this once the token only api is being used
pub need_dashboard_entry_response: Option<bool>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct AcceptInvitationRequest {
+ pub merchant_ids: Vec<String>,
+}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct DeleteUserRoleRequest {
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 83cdd1d318b..bb30d30759e 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -7,6 +7,8 @@ use diesel_models::{
user_role::UserRoleNew,
};
use error_stack::{report, ResultExt};
+#[cfg(feature = "email")]
+use external_services::email::EmailData;
use masking::{ExposeInterface, PeekInterface};
#[cfg(feature = "email")]
use router_env::env;
@@ -570,6 +572,7 @@ pub async fn invite_multiple_user(
user_from_token: auth::UserFromToken,
requests: Vec<user_api::InviteUserRequest>,
req_state: ReqState,
+ is_token_only: Option<bool>,
) -> UserResponse<Vec<InviteMultipleUserResponse>> {
if requests.len() > 10 {
return Err(report!(UserErrors::MaxInvitationsError))
@@ -577,7 +580,8 @@ pub async fn invite_multiple_user(
}
let responses = futures::future::join_all(requests.iter().map(|request| async {
- match handle_invitation(&state, &user_from_token, request, &req_state).await {
+ match handle_invitation(&state, &user_from_token, request, &req_state, is_token_only).await
+ {
Ok(response) => response,
Err(error) => InviteMultipleUserResponse {
email: request.email.clone(),
@@ -597,6 +601,7 @@ async fn handle_invitation(
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
req_state: &ReqState,
+ is_token_only: Option<bool>,
) -> UserResult<InviteMultipleUserResponse> {
let inviter_user = user_from_token.get_user_from_db(state).await?;
@@ -635,7 +640,14 @@ async fn handle_invitation(
.err()
.unwrap_or(false)
{
- handle_new_user_invitation(state, user_from_token, request, req_state.clone()).await
+ handle_new_user_invitation(
+ state,
+ user_from_token,
+ request,
+ req_state.clone(),
+ is_token_only,
+ )
+ .await
} else {
Err(UserErrors::InternalServerError.into())
}
@@ -718,6 +730,7 @@ async fn handle_new_user_invitation(
user_from_token: &auth::UserFromToken,
request: &user_api::InviteUserRequest,
req_state: ReqState,
+ is_token_only: Option<bool>,
) -> UserResult<InviteMultipleUserResponse> {
let new_user = domain::NewUser::try_from((request.clone(), user_from_token.clone()))?;
@@ -756,25 +769,36 @@ async fn handle_new_user_invitation(
})?;
let is_email_sent;
+ // TODO: Adding this to avoid clippy lints, remove this once the token only flow is being used
+ let _ = is_token_only;
+
#[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 email_contents = email_types::InviteUser {
- recipient_email: invitee_email,
- user_name: domain::UserName::new(new_user.get_name())?,
- settings: state.conf.clone(),
- subject: "You have been invited to join Hyperswitch Community!",
- merchant_id: user_from_token.merchant_id.clone(),
+ let email_contents: Box<dyn EmailData + Send + 'static> = if let Some(true) = is_token_only
+ {
+ Box::new(email_types::InviteRegisteredUser {
+ recipient_email: invitee_email,
+ user_name: domain::UserName::new(new_user.get_name())?,
+ settings: state.conf.clone(),
+ subject: "You have been invited to join Hyperswitch Community!",
+ merchant_id: user_from_token.merchant_id.clone(),
+ })
+ } else {
+ Box::new(email_types::InviteUser {
+ recipient_email: invitee_email,
+ user_name: domain::UserName::new(new_user.get_name())?,
+ settings: state.conf.clone(),
+ subject: "You have been invited to join Hyperswitch Community!",
+ merchant_id: user_from_token.merchant_id.clone(),
+ })
};
let send_email_result = state
.email_client
- .compose_and_send_email(
- Box::new(email_contents),
- state.conf.proxy.https_url.as_ref(),
- )
+ .compose_and_send_email(email_contents, state.conf.proxy.https_url.as_ref())
.await;
logger::info!(?send_email_result);
is_email_sent = send_email_result.is_ok();
@@ -1203,11 +1227,11 @@ pub async fn create_merchant_account(
pub async fn list_merchants_for_user(
state: AppState,
- user_from_token: auth::UserFromToken,
+ user_from_token: Box<dyn auth::GetUserIdFromAuth>,
) -> UserResponse<Vec<user_api::UserMerchantAccount>> {
let user_roles = state
.store
- .list_user_roles_by_user_id(user_from_token.user_id.as_str())
+ .list_user_roles_by_user_id(user_from_token.get_user_id().as_str())
.await
.change_context(UserErrors::InternalServerError)?;
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index ae20ec51ad4..0d196e1c4af 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -170,8 +170,38 @@ pub async fn transfer_org_ownership(
pub async fn accept_invitation(
state: AppState,
- user_token: auth::UserFromSinglePurposeToken,
+ user_token: auth::UserFromToken,
req: user_role_api::AcceptInvitationRequest,
+) -> UserResponse<()> {
+ futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async {
+ state
+ .store
+ .update_user_role_by_user_id_merchant_id(
+ user_token.user_id.as_str(),
+ merchant_id,
+ UserRoleUpdate::UpdateStatus {
+ status: UserStatus::Active,
+ modified_by: user_token.user_id.clone(),
+ },
+ )
+ .await
+ .map_err(|e| {
+ logger::error!("Error while accepting invitation {}", e);
+ })
+ .ok()
+ }))
+ .await
+ .into_iter()
+ .reduce(Option::or)
+ .flatten()
+ .ok_or(UserErrors::MerchantIdNotFound.into())
+ .map(|_| ApplicationResponse::StatusOk)
+}
+
+pub async fn merchant_select(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+ req: user_role_api::MerchantSelectRequest,
) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async {
state
@@ -207,7 +237,6 @@ pub async fn accept_invitation(
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
-
let response = utils::user::get_dashboard_entry_response(
&state,
user_from_db,
@@ -223,10 +252,10 @@ pub async fn accept_invitation(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn accept_invitation_token_only_flow(
+pub async fn merchant_select_token_only_flow(
state: AppState,
user_token: auth::UserFromSinglePurposeToken,
- req: user_role_api::AcceptInvitationRequest,
+ req: user_role_api::MerchantSelectRequest,
) -> UserResponse<user_api::TokenOrPayloadResponse<user_api::DashboardEntryResponse>> {
let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async {
state
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 49a8e063183..1c680b8bc8e 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1192,6 +1192,11 @@ impl User {
// TODO: Remove this endpoint once migration to /merchants/list is done
.service(web::resource("/switch/list").route(web::get().to(list_merchants_for_user)))
.service(web::resource("/merchants/list").route(web::get().to(list_merchants_for_user)))
+ // The route is utilized to select an invitation from a list of merchants in an intermediate state
+ .service(
+ web::resource("/merchants_select/list")
+ .route(web::get().to(list_merchants_for_user_with_spt)),
+ )
.service(web::resource("/permission_info").route(web::get().to(get_authorization_info)))
.service(web::resource("/update").route(web::post().to(update_user_account_details)))
.service(
@@ -1241,7 +1246,11 @@ impl User {
.service(
web::resource("/invite_multiple").route(web::post().to(invite_multiple_user)),
)
- .service(web::resource("/invite/accept").route(web::post().to(accept_invitation)))
+ .service(
+ web::resource("/invite/accept")
+ .route(web::post().to(merchant_select))
+ .route(web::put().to(accept_invitation)),
+ )
.service(web::resource("/update_role").route(web::post().to(update_user_role)))
.service(
web::resource("/transfer_ownership")
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index ee42cc50fe3..7b10247dded 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -220,6 +220,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
| Flow::AcceptInvitation
+ | Flow::MerchantSelect
| Flow::DeleteUserRole
| Flow::TransferOrgOwnership
| Flow::CreateRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index a901988e51e..6de38bd55a5 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -324,6 +324,23 @@ pub async fn list_merchants_for_user(state: web::Data<AppState>, req: HttpReques
.await
}
+pub async fn list_merchants_for_user_with_spt(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::UserMerchantAccountList;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, user, _, _| user_core::list_merchants_for_user(state, user),
+ &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
pub async fn get_user_role_details(
state: web::Data<AppState>,
req: HttpRequest,
@@ -435,14 +452,18 @@ pub async fn invite_multiple_user(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<Vec<user_api::InviteUserRequest>>,
+ query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::InviteMultipleUser;
+ let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
- user_core::invite_multiple_user,
+ |state, user, payload, req_state| {
+ user_core::invite_multiple_user(state, user, payload, req_state, is_token_only)
+ },
&auth::JWTAuth(Permission::UsersWrite),
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index d406783cc71..4239f2d3814 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -209,10 +209,29 @@ pub async fn accept_invitation(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_role_api::AcceptInvitationRequest>,
- query: web::Query<user_api::TokenOnlyQueryParam>,
) -> HttpResponse {
let flow = Flow::AcceptInvitation;
let payload = json_payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ payload,
+ |state, user, req_body, _| user_role_core::accept_invitation(state, user, req_body),
+ &auth::DashboardNoPermissionAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+pub async fn merchant_select(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<user_role_api::MerchantSelectRequest>,
+ query: web::Query<user_api::TokenOnlyQueryParam>,
+) -> HttpResponse {
+ let flow = Flow::MerchantSelect;
+ let payload = json_payload.into_inner();
let is_token_only = query.into_inner().token_only;
Box::pin(api::server_wrap(
flow,
@@ -221,9 +240,9 @@ pub async fn accept_invitation(
payload,
|state, user, req_body, _| async move {
if let Some(true) = is_token_only {
- user_role_core::accept_invitation_token_only_flow(state, user, req_body).await
+ user_role_core::merchant_select_token_only_flow(state, user, req_body).await
} else {
- user_role_core::accept_invitation(state, user, req_body).await
+ user_role_core::merchant_select(state, user, req_body).await
}
},
&auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 9aac92acd2a..c7280261c2a 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -206,6 +206,23 @@ impl AuthInfo for AuthenticationData {
}
}
+pub trait GetUserIdFromAuth {
+ fn get_user_id(&self) -> String;
+}
+
+impl GetUserIdFromAuth for UserFromToken {
+ fn get_user_id(&self) -> String {
+ self.user_id.clone()
+ }
+}
+
+#[cfg(feature = "olap")]
+impl GetUserIdFromAuth for UserFromSinglePurposeToken {
+ fn get_user_id(&self) -> String {
+ self.user_id.clone()
+ }
+}
+
#[async_trait]
pub trait AuthenticateAndFetch<T, A>
where
@@ -347,6 +364,39 @@ where
}
}
+#[cfg(feature = "olap")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<Box<dyn GetUserIdFromAuth>, A> for SinglePurposeJWTAuth
+where
+ A: AppStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(Box<dyn GetUserIdFromAuth>, AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, SinglePurposeToken>(request_headers, state).await?;
+ if payload.check_in_blacklist(state).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ if self.0 != payload.purpose {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ Ok((
+ Box::new(UserFromSinglePurposeToken {
+ user_id: payload.user_id.clone(),
+ origin: payload.origin.clone(),
+ }),
+ AuthenticationType::SinglePurposeJWT {
+ user_id: payload.user_id,
+ purpose: payload.purpose,
+ },
+ ))
+ }
+}
+
#[derive(Debug)]
pub struct AdminApiAuth;
@@ -786,6 +836,37 @@ where
}
}
+#[cfg(feature = "olap")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<Box<dyn GetUserIdFromAuth>, A> for DashboardNoPermissionAuth
+where
+ A: AppStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(Box<dyn GetUserIdFromAuth>, AuthenticationType)> {
+ let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
+ if payload.check_in_blacklist(state).await? {
+ return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
+ }
+
+ Ok((
+ Box::new(UserFromToken {
+ user_id: payload.user_id.clone(),
+ merchant_id: payload.merchant_id.clone(),
+ org_id: payload.org_id,
+ role_id: payload.role_id,
+ }),
+ AuthenticationType::MerchantJwt {
+ merchant_id: payload.merchant_id,
+ user_id: Some(payload.user_id),
+ },
+ ))
+ }
+}
+
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for DashboardNoPermissionAuth
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 9ea86167fcf..a893386ab87 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -386,6 +386,8 @@ pub enum Flow {
UpdateUserAccountDetails,
/// Accept user invitation
AcceptInvitation,
+ /// Select merchant from invitations
+ MerchantSelect,
/// Initiate external authentication for a payment
PaymentsExternalAuthentication,
/// Authorize the payment after external 3ds authentication
|
2024-05-08T13:34:50Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This PR:
- adds new route to accept invite from dashboard with JWT Auth
- adds new routes to get list of merchants to select for user, SPT Auth
- modifies to send accept invite from email instead of set password for new user in token only flow
### Additional Changes
- [x] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [ ] This PR modifies application configuration/environment variables
<!--
Provide links to the files with corresponding changes.
Following are the paths where you can find config files:
1. `config`
2. `crates/router/src/configs`
3. `loadtest/config`
-->
## Motivation and Context
Closes [#4590](https://github.com/juspay/hyperswitch/issues/4590)
## How did you test it?
**To accept invite from inside dashboard**
```
curl --location --request PUT 'http://localhost:8080/user/user/invite/accept' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"merchant_ids": [
"merchant_175173995"
]
}'
```
Response will be 200 Ok
**To get merchant select list**
```
curl --location 'http://localhost:8080/user/merchants_select/list' \
--header 'Authorization: Bearer JWT'
```
Respnse will be something like
```
[
{
"merchant_id": "merchant_1715075310",
"merchant_name": "sd",
"is_active": true,
"role_id": "merchant_view_only",
"role_name": "view_only",
"org_id": "org_BoTucsApoZG6LeGY41hZ"
},
{
"merchant_id": "merchant_1715173995",
"merchant_name": null,
"is_active": true,
"role_id": "merchant_admin",
"role_name": "admin",
"org_id": "org_fhL0yj8FWiPhnPnGR7NM"
}
]
```
For new user invitation we should send accept_invite from email not reset password email
```
curl --location 'http://localhost:8080/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data-raw '[
{
"email": "test+totp@gmail.com",
"name": "test",
"role_id": "merchant_admin"
}
]'
```
Response for email feature flag enable:
```
[
{
"email": "apoorvdixit88+ttp@gmail.com",
"is_email_sent": true
}
]
```
Also check for what email got sent in inbox.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [x] I formatted the code `cargo +nightly fmt --all`
- [x] I addressed lints thrown by `cargo clippy`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
|
f386f423c0e5fac55a24756d7ee7a3ce1c20fb13
|
**To accept invite from inside dashboard**
```
curl --location --request PUT 'http://localhost:8080/user/user/invite/accept' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"merchant_ids": [
"merchant_175173995"
]
}'
```
Response will be 200 Ok
**To get merchant select list**
```
curl --location 'http://localhost:8080/user/merchants_select/list' \
--header 'Authorization: Bearer JWT'
```
Respnse will be something like
```
[
{
"merchant_id": "merchant_1715075310",
"merchant_name": "sd",
"is_active": true,
"role_id": "merchant_view_only",
"role_name": "view_only",
"org_id": "org_BoTucsApoZG6LeGY41hZ"
},
{
"merchant_id": "merchant_1715173995",
"merchant_name": null,
"is_active": true,
"role_id": "merchant_admin",
"role_name": "admin",
"org_id": "org_fhL0yj8FWiPhnPnGR7NM"
}
]
```
For new user invitation we should send accept_invite from email not reset password email
```
curl --location 'http://localhost:8080/user/user/invite_multiple' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data-raw '[
{
"email": "test+totp@gmail.com",
"name": "test",
"role_id": "merchant_admin"
}
]'
```
Response for email feature flag enable:
```
[
{
"email": "apoorvdixit88+ttp@gmail.com",
"is_email_sent": true
}
]
```
Also check for what email got sent in inbox.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.